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

Python Unit-tests are running twice when run created test suite

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

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

class HTestSuite(unittest.TestCase):
    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)

if __name__ == "__main__":
    unittest.main()

您在测试用例中有测试 运行ner 代码 - 因此您的测试将由 unittest.main 执行,然后由您自己的测试 运行ner 执行。您可以将 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