Challenge - 5 Problems
Caplog Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this pytest caplog test?
Consider this pytest test using caplog to capture logs. What will be the value of
caplog.records[0].levelname after running the test?PyTest
import logging def test_log_level(caplog): logger = logging.getLogger('mylogger') with caplog.at_level(logging.WARNING): logger.error('Error occurred') print(caplog.records[0].levelname)
Attempts:
2 left
💡 Hint
Remember that logger.error logs at ERROR level, which is higher than WARNING.
✗ Incorrect
The logger logs an error message, which has level ERROR. caplog.records captures the actual log records, so the first record's levelname is 'ERROR'.
❓ assertion
intermediate2:00remaining
Which assertion correctly checks for a log message using caplog?
You want to assert that the log message 'User created' was logged during the test. Which assertion is correct?
PyTest
import logging def test_user_creation_logs(caplog): logger = logging.getLogger('app') logger.info('User created')
Attempts:
2 left
💡 Hint
caplog.messages is a list of log messages as strings.
✗ Incorrect
caplog.messages contains the formatted log messages as strings. So checking caplog.messages[0] equals 'User created' is correct.
🔧 Debug
advanced2:00remaining
Why does this caplog test fail to capture logs?
This test does not capture any logs. What is the reason?
PyTest
import logging def test_no_logs(caplog): logger = logging.getLogger('mylogger') logger.setLevel(logging.ERROR) with caplog.at_level(logging.WARNING): logger.info('Info message') assert len(caplog.records) == 1
Attempts:
2 left
💡 Hint
Logger's own level controls which messages it emits.
✗ Incorrect
Logger's level is ERROR, so it ignores INFO messages. caplog.at_level sets capture level but does not override logger's level.
❓ framework
advanced2:00remaining
How to capture logs from a specific logger using caplog?
You want to capture logs only from the logger named 'myapp.database'. Which caplog usage is correct?
Attempts:
2 left
💡 Hint
caplog.at_level accepts a logger parameter to filter logs.
✗ Incorrect
Using caplog.at_level with logger='myapp.database' captures logs only from that logger at INFO level.
🧠 Conceptual
expert2:00remaining
What is the main difference between caplog.records and caplog.messages?
Choose the best explanation of the difference between caplog.records and caplog.messages in pytest.
Attempts:
2 left
💡 Hint
Think about raw log data vs formatted text.
✗ Incorrect
caplog.records holds LogRecord objects with detailed info; caplog.messages holds just the formatted message strings.