Giving parameters into TestCase from Suite in python

后端 未结 5 875
滥情空心
滥情空心 2020-12-16 22:42

From python documentation(http://docs.python.org/library/unittest.html):

import unittest

class WidgetTestCase(unittest.TestCase):
    def setUp(self):
              


        
5条回答
  •  余生分开走
    2020-12-16 23:28

    I've found a way to do this, but it's a bit of a cludge.

    Basically, what I do is add, to the TestCase, an __init__ method which defines a 'default' parameter and a __str__ so that we can distinguish cases:

    class WidgetTestCase(unittest.TestCase):
    
        def __init__(self, methodName='runTest'):
            self.parameter = default_parameter
            unittest.TestCase.__init__(self, methodName)
    
        def __str__(self):
            ''' Override this so that we know which instance it is '''
            return "%s(%s) (%s)" % (self._testMethodName, self.currentTest, unittest._strclass(self.__class__))
    

    Then in suite(), I iterate over my test parameters, replacing the default parameter with one specific to each test:

    def suite():
        suite = unittest.TestSuite()
    
        for test_parameter in test_parameters:
            loadedtests = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
            for t in loadedtests:
                t.parameter = test_parameter
            suite.addTests(loadedtests)
    
        suite.addTests(unittest.TestLoader().loadTestsFromTestCase(OtherWidgetTestCases))
        return suite
    

    where OtherWidgetTestCases are tests which don't need to be parameterised.

    For instance I have a bunch of tests on real data for which a suite of tests need to be applied to each, but I also have some synthetic data sets, designed to test certain edge cases not normally present in the data, and I only need to apply certain tests to those, so they get their own tests in OtherWidgetTestCases.

提交回复
热议问题