Complete the code to capture log messages using pytest.
def test_log_capture(caplog): with caplog.[1](level="INFO"): logger = logging.getLogger() logger.info("Hello")
The caplog.at_level() method sets the logging level to capture messages at or above that level.
Complete the code to assert that a log message contains the expected text.
def test_log_message(caplog): with caplog.at_level("WARNING"): logger = logging.getLogger() logger.warning("Disk space low") assert "[1]" in caplog.text
The caplog.text contains all captured log messages as a single string. We check if the expected message is present.
Fix the error in the assertion to check the first captured log record's message.
def test_first_log_message(caplog): with caplog.at_level("ERROR"): logger = logging.getLogger() logger.error("Failure occurred") assert caplog.records[0].[1] == "Failure occurred"
The LogRecord object has a msg attribute that stores the log message.
Fill both blanks to assert that the log level of the first record is ERROR and the message contains 'critical'.
def test_log_level_and_message(caplog): with caplog.at_level("ERROR"): logger = logging.getLogger() logger.error("A critical failure happened") assert caplog.records[0].[1] == logging.[2] assert "critical" in caplog.records[0].msg
The levelno attribute holds the numeric log level. logging.ERROR is the constant for the ERROR level.
Fill all three blanks to capture logs at INFO level, log an info message, and assert the message is captured.
def test_info_log_capture(caplog): with caplog.[1]("INFO"): logger = logging.getLogger() logger.[2]("Process started") assert "[3]" in caplog.text
Use caplog.at_level to set capture level, logger.info to log an info message, and check the message text in caplog.text.