pytest-从运行测试的CLI命令指定日志级别 [英] pytest - specify log level from the CLI command running the tests

查看:484
本文介绍了pytest-从运行测试的CLI命令指定日志级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

my team and I are using Pytest + Jenkins to automate our product testing. we have been using the standard Logging lib of python to get proper log messages during testing, before and after each test etc. we have multiple layers of logging, we log out ERROR, WARNING, INFO and DEBUG. the default value for our logger is INFO. we create the logger object in the primary setup of the tests, and pass it down to each object created, so all our logs go to the same logger.

到目前为止,当我们开发新功能或测试时,我们在本地以DEBUG模式工作,并在将新代码提交给SVN时将其更改回INFO,但是我试图添加使用该选项来更改日志记录级别的选项CLI,但是我还没有发现容易实现的东西.我曾经考虑过使用夹具,但据我了解,这些夹具仅用于测试本身,而不是用于安装/拆卸阶段,并且创建日志时所涉及的测试较少. 关于如何在CLI命令中添加Pytest选项以支持更改日志记录级别的任何技巧或想法?

so far when we are developing a new feature or test, we are working in DEBUG mode locally, and change it back to INFO when submitting new code to our SVN, but i am trying to add option to change logging level using the CLI, but i haven't found anything easy to implement. I've considered using Fixtures, but from what i understand those are only for the tests themselves, and not for the setup/tear-down phases, and the log is created regard less of the tests. any hack or idea on how to add a Pytest option to the CLI command to support changing logging level?

推荐答案

组合

Combining pytest commandline options and the python loglevel from commandline example you can do the following:

将以下内容添加到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固定装置

and then request the logger fixture in your tests

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

然后像这样运行pytest

Then run pytest like

py.test --log INFO

将日志级别设置为INFO.

这篇关于pytest-从运行测试的CLI命令指定日志级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆