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

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

    I use metaclasses and decorators for generate tests. You can check my implementation python_wrap_cases. This library doesn't require any test frameworks.

    Your example:

    import unittest
    from python_wrap_cases import wrap_case
    
    
    @wrap_case
    class TestSequence(unittest.TestCase):
    
        @wrap_case("foo", "a", "a")
        @wrap_case("bar", "a", "b")
        @wrap_case("lee", "b", "b")
        def testsample(self, name, a, b):
            print "test", name
            self.assertEqual(a, b)
    

    Console output:

    testsample_u'bar'_u'a'_u'b' (tests.example.test_stackoverflow.TestSequence) ... test bar
    FAIL
    testsample_u'foo'_u'a'_u'a' (tests.example.test_stackoverflow.TestSequence) ... test foo
    ok
    testsample_u'lee'_u'b'_u'b' (tests.example.test_stackoverflow.TestSequence) ... test lee
    ok
    

    Also you may use generators. For example this code generate all possible combinations of tests with arguments a__list and b__list

    import unittest
    from python_wrap_cases import wrap_case
    
    
    @wrap_case
    class TestSequence(unittest.TestCase):
    
        @wrap_case(a__list=["a", "b"], b__list=["a", "b"])
        def testsample(self, a, b):
            self.assertEqual(a, b)
    

    Console output:

    testsample_a(u'a')_b(u'a') (tests.example.test_stackoverflow.TestSequence) ... ok
    testsample_a(u'a')_b(u'b') (tests.example.test_stackoverflow.TestSequence) ... FAIL
    testsample_a(u'b')_b(u'a') (tests.example.test_stackoverflow.TestSequence) ... FAIL
    testsample_a(u'b')_b(u'b') (tests.example.test_stackoverflow.TestSequence) ... ok
    

提交回复
热议问题