【问题标题】:pytest - specify log level from the CLI command running the testspytest - 从运行测试的 CLI 命令指定日志级别
【发布时间】:2017-10-10 15:56:06
【问题描述】:

我和我的团队正在使用 Pytest + Jenkins 来自动化我们的产品测试。我们一直在使用 python 的标准 Logging 库在测试期间、每次测试之前和之后等获取正确的日志消息。我们有多层日志记录,我们注销 ERROR、WARNING、INFO 和 DEBUG。我们记录器的默认值为 INFO。我们在测试的主要设置中创建记录器对象,并将其传递给创建的每个对象,因此我们所有的日志都转到同一个记录器。

到目前为止,当我们开发新功能或测试时,我们在本地以 DEBUG 模式工作,并在向我们的 SVN 提交新代码时将其更改回 INFO,但我正在尝试添加选项以使用更改日志记录级别CLI,但我还没有发现任何容易实现的东西。我考虑过使用 Fixtures,但据我了解,这些仅用于测试本身,而不用于设置/拆卸阶段,并且创建的日志与测试无关。 关于如何向 CLI 命令添加 Pytest 选项以支持更改日志记录级别的任何技巧或想法?

【问题讨论】:

标签: python linux logging command-line-interface pytest


【解决方案1】:

Pytest 3.5 引入了一个参数

pytest --log-cli-level=INFO

对于 3.5 之前的版本,您可以组合 pytest commandline optionspython loglevel from commandline example 来执行以下操作:

将以下内容添加到conftest.py

import pytest
import logging


def pytest_addoption(parser):
    parser.addoption(
        "--log", action="store", default="WARNING", help="set logging level"
    )


@pytest.fixture
def logger():
    loglevel = pytest.config.getoption("--log")
    logger = logging.getLogger(__name__)

    numeric_level = getattr(
        logging,
        loglevel.upper(),
        None
    )
    if not isinstance(numeric_level, int):
        raise ValueError('Invalid log level: %s' % loglevel)

    logger.setLevel(numeric_level)
    return logger

然后在您的测试中请求 logger 夹具

def test_bla(logger):
    assert True
    logger.info("True is True")

然后像这样运行pytest

py.test --log INFO

将日志级别设置为INFO

【讨论】:

  • 这能回答你的问题吗?
  • 不完全是,但你的例子确实给了我正确的想法。我在套件的 setup_class 中创建记录器对象,所以我没有使用固定装置,我只是使用了你给我的示例,说明如何使用 pytest_addoption 方法,将日志记录级别添加到 pytest CLI 命令。我没有意识到它是如此简单,并且在阅读 pytest 文档时迷失了固定装置和钩子。
【解决方案2】:

试试--log-cli-level=INFO

喜欢:

pytest -vv -s --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" ./test_file.py

【讨论】:

    【解决方案3】:

    这现在内置在 pytest 中。只需在运行测试时将“--log-level=”添加到命令行。例如:

    pytest --log-level=INFO
    

    可在此处找到文档更新:https://docs.pytest.org/en/latest/logging.html

    【讨论】:

    • 谢谢,这比--log-cli-level 效果更好,禁用第三方模块日志记录。
    • 奇怪的是,这对我不起作用,我的图书馆和第 3 方。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    • 2012-09-14
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 2021-10-16
    相关资源
    最近更新 更多