We check log messages to make sure our program reports important events correctly. This helps us find problems and understand what happened during a test.
0
0
Asserting log messages in PyTest
Introduction
When you want to confirm that a warning or error message is shown during a test.
When your code logs important steps and you want to verify those steps happened.
When debugging and you want to ensure specific log messages appear for certain actions.
When testing that sensitive information is not logged by mistake.
When you want to check that your logging setup works as expected.
Syntax
PyTest
with caplog.at_level(logging.LEVEL): # code that triggers logging assert 'expected message' in caplog.text
caplog is a pytest fixture that captures log messages during tests.
You can set the log level with caplog.at_level() to capture messages of that level or higher.
Examples
This test checks that a warning message is logged.
PyTest
def test_warning_log(caplog): import logging with caplog.at_level(logging.WARNING): logging.warning('This is a warning') assert 'This is a warning' in caplog.text
This test asserts the error message appears in the captured logs.
PyTest
def test_error_log(caplog): import logging with caplog.at_level(logging.ERROR): logging.error('Error happened') assert any('Error happened' in msg for msg in caplog.messages)
Sample Program
This test runs a function that logs messages at different levels. It then checks that all these messages appear in the captured logs.
PyTest
import logging import pytest def function_that_logs(): logging.info('Starting process') logging.warning('A warning occurred') logging.error('An error occurred') def test_logs(caplog): with caplog.at_level(logging.INFO): function_that_logs() assert 'Starting process' in caplog.text assert 'A warning occurred' in caplog.text assert 'An error occurred' in caplog.text if __name__ == '__main__': pytest.main([__file__])
OutputSuccess
Important Notes
Always import logging to use log levels and log messages.
Use caplog.text to get all captured logs as one string, or caplog.records for detailed log records.
Set the log level carefully to capture the messages you want.
Summary
Use caplog fixture to capture logs in pytest tests.
Check log messages with assertions on caplog.text or caplog.messages.
Set log level with caplog.at_level() to control which messages are captured.