How do you generate dynamic (parameterized) unit tests in python?

后端 未结 25 2160
面向向阳花
面向向阳花 2020-11-22 07:09

I have some kind of test data and want to create a unit test for each item. My first idea was to do it like this:

import unittest

l = [[\"foo\", \"a\", \"a\         


        
25条回答
  •  悲哀的现实
    2020-11-22 07:43

    load_tests is a little known mechanism introduced in 2.7 to dynamically create a TestSuite. With it, you can easily create parametrized tests.

    For example:

    import unittest
    
    class GeneralTestCase(unittest.TestCase):
        def __init__(self, methodName, param1=None, param2=None):
            super(GeneralTestCase, self).__init__(methodName)
    
            self.param1 = param1
            self.param2 = param2
    
        def runTest(self):
            pass  # Test that depends on param 1 and 2.
    
    
    def load_tests(loader, tests, pattern):
        test_cases = unittest.TestSuite()
        for p1, p2 in [(1, 2), (3, 4)]:
            test_cases.addTest(GeneralTestCase('runTest', p1, p2))
        return test_cases
    

    That code will run all the TestCases in the TestSuite returned by load_tests. No other tests are automatically run by the discovery mechanism.

    Alternatively, you can also use inheritance as shown in this ticket: http://bugs.python.org/msg151444

提交回复
热议问题