caplog in pytest?caplog is used to capture log messages during test execution. It helps verify that the expected logs are generated by the code under test.
caplog?You can access captured logs via caplog.records for log records or caplog.text for the full log output as a string.
caplog in a test?Use caplog.set_level("LEVEL") to set the minimum log level to capture, for example caplog.set_level("INFO").
caplog to check if a warning log message was emitted.def test_warning_log(caplog):
import logging
logger = logging.getLogger()
with caplog.at_level(logging.WARNING):
logger.warning("This is a warning")
assert "This is a warning" in caplog.textCapturing logs helps confirm that the code behaves as expected internally, especially for warnings, errors, or important info messages, improving test coverage and debugging.
caplog.records provide in pytest?caplog.records gives a list of log record objects, each representing a captured log message with details like level and message.
caplog?Setting caplog.set_level("WARNING") captures warnings and errors, ignoring info and debug logs.
The correct fixture name is caplog.
Using assert "message" in caplog.text is a direct and automated way to verify logs.
caplog.at_level(logging.WARNING) do?This context manager temporarily sets the capture level to WARNING for the code inside the block.
caplog in pytest to verify that a specific log message was generated.caplog is helpful in automated testing.