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

后端 未结 25 2411
面向向阳花
面向向阳花 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:31

    Super late to the party, but I had trouble making these work for setUpClass.

    Here's a version of @Javier's answer that gives setUpClass access to dynamically allocated attributes.

    import unittest
    
    
    class GeneralTestCase(unittest.TestCase):
        @classmethod
        def setUpClass(cls):
            print ''
            print cls.p1
            print cls.p2
    
        def runTest1(self):
            self.assertTrue((self.p2 - self.p1) == 1)
    
        def runTest2(self):
            self.assertFalse((self.p2 - self.p1) == 2)
    
    
    def load_tests(loader, tests, pattern):
        test_cases = unittest.TestSuite()
        for p1, p2 in [(1, 2), (3, 4)]:
            clsname = 'TestCase_{}_{}'.format(p1, p2)
            dct = {
                'p1': p1,
                'p2': p2,
            }
            cls = type(clsname, (GeneralTestCase,), dct)
            test_cases.addTest(cls('runTest1'))
            test_cases.addTest(cls('runTest2'))
        return test_cases
    

    Outputs

    1
    2
    ..
    3
    4
    ..
    ----------------------------------------------------------------------
    Ran 4 tests in 0.000s
    
    OK
    

提交回复
热议问题