运行 时未从 XMLRunner 创建测试报告

Test report is not creating while running from XMLRunner

我正在运行使用 XMLTestRunner Python 宁单元测试用例。

这是我的主文件:

#LoggingService.py
class LoggerWriter:
    # used to redirect console msgs to the log
    def write(self, message):
        log_event('warning', 'Console', message)

def direct_console_to_log():
    global console_redirected
    # This function can be called several times. Avoid redirecting more than once
    if not console_redirected:
        console_output = LoggerWriter()
        sys.stderr = console_output
        sys.stdout = console_output
        console_redirected = True

def log_event(level, _id, event_details):
    # log the event
    pass

这是我的测试文件之一:

#LoggingServiceTest.py
import unittest
import LoggingService
from LoggingService import direct_console_to_log
class Test(unittest.TestCase):
    @patch('LoggingService.log_event')
    def test_log_writer(self,log_mock):
        direct_console_to_log()
        print ('console msg')
        self.assertTrue(log_mock.called)

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

我曾经 运行 来自 XMLRunner.py 的所有测试文件:

#XMLRunner.py
from xmlrunner import XMLTestRunner
import unittest

test_modules = [file1.Test, file2.Test, LoggingServiceTest.py, .... file25.Test]
suite = unittest.TestSuite()

for test_module in test_modules:
    tests = unittest.TestLoader().loadTestsFromTestCase(test_module)
    suite.addTests(tests)

if __name__ == '__main__':
    # import xmlrunner
    # unittest.main(testRunner=xmlrunner.XMLTestRunner(output='test-reports'))
    XMLTestRunner(output='test-reports').run(suite)

当我尝试从 "XMLRunner.py" 运行 LoggingServiceTest.py 文件时,当我尝试不使用 "LoggingServiceTest.py" 时,测试报告不会 generate.But,然后报告生成成功。

而且我不确定测试用例函数发生了什么 (test_log_writer(self,log_mock)) 在LoggingServiceTest.py 运行宁。 任何人都可以清除我

我使用下面的命令运行测试用例:

Python2.7.14\python.exe -m coverage run -p --branch --source=. --omit=Unit_Tests/*.py Unit_Tests/Testing.py

调试多了终于解决了

当从 XMLRunner 启动测试用例时,它正在创建一些文件对象来写入 stderr 和 stdout,它在 sys.stderr, sys.stdout 变量

中定义

我的测试用例覆盖了 sys.stderr, sys.stdout 变量。

所以 XMLRunner 尝试从 sys.stderr, sys.stdout 获取文件对象,但它不存在,因此它不会生成报告。