Which pytest code snippet correctly asserts that a ValueError is raised with the exact message 'Invalid input' when calling func()?
def func(): raise ValueError('Invalid input')
Check the correct parameter name for matching exception messages in pytest.raises.
Option C uses the correct match parameter to check the exception message exactly. Option C is valid code but does not use the match parameter directly. Option C uses a wrong parameter message. Option C uses match but with wrong case, so it won't match exactly.
What will happen when running this pytest test?
def func():
raise RuntimeError('File not found error')
def test_func():
with pytest.raises(RuntimeError, match='not found'):
func()def func(): raise RuntimeError('File not found error') def test_func(): with pytest.raises(RuntimeError, match='not found'): func()
Remember that match uses regular expression search, so partial matches work.
Option D is correct because match uses regex search, so 'not found' matches the message 'File not found error'. Option D is wrong because exact full message match is not required. Option D is wrong because match is valid. Option D is wrong because exception type matches.
Given this code, why does the test fail?
def func():
raise KeyError('missing key')
def test_func():
with pytest.raises(KeyError, match=r'^missing key$'):
func()def func(): raise KeyError('missing key') def test_func(): with pytest.raises(KeyError, match=r'^missing key$'): func()
Check how Python formats KeyError messages.
KeyError messages include quotes around the key, so the actual message is "'missing key'" including quotes. The match='missing key' does not match because it lacks quotes. Option A explains this correctly. Options A, B, and D are incorrect.
Which practice is best when matching exception messages in pytest tests?
Think about test maintenance and message variability.
Option A is best because using match with a substring or regex makes tests less brittle to message changes. Option A is too strict and fragile. Option A loses message verification. Option A is more verbose and less clean.
What is the behavior of the match parameter in pytest.raises when matching exception messages?
Recall how match uses regex internally.
The match parameter uses Python's re.search on the exception message string, so it looks for a regex pattern anywhere in the message. It does not require exact equality or start matching only. It does not match the exception type name.