B. caplog.at_level() must be used as a context manager with 'with'.
C. caplog.text does not exist; use caplog.records instead.
D. Logging messages must be uppercase strings.
Solution
Step 1: Check caplog.at_level usage
The method at_level() must be used with a with statement to set the log level context.
Step 2: Identify the error
Calling caplog.at_level(logging.INFO) without with does not set the level properly, so logs may not be filtered as expected.
Final Answer:
caplog.at_level() must be used as a context manager with 'with'. -> Option B
Quick Check:
Use 'with caplog.at_level(level):' always [OK]
Hint: Always use 'with' when calling caplog.at_level() [OK]
Common Mistakes:
Calling at_level() without 'with' statement
Assuming caplog.text is invalid (it exists)
Thinking assert syntax is wrong
5. You want to test a function that logs messages at DEBUG, INFO, and ERROR levels. You only want to capture INFO and ERROR logs but exclude DEBUG. Which pytest code snippet correctly sets this up?
hard
A. with caplog.at_level(logging.ERROR):
func()
assert 'INFO message' in caplog.text
B. with caplog.at_level(logging.DEBUG):
func()
assert 'INFO message' in caplog.text
C. with caplog.at_level(logging.INFO):
func()
assert 'DEBUG message' in caplog.text
D. with caplog.at_level(logging.INFO):
func()
assert 'DEBUG message' not in caplog.text
Solution
Step 1: Determine log levels to capture
Setting caplog.at_level(logging.INFO) captures INFO and ERROR logs but excludes DEBUG logs.
Step 2: Verify assertions
with caplog.at_level(logging.INFO):
func()
assert 'DEBUG message' not in caplog.text asserts DEBUG messages are not in captured logs, which matches the requirement.
Final Answer:
with caplog.at_level(logging.INFO):
func()
assert 'DEBUG message' not in caplog.text -> Option D
Quick Check:
Set level INFO to exclude DEBUG logs [OK]
Hint: Set level to INFO to exclude DEBUG logs [OK]
Common Mistakes:
Setting level too low and capturing DEBUG logs
Setting level too high and missing INFO logs
Wrong assertion about presence of DEBUG logs
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.