Challenge - 5 Problems
Custom Exception Testing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of pytest test for custom exception
What is the test result when running this pytest code that checks for a custom exception?
PyTest
import pytest class MyError(Exception): pass def func(): raise MyError("fail") def test_func_raises(): with pytest.raises(MyError): func()
Attempts:
2 left
💡 Hint
pytest.raises expects the specified exception to be raised inside the with block.
✗ Incorrect
The test passes because func() raises MyError as expected, so pytest.raises catches it and the test succeeds.
❓ assertion
intermediate2:00remaining
Correct assertion to test exception message
Which assertion correctly tests that the exception message contains the word 'timeout'?
PyTest
import pytest def func(): raise TimeoutError("Connection timeout occurred") def test_func(): with pytest.raises(TimeoutError) as exc_info: func() # Which assertion below is correct here?
Attempts:
2 left
💡 Hint
Exception message is accessed by converting exc_info.value to string.
✗ Incorrect
The exception message is stored in exc_info.value and converting it to string shows the message. The other options access non-existent attributes or expect exact match.
🔧 Debug
advanced2:00remaining
Identify the error in this pytest exception test
Why does this pytest test fail with an error instead of passing?
PyTest
import pytest class CustomError(Exception): pass def func(): raise CustomError("error") def test_func(): with pytest.raises(CustomError): func
Attempts:
2 left
💡 Hint
Check how func is called inside the with block.
✗ Incorrect
The test fails because func is referenced but not called (missing parentheses), so no exception is raised and pytest.raises fails.
🧠 Conceptual
advanced2:00remaining
Why use custom exceptions in testing?
What is the main advantage of defining and testing custom exceptions in your code?
Attempts:
2 left
💡 Hint
Think about how custom exceptions help in identifying specific problems.
✗ Incorrect
Custom exceptions help identify specific error conditions clearly, making tests more precise and easier to understand.
❓ framework
expert2:00remaining
Best pytest pattern for testing multiple custom exceptions
You want to test that a function raises either CustomErrorA or CustomErrorB depending on input. Which pytest pattern correctly tests this in one test function?
Attempts:
2 left
💡 Hint
Check pytest documentation for multiple exceptions in raises.
✗ Incorrect
pytest.raises accepts a tuple of exception classes to check for multiple possible exceptions in one test.