Recall & Review
beginner
What is the purpose of the
pytest.raises context manager?It is used to check that a specific exception is raised during the execution of a block of code in a test.
Click to reveal answer
beginner
How do you use
pytest.raises to test if a function raises a ValueError?Use it as a context manager like this:<br>
with pytest.raises(ValueError):
function_that_raises()Click to reveal answer
beginner
What happens if the expected exception is not raised inside the
pytest.raises block?The test will fail because
pytest.raises expects the specified exception to occur.Click to reveal answer
intermediate
Can
pytest.raises capture the exception object for further checks?Yes, by using the
as keyword, you can capture the exception and inspect its message or attributes.<br>Example:<br>with pytest.raises(ValueError) as exc_info:
function_that_raises()
assert 'error message' in str(exc_info.value)Click to reveal answer
intermediate
Why is using
pytest.raises better than a try-except block in tests?Because it makes tests cleaner and more readable by clearly showing the expected exception, and it automatically fails the test if the exception is not raised.
Click to reveal answer
What does
pytest.raises(ValueError) check for?✗ Incorrect
pytest.raises(ValueError) expects a ValueError exception to be raised inside its block.
How do you capture the exception object with
pytest.raises?✗ Incorrect
Use as exc_info to capture the exception object for inspection.
What happens if the expected exception is not raised inside
pytest.raises?✗ Incorrect
If the expected exception is not raised, pytest.raises causes the test to fail.
Which of these is a correct way to test that
my_func() raises a KeyError?✗ Incorrect
The correct syntax uses with pytest.raises(KeyError): as a context manager.
Why is
pytest.raises preferred over manual try-except in tests?✗ Incorrect
pytest.raises improves readability and test reliability by clearly expecting exceptions.
Explain how to use
pytest.raises to test that a function raises a specific exception and how to check the exception message.Think about capturing the exception and then asserting on its message.
You got /4 concepts.
Describe what happens when the expected exception is not raised inside a
pytest.raises block during test execution.Consider the purpose of expecting exceptions in tests.
You got /3 concepts.