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

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

    Use the ddt library. It adds simple decorators for the test methods:

    import unittest
    from ddt import ddt, data
    from mycode import larger_than_two
    
    @ddt
    class FooTestCase(unittest.TestCase):
    
        @data(3, 4, 12, 23)
        def test_larger_than_two(self, value):
            self.assertTrue(larger_than_two(value))
    
        @data(1, -3, 2, 0)
        def test_not_larger_than_two(self, value):
            self.assertFalse(larger_than_two(value))
    

    This library can be installed with pip. It doesn't require nose, and works excellent with the standard library unittest module.

提交回复
热议问题