Test Overview
This test checks that only log messages at or above the WARNING level are captured during test execution. It verifies that INFO level messages are filtered out and do not appear in the captured logs.
This test checks that only log messages at or above the WARNING level are captured during test execution. It verifies that INFO level messages are filtered out and do not appear in the captured logs.
import logging import pytest def test_log_level_filtering(caplog): caplog.set_level(logging.WARNING) logging.getLogger().info("This is an info message") logging.getLogger().warning("This is a warning message") assert "This is an info message" not in caplog.text assert "This is a warning message" in caplog.text
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | pytest test runner initialized | — | PASS |
| 2 | caplog fixture sets log capture level to WARNING | Logging system configured to capture WARNING and above | — | PASS |
| 3 | Logger emits INFO level message: 'This is an info message' | INFO message generated but below capture level | — | PASS |
| 4 | Logger emits WARNING level message: 'This is a warning message' | WARNING message generated and captured | — | PASS |
| 5 | Assert INFO message is not in captured logs | Captured logs do not contain INFO message | assert "This is an info message" not in caplog.text | PASS |
| 6 | Assert WARNING message is in captured logs | Captured logs contain WARNING message | assert "This is a warning message" in caplog.text | PASS |
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