Instantiate Python unittest.TestCase with arguments

后端 未结 3 541
暖寄归人
暖寄归人 2021-01-07 22:48

I would like to iterate over a list of items, and run an assertion on each of them. One example might be checking whether each number in a list is odd.

TestCas

3条回答
  •  失恋的感觉
    2021-01-07 23:33

    Same can be achieved using class attributes.

    class TestOdd1(unittest.TestCase):
        NUMBER=1
        def runTest(self):
            """Assert that the item is odd"""
            self.assertTrue( self.NUMBER % 2 == 1, "Number should be odd")
    
    class TestOdd2(TestOdd1):
        NUMBER=2
    
    if __name__ == '__main__':
        unittest.main()
    

    The unittesting will discover them automatically, so no need to create a suite.

    If you want to avoid using a TestCase for base class, you can use multiple inheritance:

    from unittest import TestCase, main
    
    class TestOdd:
        def runTest(self):
            """Assert that the item is odd"""
            self.assertTrue( self.NUMBER % 2 == 1, "Number should be odd")
    
    class TestOdd1(TestOdd, TestCase):
        NUMBER=1
    class TestOdd2(TestOdd, TestCase):
        NUMBER=2
    
    if __name__ == '__main__':
        main()
    

提交回复
热议问题