When we use Python's unittest for automation or unit testing, sometimes a test case needs to be executed several times depending on the combination of input and output, but a use case in UnitTest can only have one set of parameter combinations, and if you use a circular approach, In the generated test report there will be only one test case statistics, the fact that we need a set of parameters to be counted as a test case, or the use case copy N (this way who can meet the demand, the single actually maintenance too cumbersome, if there is a change, need to copy n copies), So what should we do to achieve our needs? After looking for information and Baidu, we can use the Python setattr function at run time to produce test_ at the beginning of the test case method, the script is as follows:
Import unittestfrom Test import Test_supportclass mytestcase (unittest. TestCase): def setUp (self): pass def Clear (self): pass def gettest (self, arg1, arg2): #定义的函数, Method of execution of the resulting test case pass @staticmethod def gettestfunc (Arg1, arg2): def func (self): self.gettest ( Arg1, arg2) return func def __generatetestcases (): arglists = [(' Arg11 ', ' Arg12 '), (' Arg21 ', ' Arg22 '), ( ' Arg31 ', ' arg32 ')] for the args in arglists: setattr (mytestcase, ' test_func_%s_%s '% (Args[0], args[1]), Mytestcase.gettestfunc (*args)) #通过setattr自动为TestCase类添加成员方法, the method begins with "Test_func_"
__generatetestcases () if __name__ = = ' __main__ ': Unittest.main ()
To this, we have completed the desired, on this basis can be increased parameterization, etc., to achieve the requirements of automated testing.
In Python, UnitTest uses different combinations of parameters to produce a separate test case