我想在测试函数中放一些日志语句来检查一些状态变量。
我有以下代码片段:
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__'
块的日志消息被传输到控制台。
有没有办法迫使pytest也从测试方法向控制台发出日志记录?
对我有用,这是我得到的输出:[snip->;示例不正确]
编辑:似乎必须将
-s
选项传递给py.test,这样它就不会捕获stdout。在这里(py.test未安装),它足以使用python pytest.py -s pyt.py
。对于您的代码,您只需要将
-s
传入args
到main
:请参阅capturing output上的py.test文档。
由于版本3.3,
pytest
支持实时日志记录,这意味着测试中发出的所有日志记录将立即打印到终端。该特性记录在Live Logs部分下。默认情况下禁用实时日志记录;要启用它,请在pytest.ini
配置中设置log_cli = 1
。实时日志记录支持发送到终端和文件;相关选项允许自定义记录:终端:
log_cli_level
log_cli_format
log_cli_date_format
文件:
log_file
log_file_level
log_file_format
log_file_date_format
注意:
如this comment中的Kévin Barré所指出,从命令行重写ini选项可以通过log_cli
无法从命令行传递标志,必须在pytest.ini
中设置。所有其他选项都可以从命令行传递或在配置文件中设置。-o/--override
选项完成。因此,与其在pytest.ini
中声明log_cli
,您只需调用:实例
用于演示的简单测试文件:
如您所见,不需要额外的配置;
pytest
将根据pytest.ini
中指定的选项或从命令行传递的选项自动设置记录器。到终端的实时日志,
INFO
级别,奇特的输出pytest.ini
中的配置:运行测试:
终端和文件的实时日志记录,终端中只有消息级,文件中有奇特的输出
pytest.ini
中的配置:试运行:
1尽管您可以在
[tool:pytest]
部分下的setup.cfg
中配置pytest
,但是当您希望提供自定义实时日志格式时,不要尝试这样做。其他读取setup.cfg
的工具可能会将%(message)s
之类的内容视为字符串插值而失败。使用pytest.ini
来避免错误。相关问题 更多 >
编程相关推荐