在 pytest 测试中记录日志 [英] Logging within pytest tests

查看:78
本文介绍了在 pytest 测试中记录日志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在测试函数中放入一些日志语句来检查一些状态变量.

I would like to put some logging statements within test function to examine some state variables.

我有以下代码片段:

import pytest,os
import logging

logging.basicConfig(level=logging.DEBUG)
mylogger = logging.getLogger()

#############################################################################

def setup_module(module):
    ''' Setup for the entire module '''
    mylogger.info('Inside Setup')
    # Do the actual setup stuff here
    pass

def setup_function(func):
    ''' Setup for test functions '''
    if func == test_one:
        mylogger.info(' Hurray !!')

def test_one():
    ''' Test One '''
    mylogger.info('Inside Test 1')
    #assert 0 == 1
    pass

def test_two():
    ''' Test Two '''
    mylogger.info('Inside Test 2')
    pass

if __name__ == '__main__':
    mylogger.info(' About to start the tests ')
    pytest.main(args=[os.path.abspath(__file__)])
    mylogger.info(' Done executing the tests ')

我得到以下输出:

[bmaryada-mbp:/Users/bmaryada/dev/platform/main/proto/tests/tpch $]python minitest.py
INFO:root: About to start the tests 
======================================================== test session starts =========================================================
platform darwin -- Python 2.6.2 -- pytest-2.0.0
collected 2 items 

minitest.py ..

====================================================== 2 passed in 0.01 seconds ======================================================
INFO:root: Done executing the tests 

请注意,只有来自 '__name__ == __main__' 块的日志消息会传输到控制台.

Notice that only the logging messages from the '__name__ == __main__' block get transmitted to the console.

有没有办法强制 pytest 也从测试方法向控制台发出日志记录?

Is there a way to force pytest to emit logging to console from test methods as well?

推荐答案

对我有用,这是我得到的输出:[snip -> 示例不正确]

Works for me, here's the output I get: [snip -> example was incorrect]

看来您必须将 -s 选项传递给 py.test,这样它就不会捕获标准输出.这里(没有安装py.test),使用python pytest.py -s pyt.py就足够了.

It seems that you have to pass the -s option to py.test so it won't capture stdout. Here (py.test not installed), it was enough to use python pytest.py -s pyt.py.

对于你的代码,你只需要将 args 中的 -s 传递给 main:

For your code, all you need is to pass -s in args to main:

 pytest.main(args=['-s', os.path.abspath(__file__)])

请参阅有关捕获输出的 py.test 文档.

See the py.test documentation on capturing output.

这篇关于在 pytest 测试中记录日志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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