单元测试.TestSuite除了当前添加的测试之外,还运行以前加载的测试

2024-10-03 06:28:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码使用unittest框架运行测试。这是我的一个方法的基本思想:

    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)

很明显,我想要实现的是运行lTestsPaths列表中的测试。出于某种原因,它不是单独运行lTestsPaths中的每个测试,而是运行以前运行的所有测试之外的每个测试。当从代码中的不同位置调用此方法时,也会发生这种情况。即,以前运行的所有测试(在以前的调用中)都将再次运行。你知道吗

在调试时,我看到当tstSuite初始化时,它是用以前运行的所有测试初始化的。你知道吗

为什么会这样?如何使此代码按预期运行?你知道吗


Tags: 方法代码inself框架defunittesttemp
1条回答
网友
1楼 · 发布于 2024-10-03 06:28:50

经过几个小时的调试,我找到了问题的根源:问题似乎是temp_module的名称,也就是说,因为我给所有temp模块取了相同的名称。这与内置的dir方法有关,因为dir方法由testLoader.loadTestsFromModule(temp_module)调用,返回以前运行的测试对象名称。我不知道为什么,但这就是代码行为的原因。你知道吗

为了解决这个问题,我在使用模块后从sys.modules中删除了模块名:“temp\u module”。也许有一个更干净的方法,但这是可行的。你知道吗

以下是对我有效的改进代码:

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']

相关问题 更多 >