在 pytest 测试中记录日志
我想在测试函数中放置一些日志语句来检查一些状态变量。
我有以下代码片段:
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 也从测试方法将日志记录发送到控制台?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
从 3.3 版本开始,
pytest
支持实时日志记录,这意味着测试中发出的所有日志记录都将立即打印到终端。该功能记录在实时日志部分。默认情况下禁用实时记录;要启用它,请在pyproject.toml
1 或pytest.ini
2 中设置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
正如此评论中的 >Kévin Barré ,可以通过以下方式从命令行覆盖
ini
选项:因此,不要在
pytest 中声明
,您可以简单地调用:log_cli
.iniExamples
用于演示的简单测试文件:
正如您所看到的,不需要额外的配置; pytest 将根据 pytest.ini 中指定的选项或从命令行传递的选项自动设置记录器。
实时记录到终端,
INFO
级别,奇特的输出pyproject.toml
中的配置:旧版
pytest.ini
中的相同配置:运行测试:
实时记录到终端和文件,仅消息和文件终端中的
CRITICAL
级别,pytest.log
文件中的精美输出pyproject.toml
中的配置:旧版
pytest.ini 中的相同配置
:测试运行:
1
pyproject.toml
自版本 6.0 起受支持,是 IMO 的最佳选择。有关规范,请参阅 PEP 518。2 虽然您也可以在
[tool:pytest]
部分下的setup.cfg
中配置pytest
,但不要'当您想提供自定义实时日志记录格式时,不要试图这样做。其他读取setup.cfg
的工具可能会将%(message)s
之类的内容视为字符串插值并失败。无论如何,最好的选择是使用 pyproject.toml ,但如果您被迫使用旧的 ini 样式格式,请坚持使用 pytest.ini 以避免错误。Since version 3.3,
pytest
supports live logging, meaning that all the log records emitted in tests will be printed to the terminal immediately. The feature is documented under Live Logs section. Live logging is disabled by default; to enable it, setlog_cli = 1
in thepyproject.toml
1 orpytest.ini
2 config. Live logging supports emitting to terminal and file; the relevant options allow records customizing:terminal:
log_cli_level
log_cli_format
log_cli_date_format
file:
log_file
log_file_level
log_file_format
log_file_date_format
As pointed out by Kévin Barré in this comment, overriding
ini
options from command line can be done via:So instead of declaring
log_cli
inpytest.ini
, you can simply call:Examples
Simple test file used for demonstrating:
As you can see, no extra configuration needed;
pytest
will setup the logger automatically, based on options specified inpytest.ini
or passed from command line.Live logging to terminal,
INFO
level, fancy outputConfiguration in
pyproject.toml
:The identical configuration in legacy
pytest.ini
:Running the test:
Live logging to terminal and file, only message &
CRITICAL
level in terminal, fancy output inpytest.log
fileConfiguration in
pyproject.toml
:The identical configuration in legacy
pytest.ini
:Test run:
1
pyproject.toml
supported since version 6.0 and is the best option IMO. See PEP 518 for the specs.2 Although you can also configure
pytest
insetup.cfg
under the[tool:pytest]
section, don't be tempted to do that when you want to provide custom live logging format. Other tools readingsetup.cfg
might treat stuff like%(message)s
as string interpolation and fail. The best choice is usingpyproject.toml
anyway, but if you are forced to use the legacy ini-style format, stick topytest.ini
to avoid errors.使用 pytest --log-cli-level=DEBUG 可以与 pytest 配合使用(从 6.2.2 到 7.1.1 进行测试)
使用 pytest --log-cli-level=DEBUG --capture =tee-sys 还将打印
stdtout
。Using
pytest --log-cli-level=DEBUG
works fine with pytest (tested from 6.2.2 to 7.1.1)Using
pytest --log-cli-level=DEBUG --capture=tee-sys
will also printstdtout
.对我有用,这是我得到的输出: [snip ->示例不正确]
编辑:似乎您必须将
-s
选项传递给 py.test,这样它就不会捕获标准输出。在这里(未安装 py.test),使用 python pytest.py -s pyt.py 就足够了。对于您的代码,您只需将
args
中的-s
传递给main
:请参阅 捕获输出。
Works for me, here's the output I get: [snip -> example was incorrect]
Edit: 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 usepython pytest.py -s pyt.py
.For your code, all you need is to pass
-s
inargs
tomain
:See the py.test documentation on capturing output.
要打开记录器输出,请从命令行发送
--capture=no
标志。--capture=no
将显示记录器和打印语句的所有输出。如果您想捕获记录器的输出而不是打印语句,请使用--capture=sys
这里是有关“捕获 stdout/stderr 输出”的更多信息
默认记录器输出级别为“警告”
要更改日志输出级别,请使用
--log-cli-level
标志。To turn logger output on use send
--capture=no
flag from command line.--capture=no
will show all outputs from logger and print statements. If you would like to capture outputs from logger and not print statements use--capture=sys
Here is more information about "Capturing of the stdout/stderr output"
By default logger output level is "WARNING"
To change log output level use
--log-cli-level
flag.如果你想用命令行过滤日志,可以通过 --log-cli-level (pytest --log-cli-level)
并且日志将从您指定的级别及以上显示
(例如 pytest --log-cli-level=INFO 将显示 INFO 及以上日志(警告、错误、严重))
请注意:默认 -如果您未指定 -log-cli-level ,则会出现警告(https: //docs.pytest.org/en/6.2.x/logging.html)
但是如果你不想每次使用pytest时都使用--log-cli-level,
您可以设置日志级别
在你的 pytest 配置文件(pytest.ini/tox.ini/setup.cfg)中,
例如
将 log-level=INFO 放入 pytest.ini (或我提到的其他配置文件)中
,当你运行 时, pytest,你只能看到INFO及以上日志
If you want to filter logs with the command line, you can pass --log-cli-level (pytest --log-cli-level)
and logs will be shown from the level you specified and above
(e.g. pytest --log-cli-level=INFO will show INFO and above logs(WARNING, ERROR, CRITICAL))
note that: default --log-cli-level is a WARNING if you don't specify it (https://docs.pytest.org/en/6.2.x/logging.html)
But if you dont want to use --log-cli-level every time use pytest,
you can set log-level
in your pytest config file (pytest.ini/tox.ini/setup.cfg)
e.g.
put log-level=INFO in pytest.ini (or other config files i mentioned)
when you run pytest, you only see INFO and above logs
如果您使用
vscode
,请使用以下配置,假设您已安装适用于您的 Python 项目的 Python 官方插件 (
ms-python.python
)。下的
./.vscode/setting.json
您的项目 一些插件可以使用它,包括但不限于:
littlefoxteam.vscode-python-test-adapter
)hbenl.vscode-test-explorer
)If you use
vscode
, use following config, assuming you've installedPython official plugin (
ms-python.python
) for your python project../.vscode/setting.json
under your projP.S. Some plugins work on it, including but not limited to:
littlefoxteam.vscode-python-test-adapter
)hbenl.vscode-test-explorer
)您可以阅读:
pytest 日志记录
这是一个简单的示例,您可以运行 foo 函数并获取日志。
现在您可以运行 pytest 并从您需要的函数中获取日志信息。
如果没有任何错误,日志将被省略。
You can read:
Documentation for logging in pytest
Here is simple example that you can run and get log from foo function.
Now you can run pytest and get log info from function that you need.
If you don't have any errors, logs will be omitted.