Skip to content Skip to sidebar Skip to footer

How To Use Logging, Pytest Fixture And Capsys?

I am trying to unit-test some algorithm that uses logging library. I have a fixture that creates a logger. In my 1st test case, I do not use this fixture and uses a print to log to

Solution 1:

Thanks a lot for your ideas!

Reverse logger, capsys, make logger request the capsys fixture and use capfd do not change anything.

I tried pytest-catchlog plugin and it works fine!

import pytest

import logging

@pytest.fixture()deflogger():

    logger = logging.getLogger('Some.Logger')
    logger.setLevel(logging.INFO)

    return logger

deftest_logger_with_fixture(logger, caplog):

    logger.info('Bouyaka!')

    assert'Bouyaka!'in caplog.text

    # passes!

In my original tests, I logged to stdout and stderr and captured them. This is an even better solution, as I do not need this tweak to check that my logs work fine.

Well, now I just need to rework all my tests to use caplog, but this is my own business ;)

The only thing left, now that I have a better solution, is to understand what is wrong in my original test case def test_logger_with_fixture(logger, capsys).

Solution 2:

I'm guessing the logger gets created (via the fixture) before the capsys fixture is set up.

Some ideas:

  • Use the pytest-catchlog plugin
  • Maybe reverse logger, capsys
  • Make logger request the capsys fixture
  • Use capfd which is more lowlevel capturing without altering sys

Solution 3:

As of pytest 3.3, the functionality of capturing log message was added to pytest core. This is supported by the caplog fixture:

def test_baz(caplog):
    func_under_test()
    forrecordin caplog.records:
        assert record.levelname != 'CRITICAL'
    assert 'wally'notin caplog.text

More information can be found at the documentation

Post a Comment for "How To Use Logging, Pytest Fixture And Capsys?"