Challenge - 5 Problems
Warning Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of pytest.warns context usage
What will be the output of this pytest test when run?
PyTest
import warnings import pytest def test_warning_capture(): with pytest.warns(DeprecationWarning) as record: warnings.warn("Deprecated feature", DeprecationWarning) return len(record) result = test_warning_capture()
Attempts:
2 left
💡 Hint
Count how many warnings are captured inside the context.
✗ Incorrect
The pytest.warns context captures warnings of the specified type. Since one DeprecationWarning is issued, the record contains one warning, so len(record) is 1.
❓ assertion
intermediate2:00remaining
Correct assertion to check warning message
Which assertion correctly verifies that the warning message contains the word 'deprecated'?
PyTest
import warnings import pytest def test_warning_message(): with pytest.warns(UserWarning) as record: warnings.warn("This feature is deprecated", UserWarning) warning_message = str(record[0].message) # Which assertion below is correct?
Attempts:
2 left
💡 Hint
Check if the substring is anywhere in the message.
✗ Incorrect
The warning message is 'This feature is deprecated', so checking if 'deprecated' is contained anywhere is correct. Exact equality or startswith will fail.
🔧 Debug
advanced2:00remaining
Identify the error in warning assertion
What error will this test raise when run?
PyTest
import warnings import pytest def test_wrong_warning(): with pytest.warns(DeprecationWarning): warnings.warn("Use new API", UserWarning)
Attempts:
2 left
💡 Hint
Check if the warning type matches the expected one.
✗ Incorrect
The test expects a DeprecationWarning but the code issues a UserWarning. pytest.warns raises AssertionError if the expected warning is not raised.
❓ framework
advanced2:00remaining
Using pytest.warns as a function decorator
Which option correctly uses pytest.warns as a decorator to check for a warning?
PyTest
import warnings import pytest # Choose the correct decorator usage
Attempts:
2 left
💡 Hint
Check the correct decorator name and matching warning type.
✗ Incorrect
pytest.warns can be used as a decorator to check that the decorated function raises the specified warning. Option D correctly uses it with matching warning type.
🧠 Conceptual
expert2:00remaining
Behavior of pytest.warns with multiple warnings
If a code block inside pytest.warns(WarningType) emits multiple warnings, how does pytest.warns behave?
Attempts:
2 left
💡 Hint
Think about how pytest.warns matches warnings inside the block.
✗ Incorrect
pytest.warns passes if at least one warning of the expected type is raised. It does not fail if multiple warnings occur, nor does it fail for other warnings unless they cause test failure separately.