Python 在 py.test 测试中记录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4673373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Logging within py.test tests
提问by superselector
I would like to put some logging statements within test function to examine some state variables.
我想在测试函数中放置一些日志语句来检查一些状态变量。
I have the following code snippet:
我有以下代码片段:
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 ')
I get the following output:
我得到以下输出:
[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
Notice that only the logging messages from the '__name__ == __main__'block get transmitted to the console.
请注意,只有来自'__name__ == __main__'块的日志消息才会传输到控制台。
Is there a way to force pytest to emit logging to console from test methods as well?
有没有办法强制 pytest 也从测试方法向控制台发出日志记录?
采纳答案by TryPyPy
Works for me, here's the output I get: [snip -> example was incorrect]
对我有用,这是我得到的输出:[snip -> 示例不正确]
Edit: It seems that you have to pass the -soption 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.
编辑:似乎您必须将-s选项传递给 py.test 以便它不会捕获标准输出。在这里(未安装 py.test),使用 python pytest.py -s pyt.py.
For your code, all you need is to pass -sin argsto main:
对于你的代码,你需要的是通过-s在args到main:
pytest.main(args=['-s', os.path.abspath(__file__)])
See the py.test documentation on capturing output.
请参阅有关捕获输出的 py.test 文档。
回答by hoefling
Since version 3.3, pytestsupports live logging, meaning that all the log records emitted in tests will be printed to the terminal immediately. The feature is documented under Live Logssection. Live logging is disabled by default; to enable it, set log_cli = 1in the pytest.iniconfig1. Live logging supports emitting to terminal and file; the relevant options allow records customizing:
从 3.3 版本开始,pytest支持实时日志记录,这意味着测试中发出的所有日志记录都会立即打印到终端。该功能记录在实时日志部分。默认情况下禁用实时日志记录;要启用它,请log_cli = 1在pytest.ini配置1 中设置。实时日志支持发送到终端和文件;相关选项允许自定义记录:
terminal:
终端:
log_cli_levellog_cli_formatlog_cli_date_format
log_cli_levellog_cli_formatlog_cli_date_format
file:
文件:
log_filelog_file_levellog_file_formatlog_file_date_format
log_filelog_file_levellog_file_formatlog_file_date_format
Note: As pointed out by Kévin Barréin this comment, overriding ini options from command line can be done via the log_cliflag can't be passed from command line and mustbe set in pytest.ini. All the other options can be both passed from command line or set in the config file.-o/--overrideoption. So instead of declaring log_cliin pytest.ini, you can simply call:
注意:正如Kévin Barré在此评论中指出的那样,可以通过该log_cli标志不能从命令行传递,必须在pytest.ini. 所有其他选项都可以从命令行传递或在配置文件中设置。-o/--override选项从命令行覆盖 ini选项。因此,而不是声明log_cli中pytest.ini,你可以简单地调用:
$ pytest -o log_cli=true ...
Examples
例子
Simple test file used for demonstrating:
用于演示的简单测试文件:
# test_spam.py
import logging
LOGGER = logging.getLogger(__name__)
def test_eggs():
LOGGER.info('eggs info')
LOGGER.warning('eggs warning')
LOGGER.error('eggs error')
LOGGER.critical('eggs critical')
assert True
As you can see, no extra configuration needed; pytestwill setup the logger automatically, based on options specified in pytest.inior passed from command line.
如您所见,不需要额外的配置;pytest将根据pytest.ini命令行中指定或传递的选项自动设置记录器。
Live logging to terminal, INFOlevel, fancy output
实时记录到终端、INFO级别、花哨的输出
Configuration in pytest.ini:
配置pytest.ini:
[pytest]
log_cli = 1
log_cli_level = INFO
log_cli_format = %(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s)
log_cli_date_format=%Y-%m-%d %H:%M:%S
Running the test:
运行测试:
$ pytest test_spam.py
=============================== test session starts ================================
platform darwin -- Python 3.6.4, pytest-3.7.0, py-1.5.3, pluggy-0.7.1 -- /Users/hoefling/.virtualenvs/stackoverflow/bin/python3.6
cachedir: .pytest_cache
rootdir: /Users/hoefling/projects/private/stackoverflow/so-4673373, inifile: pytest.ini
collected 1 item
test_spam.py::test_eggs
---------------------------------- live log call -----------------------------------
2018-08-01 14:33:20 [ INFO] eggs info (test_spam.py:7)
2018-08-01 14:33:20 [ WARNING] eggs warning (test_spam.py:8)
2018-08-01 14:33:20 [ ERROR] eggs error (test_spam.py:9)
2018-08-01 14:33:20 [CRITICAL] eggs critical (test_spam.py:10)
PASSED [100%]
============================= 1 passed in 0.01 seconds =============================
Live logging to terminal and file, only message & CRITICALlevel in terminal, fancy output in pytest.logfile
实时记录到终端和文件,终端中只有消息和CRITICAL级别,pytest.log文件中的花哨输出
Configuration in pytest.ini:
配置pytest.ini:
[pytest]
log_cli = 1
log_cli_level = CRITICAL
log_cli_format = %(message)s
log_file = pytest.log
log_file_level = DEBUG
log_file_format = %(asctime)s [%(levelname)8s] %(message)s (%(filename)s:%(lineno)s)
log_file_date_format=%Y-%m-%d %H:%M:%S
Test run:
测试运行:
$ pytest test_spam.py
=============================== test session starts ================================
platform darwin -- Python 3.6.4, pytest-3.7.0, py-1.5.3, pluggy-0.7.1 -- /Users/hoefling/.virtualenvs/stackoverflow/bin/python3.6
cachedir: .pytest_cache
rootdir: /Users/hoefling/projects/private/stackoverflow/so-4673373, inifile: pytest.ini
collected 1 item
test_spam.py::test_eggs
---------------------------------- live log call -----------------------------------
eggs critical
PASSED [100%]
============================= 1 passed in 0.01 seconds =============================
$ cat pytest.log
2018-08-01 14:38:09 [ INFO] eggs info (test_spam.py:7)
2018-08-01 14:38:09 [ WARNING] eggs warning (test_spam.py:8)
2018-08-01 14:38:09 [ ERROR] eggs error (test_spam.py:9)
2018-08-01 14:38:09 [CRITICAL] eggs critical (test_spam.py:10)
1Although you can configure pytestin setup.cfgunder the [tool:pytest]section, don't be tempted to do that when you want to provide custom live logging format. Other tools reading setup.cfgmight treat stuff like %(message)sas string interpolation and fail. Use pytest.inito avoid errors.
1尽管您可以pytest在setup.cfg该[tool:pytest]部分下进行配置,但是当您想要提供自定义实时日志记录格式时,请不要尝试这样做。其他工具阅读setup.cfg可能会将诸如%(message)s字符串插值之类的东西视为失败。使用pytest.ini以避免错误。

