In Python, unittest is used to generate a separate test case based on different parameter combinations.
In some cases, you need to use different parameter combinations to test the same behavior. You want to know what to test from the test case execution result, instead of simply getting a large test case; in this case, if you only write a test case and use an embedded loop to perform the test, it is difficult to see one of the test results except errors. The key to the problem is whether there is a way to generate a test case based on different combinations of input parameters. For example, if you have 10 groups of data, you can get 10 test cases, of course, it is not applicable to writing so many test _ member functions manually. One possible idea is not to use unittest. the test _ member function method in the TestCase class box is to write the runTest member function by yourself, which requires some additional work and does not seem so "intelligent ". So how can we make the framework automatically call testcase? Our idea is to use setattr to automatically add a member function to an existing TestCase class. In order to make this method work, we need to use the static method of the class to generate a member function of the decorate class, and make the function return a test function object to register the call to add the test member function in a certain place (only before the actual execution can be done, it can be automatically executed in the module or manually called)
Code example:
Import unittest
From test import test_support
Class MyTestCase (unittest. TestCase ):
Def setUp (self ):
# Some setup code
Pass
Def clear (self ):
# Some cleanup code
Pass
Def action (self, arg1, arg2 ):
Pass
@ Staticmethod
Def getTestFunc (arg1, arg2 ):
Def func (self ):
Self. action (arg1, arg2)
Return func
Def _ generateTestCases ():
Arglists = [('arg11', 'arg12'), ('arg21', 'arg22'), ('arg31', 'arg32')]
For args in arglists:
Setattr (MyTestCase, 'test _ func _ % s _ % s' % (args [0], args [1]),
MyTestCase. getTestFunc (* args ))
_ GenerateTestCases ()
If _ name _ = '_ main __':
# Test_support.run_unittest (MyTestCase)
Unittest. main ()