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

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

问题描述

需要py.test在python日志记录模块的日志文件中记录断言错误. 该测试已设置python日志记录模块,所有日志均按预期进行. 我在整个测试中都使用了assert语句.但是当遇到断言错误时, 这些消息不会记录在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挂钩负责实际运行测试功能,但不负责捕获异常并报告异常.这意味着它是捕获异常并将其交给日志记录的理想场所.

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.

请注意,钩子记录的异常要比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天全站免登陆