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

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

    Just use metaclasses, as seen here;

    class DocTestMeta(type):
        """
        Test functions are generated in metaclass due to the way some
        test loaders work. For example, setupClass() won't get called
        unless there are other existing test methods, and will also
        prevent unit test loader logic being called before the test
        methods have been defined.
        """
        def __init__(self, name, bases, attrs):
            super(DocTestMeta, self).__init__(name, bases, attrs)
    
        def __new__(cls, name, bases, attrs):
            def func(self):
                """Inner test method goes here"""
                self.assertTrue(1)
    
            func.__name__ = 'test_sample'
            attrs[func.__name__] = func
            return super(DocTestMeta, cls).__new__(cls, name, bases, attrs)
    
    class ExampleTestCase(TestCase):
        """Our example test case, with no methods defined"""
        __metaclass__ = DocTestMeta
    

    Output:

    test_sample (ExampleTestCase) ... OK
    

提交回复
热议问题