pytest - specify log level from the CLI command running the tests

后端 未结 3 1297
-上瘾入骨i
-上瘾入骨i 2021-02-05 18:06

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

相关标签:
3条回答
  • 2021-02-05 18:09

    Pytest 3.5 introduced a parameter

    pytest --log-cli-level=INFO
    

    For versions prior to 3.5 you can combine pytest commandline options and the python loglevel from commandline example to do the following:

    Add the following to 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
    

    and then request the logger fixture in your tests

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

    Then run pytest like

    py.test --log INFO
    

    to set the log level to INFO.

    0 讨论(0)
  • 2021-02-05 18:16

    Try --log-cli-level=INFO

    like:

    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
    
    0 讨论(0)
  • 2021-02-05 18:35

    This is now built into pytest. Just add '--log-level=' to the command line when running your test. For example:

    pytest --log-level=INFO
    

    Documentation updates can be found here: https://docs.pytest.org/en/latest/logging.html

    0 讨论(0)
提交回复
热议问题