简体   繁体   English

unittest.TestSuite除了运行当前添加的测试外,还运行先前加载的测试

[英]unittest.TestSuite runs previously loaded tests in addition to currently added tests

My code runs tests using the unittest framework. 我的代码使用unittest框架运行测试。 This is the basic idea of what one of my methods looks like: 这是我的一种方法的基本概念:

    def _RunTestsList(self, lTestsPaths):
        """ Runs all tests in lTestsPaths with the unittest module
        """
        for sTestPath in lTestsPaths:
            testLoader = unittest.TestLoader()
            temp_module = imp.load_source('temp_module', sTestPath)
            tstSuite = testLoader.loadTestsFromModule(temp_module)
            unittest.TextTestRunner (verbosity=1).run(tstSuite)

What I'm obviously trying to achieve is to run the tests that are in the lTestsPaths list. 我显然想实现的目标是运行lTestsPaths列表中的测试。 For some reason what happens is, instead of running every test in lTestsPaths individually, it runs every test in addition to all the tests that were run previously. 由于某种原因,发生的是, lTestsPaths单独运行lTestsPaths每个测试之外,它还运行除先前运行的所有测试之外的每个测试。 This happens also when calling this method from different places in the code. 从代码的不同位置调用此方法时,也会发生这种情况。 Ie all the tests that were previously run (in earlier calls) are run again. 即,先前运行的所有测试(在先前的调用中)将再次运行。

When debugging, I see that when tstSuite is initialized, it is initialized with all previously run tests. 调试时,我看到初始化tstSuite时,将使用所有先前运行的测试对其进行初始化。

Why is this happening? 为什么会这样呢? How can I make this code run as expected? 如何使此代码按预期运行?

After many debugging hours I got to the root of the problem: The problem seems to be the name of the temp_module , that is, because I give all my temp modules the same name. 经过大量调试之后,我找到了问题的根源:问题似乎出在temp_module的名称上,这是因为我给所有的temp模块起了相同的名称。 This has something to do with the built-in dir method, as the dir method, which is called by testLoader.loadTestsFromModule(temp_module) returns test objects names that were run before. 这与内置的dir方法有关,因为dir方法由testLoader.loadTestsFromModule(temp_module)调用,它返回之前运行的测试对象的名称。 I'm not sure why, but this is the reason for code behavior. 我不确定为什么,但这就是代码行为的原因。

To solve this I deleted the module name: 'temp_module' from sys.modules after using the module. 为了解决这个问题,我在使用模块后从sys.modules删除了模块名称:“ temp_module”。 There may be a cleaner way, but this works. 可能有一种更清洁的方法,但这可行。

Here is the improved code that worked for me: 这是对我有用的改进代码:

def _RunTestsList(self, lTestsPaths):
    """ Runs all tests in lTestsPaths with the unittest module
    """
    for sTestPath in lTestsPaths:
        testLoader = unittest.TestLoader()
        temp_module = imp.load_source('temp_module', sTestPath)
        tstSuite = testLoader.loadTestsFromModule(temp_module)
        unittest.TextTestRunner (verbosity=1).run(tstSuite)
        del sys.modules['temp_module']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM