pytest caplog empty when tests run on package

2.1k views Asked by At

I am writing unit tests for a method that generate logs. I used pytest's caplog to check the log output, and while it works when I run on module like: pytest module_name.py, it fails when I run pytest on package pytest tests and caplog is empty.
Note that logger.propagate is set to True

Below my test method:

def test_correctly_mark_email_as_seen(mocker, caplog):
    mailbox = mocker.MagicMock()
    message = mocker.MagicMock()
    caplog.set_level(logging.INFO)
    mark_email_as_seen(mailbox, message)
    assert '::mark_email_as_seen, email marked as seen' in caplog.text

And the failure message:

>       assert '::mark_email_as_seen, email marked as seen' in caplog.text
E       AssertionError: assert '::mark_email_as_seen, email marked as seen' in ''
E        +  where '' = <_pytest.logging.LogCaptureFixture object at 0x10c88f580>.text

tests/test_email.py:12: AssertionError

My other tests are working just fine running them either on package or module.

2

There are 2 answers

2
Isu On BEST ANSWER

I was specifying the logger level in one of the test files where I didn't need logs, and apparently pytest takes that into consideration when it's running on a folder, so the logs didn't show for any test file which caused this problem.

2
ale On

Try to specify logger name, when you set the level.

caplog.set_level(logging.INFO, logger="YOUR_LOGGER_NAME")