How do I concisely implement multiple similar unit tests in the Python unittest framework?

后端 未结 9 1091
予麋鹿
予麋鹿 2020-12-24 15:10

I\'m implementing unit tests for a family of functions that all share a number of invariants. For example, calling the function with two matrices produce a matrix of known s

9条回答
  •  忘掉有多难
    2020-12-24 15:38

    You don't have to use Meta Classes here. A simple loop fits just fine. Take a look at the example below:

    import unittest
    class TestCase1(unittest.TestCase):
        def check_something(self, param1):
            self.assertTrue(param1)
    
    def _add_test(name, param1):
        def test_method(self):
            self.check_something(param1)
        setattr(TestCase1, 'test_'+name, test_method)
        test_method.__name__ = 'test_'+name
    
    for i in range(0, 3):
        _add_test(str(i), False)
    

    Once the for is executed the TestCase1 has 3 test methods that are supported by both the nose and the unittest.

提交回复
热议问题