在pytest测试中记录 [英] Logging within pytest tests
问题描述
我想在测试函数中放入一些日志记录语句以检查一些状态变量.
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,以便它不会捕获stdout.在这里(未安装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屋!