Verify log messages are filtered by log level
Preconditions (2)
✅ Expected Result: Only INFO, WARNING, and ERROR log messages are captured; DEBUG messages are filtered out
import logging import pytest # Function that logs messages at different levels def log_messages(): logger = logging.getLogger('test_logger') logger.debug('Debug message') logger.info('Info message') logger.warning('Warning message') logger.error('Error message') def test_log_level_filtering(caplog): logger = logging.getLogger('test_logger') logger.setLevel(logging.INFO) # Set log level to INFO with caplog.at_level(logging.INFO, logger='test_logger'): log_messages() # Extract captured log messages messages = [record.getMessage() for record in caplog.records] # Assertions assert 'Debug message' not in messages, 'DEBUG messages should be filtered out' assert 'Info message' in messages, 'INFO message should be captured' assert 'Warning message' in messages, 'WARNING message should be captured' assert 'Error message' in messages, 'ERROR message should be captured'
The log_messages function logs messages at four levels.
In the test test_log_level_filtering, we set the logger level to INFO to filter out DEBUG messages.
We use pytest's caplog fixture to capture logs during the function call.
After running the function, we collect all log messages and assert that DEBUG messages are not present, while INFO, WARNING, and ERROR messages are present.
This approach ensures the log level filtering works as expected.
Now add data-driven testing with 3 different logger levels: DEBUG, INFO, WARNING. Verify that only messages at or above the set level are captured.
caplog.at_level() do in pytest?caplog is a pytest fixture used to capture log messages during tests.at_level()at_level() sets the minimum log level to capture, filtering out lower-level messages.caplog.at_level() used with with statement.with caplog.at_level(logging.WARNING): which is the documented and correct syntax.import logging
def test_logs(caplog):
with caplog.at_level(logging.ERROR):
logging.warning('Warning message')
logging.error('Error message')
return caplog.records
caplog.at_level(logging.ERROR) captures logs at ERROR level or higher only.def test_example(caplog):
caplog.at_level(logging.INFO)
logging.debug('Debug message')
logging.info('Info message')
assert 'Info message' in caplog.text
at_level() must be used with a with statement to set the log level context.caplog.at_level(logging.INFO) without with does not set the level properly, so logs may not be filtered as expected.caplog.at_level(logging.INFO) captures INFO and ERROR logs but excludes DEBUG logs.Pass the test and this pattern moves unknown