Interview frequency: …
Short answer
Use pytest.raises (or assertRaises in unittest) as a context manager around only the line expected to fail, and check the type and the important fields or part of the message through match.
Explanation
Make the raises block wrap only the line that must fail, so the test does not pass because of an exception from another setup line. Check the minimal contract: the exception type and structured fields are better than matching the whole message, because wording changes. match accepts a regular expression, so use re.escape if the message contains special characters.
Code example
import pytest
def test_withdraw_more_than_balance():
account = Account(balance=10)
with pytest.raises(InsufficientFunds, match="balance") as exc_info:
account.withdraw(50)
assert exc_info.value.missing == 40Common mistakes
- Putting the entire test inside pytest.raises, so it passes because of an unexpected error.
- Matching the full message text, so the test fails on any wording change.