Recall & Review
beginner
What is the purpose of matching exception messages in pytest?
Matching exception messages helps verify that the error raised is not only of the correct type but also contains the expected message, ensuring precise error handling.
Click to reveal answer
beginner
How do you check for a specific exception message in pytest?
Use the
pytest.raises() context manager with the match parameter to specify a regex pattern that the exception message should match.Click to reveal answer
beginner
Example: Write a pytest snippet to check if a
ValueError is raised with message containing 'invalid input'.import pytest
def test_invalid_input():
with pytest.raises(ValueError, match="invalid input"):
raise ValueError("This is an invalid input error")Click to reveal answer
intermediate
Why use regex patterns in the
match parameter instead of exact strings?Regex allows flexible matching of exception messages, handling variations like additional details or formatting, making tests less brittle.
Click to reveal answer
beginner
What happens if the exception message does not match the pattern in pytest?
The test fails because pytest expects the exception message to match the pattern. This ensures the error is exactly what the test expects.
Click to reveal answer
Which pytest feature lets you check for an exception and its message?
✗ Incorrect
pytest.raises() with the match parameter is the correct way to check both exception type and message.
What type of pattern does the
match parameter in pytest accept?✗ Incorrect
The match parameter accepts a regex pattern to flexibly match exception messages.
If the exception message is 'File not found', which match pattern will correctly match it?
✗ Incorrect
The regex "File.*found" matches any characters between 'File' and 'found', covering the message.
What happens if the exception type is correct but the message does not match the pattern?
✗ Incorrect
The test fails because both exception type and message must match.
Why is matching exception messages useful in testing?
✗ Incorrect
Matching messages confirms the error is exactly what the test expects, improving test accuracy.
Explain how to use pytest to check that a function raises a ValueError with a specific message.
Think about how to combine exception type and message checking in pytest.
You got /3 concepts.
Describe why using regex patterns for matching exception messages is better than exact string matching.
Consider how error messages might change slightly but still be valid.
You got /3 concepts.