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

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

    import unittest
    
    def generator(test_class, a, b):
        def test(self):
            self.assertEqual(a, b)
        return test
    
    def add_test_methods(test_class):
        #First element of list is variable "a", then variable "b", then name of test case that will be used as suffix.
        test_list = [[2,3, 'one'], [5,5, 'two'], [0,0, 'three']]
        for case in test_list:
            test = generator(test_class, case[0], case[1])
            setattr(test_class, "test_%s" % case[2], test)
    
    
    class TestAuto(unittest.TestCase):
        def setUp(self):
            print 'Setup'
            pass
    
        def tearDown(self):
            print 'TearDown'
            pass
    
    _add_test_methods(TestAuto)  # It's better to start with underscore so it is not detected as a test itself
    
    if __name__ == '__main__':
        unittest.main(verbosity=1)
    

    RESULT:

    >>> 
    Setup
    FTearDown
    Setup
    TearDown
    .Setup
    TearDown
    .
    ======================================================================
    FAIL: test_one (__main__.TestAuto)
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "D:/inchowar/Desktop/PyTrash/test_auto_3.py", line 5, in test
        self.assertEqual(a, b)
    AssertionError: 2 != 3
    
    ----------------------------------------------------------------------
    Ran 3 tests in 0.019s
    
    FAILED (failures=1)
    

提交回复
热议问题