需要 py.test 从 python 日志模块记录日志文件中的断言错误

ken*_*ong 1 python assert pytest

需要 py.test 从 python 日志模块记录日志文件中的断言错误。该测试设置了 python 日志记录模块,所有日志都按预期进行。我在整个测试中使用了断言语句。但是当遇到断言错误时,这些消息不会记录在 python 日志输出中,而是记录在命令控制台中。

有没有办法让 py.test 在测试的日志输出中记录断言错误?

Right now the errors are in command console but it would be great if these assertion errors are also logged as part of python logging output so all the log messages are captured in one place. Also, for long running test, I cannot see the errors until the entire test finish which could be a long time to wait. It would be great if I can see the assertion error immediately so I may decide to take action.

flu*_*lub 6

您可以通过在 conftest.py 文件中使用 pytest_runtest_call 钩子来实现这一点:

import logging

def pytest_runtest_call(__multicall__):
    try:
        __multicall__.execute()
    except KeyboardInterrupt:
        raise
    except:
        logging.exception('pytest_runtest_call caught exception:')
        raise
Run Code Online (Sandbox Code Playgroud)

pytest_runtest_call 钩子负责实际运行测试函数,但不负责捕获异常并报告它们。这意味着它是捕获异常并将其交给日志记录的理想场所。

而不是实际改变调用测试函数的方式,而是使用__multicall__简单地调用如果没有这个钩子就会被调用的钩子。

请注意,钩子记录的异常会比 py.test 正常报告的异常长得多。这是因为日志记录不会将堆栈截断为只是测试函数,如果需要,您可以自己添加它。