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

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

    This solution works with unittest and nose for Python 2 and Python 3:

    #!/usr/bin/env python
    import unittest
    
    def make_function(description, a, b):
        def ghost(self):
            self.assertEqual(a, b, description)
        print(description)
        ghost.__name__ = 'test_{0}'.format(description)
        return ghost
    
    
    class TestsContainer(unittest.TestCase):
        pass
    
    testsmap = {
        'foo': [1, 1],
        'bar': [1, 2],
        'baz': [5, 5]}
    
    def generator():
        for name, params in testsmap.iteritems():
            test_func = make_function(name, params[0], params[1])
            setattr(TestsContainer, 'test_{0}'.format(name), test_func)
    
    generator()
    
    if __name__ == '__main__':
        unittest.main()
    

提交回复
热议问题