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

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

    Just to throw another solution in the mix ;)

    This is effectively the same as parameterized as mentioned above, but specific to unittest:

    def sub_test(param_list):
        """Decorates a test case to run it as a set of subtests."""
    
        def decorator(f):
    
            @functools.wraps(f)
            def wrapped(self):
                for param in param_list:
                    with self.subTest(**param):
                        f(self, **param)
    
            return wrapped
    
        return decorator
    

    Example usage:

    class TestStuff(unittest.TestCase):
        @sub_test([
            dict(arg1='a', arg2='b'),
            dict(arg1='x', arg2='y'),
        ])
        def test_stuff(self, a, b):
            ...
    

提交回复
热议问题