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

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

    I have found that this works well for my purposes, especially if I need to generate tests that do slightly difference processes on a collection of data.

    import unittest
    
    def rename(newName):
        def renamingFunc(func):
            func.__name__ == newName
            return func
        return renamingFunc
    
    class TestGenerator(unittest.TestCase):
    
        TEST_DATA = {}
    
        @classmethod
        def generateTests(cls):
            for dataName, dataValue in TestGenerator.TEST_DATA:
                for func in cls.getTests(dataName, dataValue):
                    setattr(cls, "test_{:s}_{:s}".format(func.__name__, dataName), func)
    
        @classmethod
        def getTests(cls):
            raise(NotImplementedError("This must be implemented"))
    
    class TestCluster(TestGenerator):
    
        TEST_CASES = []
    
        @staticmethod
        def getTests(dataName, dataValue):
    
            def makeTest(case):
    
                @rename("{:s}".format(case["name"]))
                def test(self):
                    # Do things with self, case, data
                    pass
    
                return test
    
            return [makeTest(c) for c in TestCluster.TEST_CASES]
    
    TestCluster.generateTests()
    

    The TestGenerator class can be used to spawn different sets of test cases like TestCluster.

    TestCluster can be thought of as an implementation of the TestGenerator interface.

提交回复
热议问题