需要 py.test 从 python 日志模块记录日志文件中的断言错误 [英] Need py.test to log assert errors in log file from python logging module

查看:59
本文介绍了需要 py.test 从 python 日志模块记录日志文件中的断言错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Need py.test to log assert errors in log file from python logging module. The test has python logging module set up and all logs goes there as expected. I used assert statements through out the test. But when encounter assertion errors, those messages are not logged in the python logging output but in command console.

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

Is there a way to get py.test to log the assertion errors in the test's logging output?

现在错误在命令控制台中,但如果这些断言错误也记录为 python 日志输出的一部分,那么所有日志消息都可以在一个地方捕获,那就太好了.此外,对于长时间运行的测试,在整个测试完成之前我看不到错误,这可能需要等待很长时间.如果我能立即看到断言错误,那么我就可以决定采取行动,那就太好了.

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.

推荐答案

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

You can achieve this by using the pytest_runtest_call hook in a conftest.py file:

import logging

def pytest_runtest_call(__multicall__):
    try:
        __multicall__.execute()
    except KeyboardInterrupt:
        raise
    except:
        logging.exception('pytest_runtest_call caught exception:')
        raise

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

The pytest_runtest_call hook is responsible for actually running the test functions, but is not responsible for catching exceptions and reporting them. This means it is the ideal place to catch an exception and hand it to logging.

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

Instead of actually changing the way a test function is called this uses __multicall__ to simply call the hook which would have been called if this hook was not there.

请注意,hook 记录的异常会比 py.test 正常报告的异常长得多.这是因为日志记录不会将堆栈截断为仅作为测试函数,您可以根据需要自行添加.

Note that the exception logged by hook will be much longer then the exception which would be reported by py.test normally. This is because logging does not truncate the stack to be just the test function, you could add this yourself if it is needed.

这篇关于需要 py.test 从 python 日志模块记录日志文件中的断言错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆