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

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

    import unittest
    
    def generator(test_class, a, b,c,d,name):
        def test(self):
            print('Testexecution=',name)
            print('a=',a)
            print('b=',b)
            print('c=',c)
            print('d=',d)
    
        return test
    
    def add_test_methods(test_class):
        test_list = [[3,3,5,6, 'one'], [5,5,8,9, 'two'], [0,0,5,6, 'three'],[0,0,2,3,'Four']]
        for case in test_list:
            print('case=',case[0], case[1],case[2],case[3],case[4])
            test = generator(test_class, case[0], case[1],case[2],case[3],case[4])
            setattr(test_class, "test_%s" % case[4], test)
    
    
    class TestAuto(unittest.TestCase):
        def setUp(self):
            print ('Setup')
            pass
    
        def tearDown(self):
            print ('TearDown')
            pass
    
    add_test_methods(TestAuto)
    
    if __name__ == '__main__':
        unittest.main(verbosity=1)
    

提交回复
热议问题