Challenge - 5 Problems
pytest.raises Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of pytest.raises with ZeroDivisionError
What will be the output of this test code when run with pytest?
PyTest
import pytest def test_division(): with pytest.raises(ZeroDivisionError): x = 1 / 0 print("Test passed")
Attempts:
2 left
💡 Hint
pytest.raises expects the code inside to raise the specified error to pass.
✗ Incorrect
The code inside the with block raises ZeroDivisionError, which pytest.raises catches, so the test passes and prints 'Test passed'.
❓ assertion
intermediate2:00remaining
Correct assertion to check exception message with pytest.raises
Which option correctly asserts that a ValueError with message 'invalid input' is raised?
PyTest
import pytest def func(): raise ValueError('invalid input') def test_func(): with pytest.raises(ValueError) as excinfo: func() # Which assertion below is correct?
Attempts:
2 left
💡 Hint
Exception message is accessed via str(excinfo.value).
✗ Incorrect
The exception message is stored in excinfo.value and converted to string with str(). The other options access non-existent attributes.
🔧 Debug
advanced2:00remaining
Why does this pytest.raises test fail?
Given this test code, why does pytest report a failure?
PyTest
import pytest def test_error(): with pytest.raises(ValueError): x = int('abc') with pytest.raises(TypeError): x = int('abc')
Attempts:
2 left
💡 Hint
Check the actual error type raised by int('abc').
✗ Incorrect
int('abc') raises ValueError, so the first with block passes but the second expects TypeError and fails.
🧠 Conceptual
advanced2:00remaining
Behavior of pytest.raises when no exception is raised
What happens if the code inside a pytest.raises context manager does NOT raise the expected exception?
Attempts:
2 left
💡 Hint
pytest.raises expects an exception to be raised inside the block.
✗ Incorrect
If no exception is raised, pytest.raises causes the test to fail with a message indicating the expected exception was not raised.
❓ framework
expert3:00remaining
Using pytest.raises to test multiple exception types
Which option correctly tests that a function raises either ValueError or TypeError using pytest.raises?
Attempts:
2 left
💡 Hint
pytest.raises accepts a tuple of exception types to check multiple exceptions.
✗ Incorrect
pytest.raises accepts a tuple of exceptions to check if any of them is raised. The other options are invalid syntax or logic.