Complete the code to capture log messages using caplog.
def test_logging(caplog): with caplog.at_level([1]): logger = logging.getLogger('test') logger.info('Test message') assert 'Test message' in caplog.text
The caplog.at_level() context manager sets the logging level to capture messages. logging.INFO captures info level logs.
Complete the code to check the first captured log message's level name.
def test_log_level_name(caplog): logger = logging.getLogger('test') logger.error('Error occurred') assert caplog.records[0].[1] == 'ERROR'
levelno which is a number, not a string.msg which is the message text.The levelname attribute of a log record gives the level as a string like 'ERROR'.
Fix the error in the code to capture debug messages with caplog.
def test_debug_log(caplog): with caplog.at_level([1]): logger = logging.getLogger('test') logger.debug('Debug info') assert 'Debug info' in caplog.text
Debug messages require the logging level to be set to logging.DEBUG or lower to be captured.
Fill both blanks to filter captured logs by level and check message content.
def test_filter_logs(caplog): logger = logging.getLogger('test') logger.warning('Warning message') logger.error('Error message') filtered = [record for record in caplog.records if record.[1] == [2]] assert any('Warning' in record.msg for record in filtered)
levelno but comparing to a string.levelname to a numeric constant.To filter by level name, use levelname and compare to the string 'WARNING'.
Fill all three blanks to capture logs at error level, check message count, and verify message text.
def test_error_logs_count(caplog): with caplog.at_level([1]): logger = logging.getLogger('test') logger.error('First error') logger.error('Second error') errors = [record for record in caplog.records if record.[2] == [3]] assert len(errors) == 2 assert errors[0].msg == 'First error'
levelno but comparing to string.Set capture level to logging.ERROR. Filter records by levelname equal to 'ERROR'.