在py.test测试中记录

时间:2011-01-12 19:53:53

标签: python logging 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从测试方法发出日志记录到控制台?

6 个答案:

答案 0 :(得分:32)

自版本3.3起,pytest支持实时日志记录,这意味着测试中发出的所有日志记录将立即打印到终端。该功能记录在Live Logs下。默认情况下,实时日志记录是禁用的;要启用它,请在log_cli = 1配置中设置pytest.ini。实时日志支持向终端和文件发射;相关选项允许自定义记录:

终端:

  • log_cli_level
  • log_cli_format
  • log_cli_date_format

文件:

  • log_file
  • log_file_level
  • log_file_format
  • log_file_date_format

注意:不能从命令行传递 log_cli标志,并且必须在pytest.ini(或{{ 1}})。所有其他选项都可以从命令行传递,也可以在配置文件中设置。正如Kévin Barréthis comment所指出的那样,可以通过{ {1}}选项。因此,您无需调用setup.cfg / -o/--override中的log_cli,只需调用:

pytest.ini

示例

用于演示的简单测试文件:

setup.cfg

如您所见,不需要额外的配置。 $ pytest -o log_cli=true ... 将根据# 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 中指定或从命令行传递的选项自动设置记录器。

实时记录到pytest级别的终端,输出精美

pytest.ini中的配置:

INFO

运行测试:

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 级别,在$ 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 ============================= 文件中显示精美的输出

CRITICAL中的配置:

pytest.log

试运行:

pytest.ini

答案 1 :(得分:25)

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

编辑:您似乎必须将-s选项传递给py.test,以便它不会捕获stdout。在这里(py.test未安装),只需使用python pytest.py -s pyt.py

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

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

请参阅capturing output上的py.test文档。

答案 2 :(得分:13)

在 pytest-6.2.2 中使用 pytest --log-cli-level=DEBUG 效果很好

答案 3 :(得分:5)

要打开记录器输出,请从命令行使用发送 --capture=no 标志。 --capture=no 将显示记录器和打印语句的所有输出。如果您想从记录器中捕获输出而不是打印语句,请使用 --capture=sys

pytest --capture=no tests/system/test_backoffice.py

Here 是关于“捕获标准输出/标准输出”的更多信息

默认记录器输出级别为“警告” 要更改日志输出级别,请使用 --log-cli-level 标志。

pytest --capture=no --log-cli-level=DEBUG tests/system/test_backoffice.py

答案 4 :(得分:0)

如果您使用 vscode,请使用以下配置,假设您已安装 Python 官方插件 (ms-python.python) 用于您的 Python 项目。

./.vscode/setting.json 在您的项目下

{
  ....
  "python.testing.pytestArgs": ["-s", "src"], //here before discover-path src
  "python.testing.unittestEnabled": false,
  "python.testing.nosetestsEnabled": false,
  "python.testing.pytestEnabled": true,
  ...
}

附言一些插件可以处理它,包括但不限于

  • Visual Studio Code 的 Python 测试资源管理器 (littlefoxteam.vscode-python-test-adapter)
  • Visual Studio Code 的测试资源管理器(hbenl.vscode-test-explorer)

答案 5 :(得分:0)

您可以阅读: Documentation for logging in pytest
这是一个简单的示例,您可以运行并从 foo 函数获取日志。

#./test_main.py
from main import foo
import logging

def test_foo(caplog):
    caplog.set_level(logging.INFO)

    logging.getLogger().info('Log inside a test function!')

    assert foo(1, 2) == 5
    /* your test here*/
# ./main.py
import logging

def foo(a, b):
    logging.getLogger().info('a: ' + str(a))
    logging.getLogger().info('b: ' + str(b))
    return a + b

现在您可以运行 pytest 并从您需要的函数中获取日志信息。
如果您没有任何错误,日志将被省略。