How to Test Logging in pytest: Simple Guide with Examples
To test logging in
pytest, use the built-in caplog fixture which captures log messages during test execution. You can assert on caplog.records or caplog.text to verify that expected logs were emitted.Syntax
The caplog fixture in pytest captures log messages during a test. You can access:
caplog.records: a list of log records with attributes likelevelnameandmessage.caplog.text: a string with all captured log messages.- You can also set the log level with
caplog.set_level()to capture logs of specific severity.
python
def test_logging_example(caplog): import logging logger = logging.getLogger('mylogger') caplog.set_level(logging.INFO) logger.info('Info message') assert 'Info message' in caplog.text
Example
This example shows how to test that a logger emits an error message. It sets the log level to ERROR and asserts the message is captured.
python
import logging def function_that_logs(): logger = logging.getLogger('myapp') logger.error('An error occurred') def test_error_logging(caplog): caplog.set_level(logging.ERROR, logger='myapp') function_that_logs() assert any(record.levelname == 'ERROR' and 'error occurred' in record.message for record in caplog.records)
Output
============================= test session starts =============================
collected 1 item
test_logging.py . [100%]
============================== 1 passed in 0.01s ==============================
Common Pitfalls
Common mistakes when testing logging in pytest include:
- Not setting the log level with
caplog.set_level(), so logs below WARNING are not captured by default. - Checking
caplog.textwithout considering log level or logger name filters. - Assuming logs are captured automatically without using the
caplogfixture.
python
import logging def test_wrong_logging(caplog): logger = logging.getLogger('test') logger.info('Info message') # This will fail because default level is WARNING assert 'Info message' not in caplog.text def test_right_logging(caplog): logger = logging.getLogger('test') caplog.set_level(logging.INFO) logger.info('Info message') assert 'Info message' in caplog.text
Quick Reference
- caplog.set_level(level, logger=None): Set minimum log level to capture.
- caplog.records: List of log records to inspect details.
- caplog.text: All captured logs as a string.
- Use
any()withcaplog.recordsto check for specific log messages and levels.
Key Takeaways
Use pytest's built-in caplog fixture to capture and test log messages.
Always set the appropriate log level with caplog.set_level() to capture desired logs.
Assert on caplog.records for detailed log info or caplog.text for raw log output.
Remember logs below WARNING are not captured by default without setting level.
Check logger names if your code uses multiple loggers to avoid false negatives.