Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python pytest-从运行测试的CLI命令中指定日志级别_Python_Linux_Logging_Command Line Interface_Pytest - Fatal编程技术网

Python pytest-从运行测试的CLI命令中指定日志级别

Python pytest-从运行测试的CLI命令中指定日志级别,python,linux,logging,command-line-interface,pytest,Python,Linux,Logging,Command Line Interface,Pytest,我的团队和我正在使用Pytest+Jenkins自动化我们的产品测试。我们一直在使用python的标准日志库在测试期间、每次测试之前和之后获取适当的日志消息。我们有多个日志层,我们注销错误、警告、信息和调试。我们记录器的默认值是INFO。我们在测试的主要设置中创建logger对象,并将其传递给所创建的每个对象,以便所有日志都转到同一个logger 到目前为止,当我们开发新功能或测试时,我们在本地调试模式下工作,并在向SVN提交新代码时将其更改回INFO,但我尝试添加使用CLI更改日志记录级别的选

我的团队和我正在使用Pytest+Jenkins自动化我们的产品测试。我们一直在使用python的标准日志库在测试期间、每次测试之前和之后获取适当的日志消息。我们有多个日志层,我们注销错误、警告、信息和调试。我们记录器的默认值是INFO。我们在测试的主要设置中创建logger对象,并将其传递给所创建的每个对象,以便所有日志都转到同一个logger

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

Pytest 3.5引入了一个参数

pytest --log-cli-level=INFO
对于3.5之前的版本,您可以结合和来执行以下操作:

将以下内容添加到
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
然后在测试中请求
记录器
夹具

def test_bla(logger):
    assert True
    logger.info("True is True")
然后像这样运行pytest

py.test --log INFO

要将日志级别设置为
INFO

,现在已内置到pytest中。运行测试时,只需在命令行中添加'--log level='。例如:

pytest --log-level=INFO
可以在此处找到文档更新:

尝试
--log cli level=INFO

比如:


这回答了你的问题吗?不完全正确,但你的例子确实给了我正确的想法。我在套件的setup_类中创建logger对象,所以我没有使用fixture,我只是使用了您给我的示例,介绍了如何使用pytest_addoption方法,将日志级别添加到pytest CLI命令中。我没有意识到它这么简单,在阅读pytest文档时,我迷失在了fixture和hook中。谢谢,这比禁用第三方模块日志记录的
--log cli level
更有效。奇怪的是,这对我来说都不起作用,无论是我的库还是第三方。
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