Python单元测试模块,将失败记录到文件中

4

我希望能够清理正常的Python单元测试输出。我希望控制台输出仍然为:

test_isupper (__main__.TestStringMethods) ... ok
test_split (__main__.TestStringMethods) ... ok
test_upper (__main__.TestStringMethods) ... ok
test_fail (__main__.TestFail) ... ERROR

----------------------------------------------------------------------
Ran 4 tests in 0.001s

OK

但是对于失败的测试,我想要捕获详细的输出并将其放入日志文件中。所以,与其行内显示在控制台上,...

======================================================================
FAIL: test_fail (__main__.TestFail)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line x
    self.assertTrue(False)
AssertionError: False is not True

======================================================================

将日志记录到文件中以供进一步调查,同时包括任何调试级别的记录器输出。是否有一种方法可以重载unittest.testcase中的记录器以实现我的要求?

我应该提到我对Python还很陌生...


你必须向社区分享测试的完整代码,至少从测试失败开始,这样任何人都可以帮助你。只有这些数据是不可能的。 - developer_hatch
1
代码本身并不重要,因为问题涉及操作和重定向“unittest”模块的输出。我给出的示例失败测试只有两行... def test_fail(self): assertTrue(False) - Tom Schutte
2个回答

1
我最终通过使用testResult对象,获得了与我想要的结果相当接近的结果。通过该对象,我能够获取包含已通过、失败或出现错误的不同测试数据的元组。然后,我创建了一个“prettyPrint”方法来将此对象打印出漂亮的内容。
具体步骤如下:
suite = unittest.TestLoader().loadTestsFromModule( className )
testResult = unittest.TextTestRunner(verbosity=3).run( suite ) 

希望这能帮助其他想做类似事情的人。

但是调用 unittest.TextTestRunner(verbosity=3).run( suite ) 仍然会将堆栈跟踪输出到终端,而不是文件。而且您也没有使用您在示例中提到的 TestResult - Hi-Angel

0

TextTestRunner 的输出可以通过向构造函数提供一个 stream 参数来重定向到文件。然后,使用套件上的 run() 将返回 TextTestResult,您可以对其进行漂亮的打印。就像这样:

logs_filename = 'logs.txt'

def print_test_results_summary(result):
    n_failed    = len(result.failures) + len(result.unexpectedSuccesses)
    n_crashed   = len(result.errors)
    n_succeeded = result.testsRun - n_failed - n_crashed
    print(f'''See for details {logs_filename} file.
Results: Total: {result.testsRun}, Crashed: {n_crashed}, Failed: {n_failed}, Succeeded: {n_succeeded}''')

with open(logs_filename, 'w') as log_file:
    suite = unittest.defaultTestLoader.loadTestsFromModule(className)
    testResult = unittest.TextTestRunner(log_file, verbosity=3).run(suite)
    print_test_results_summary(testResult)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接