运行创建的测试套件时,Python单元测试运行两次

时间:2020-06-24 12:49:50

标签: python-unittest test-suite

[当我创建测试套件并使用HTMLTestRunner(也由我稍做修改)生成测试报告时,一次测试运行了两次。 该代码(测试套件)为:

arrange

1 个答案:

答案 0 :(得分:0)

您在测试用例中包含测试运行器代码-因此,您的测试将由unittest.main执行,然后由您自己的testrunner执行。您可以将unittest.main替换为测试运行程序代码(不需要HTestSuite):

import os
import time
import unittest
from xyz.base import log
from builtins import dir
from xyz.HTMLTestRunner import HTMLTestRunner

from xyz.tests.test.test_01 import TC01

if __name__ == "__main__":
    log.info('Running demo test suite')

    dir = os.getcwd()
    testLoad = unittest.TestLoader()
    log.info(dir)
    test_classes_to_run =[TC01]

    suites_list = []
    for test_class in test_classes_to_run:
        suite = testLoad.loadTestsFromTestCase(test_class)
        suites_list.append(suite)
    log.info(suites_list)
    newSuite = unittest.TestSuite(suites_list)
    log.info(newSuite.countTestCases())
    timestr = time.strftime("_%Y-%m-%d_%H.%M.%S")
    
    resultFile = open(os.path.join(dir, "TestReport"+ timestr + ".html"), "w")
    runner = HTMLTestRunner(stream=resultFile, title='test report', description='Tests Execution Report') 

    runner.run(newSuite)

要运行测试,只需使用:

python xyz\abc\def\demoTestSuite.py