I'd like to wrap all my tests with a fixture where the logs logged with loguru are checked for error messages.
I tried this:
@pytest.fixture(autouse=True)
def assert_no_log_error(caplog):
yield
assert "ERROR" not in caplog.text
But caplog.text is always empty. I assume, caplog is cleared after the test and before the fixture actually checks the logs. How can I make this work?
EDIT 1: I found an example about how to use loguru logs with pytest fixtures in the documentation of loguru: https://loguru.readthedocs.io/en/stable/resources/migration.html#replacing-caplog-fixture-from-pytest-library. However, this doesn't work either. It's really about that I want to check the logs in the fixture after the actual test, but I guess the captured logs are cleared after the test and before the end of the fixture.
I found the answer with the help of this post.
First, since pytest uses the standard python logging module under the hood, the logs from loguru need to be captured properly. This can be done using the pytest-loguru module, according to the loguru docs.
Install pytest-loguru with: pip install pytest-loguru
Then the fixture can be written as:
import logging
from _pytest.logging import LogCaptureFixture
@pytest.fixture(autouse=True)
def assert_no_log_error(caplog: LogCaptureFixture):
yield
for record in caplog.get_records('call'):
assert record.levelno < logging.ERROR