0

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.

Isu
  • 330
  • 1
  • 4
  • 16

2 Answers2

2

I was specifying the logger level in 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.

Isu
  • 330
  • 1
  • 4
  • 16
  • can you elaborate on this how did you fix it ? I am facing the same problem , caplog only have logs on the file level not on folder level – Niladri Aug 21 '23 at 17:10
0

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

caplog.set_level(logging.INFO, logger="YOUR_LOGGER_NAME")
ale
  • 79
  • 3
  • I did try that but got the same empty log. – Isu Mar 31 '22 at 16:24
  • Did you try to use root logger in mark_email_as_seen() just to check how it works with root? I met this issue in my tests too, but was resolved by propagate=1(True) for package logger. I see that you have done it already. – ale Apr 04 '22 at 13:20