What if you could catch every error detail automatically and never miss a bug again?
Why Checking exception attributes in PyTest? - Purpose & Use Cases
Imagine you are testing a calculator app manually. You try to divide by zero and expect an error. You write down what error message you see and hope it matches what you expect.
Manually checking error messages is slow and easy to miss details. You might forget to check the exact error type or the message text. This can cause bugs to slip through and confuse users later.
Using pytest to check exception attributes lets you automatically catch errors and verify their exact type and message. This saves time and ensures your app handles errors correctly every time.
try: divide(5, 0) except Exception as e: assert 'error' in str(e)
import pytest with pytest.raises(ZeroDivisionError) as excinfo: divide(5, 0) assert 'division by zero' in str(excinfo.value)
You can confidently test that your code raises the right errors with the right messages, catching bugs early and improving quality.
When building a login system, you want to check that entering a wrong password raises a specific error with a clear message. This helps you handle errors gracefully and inform users properly.
Manual error checks are slow and unreliable.
pytest lets you catch and check error details automatically.
This improves test accuracy and saves time.
Practice
pytest.raises?Solution
Step 1: Use
This syntax captures the exception info object for inspection.pytest.raiseswithas exc_infoStep 2: Access the exception instance via
The actual exception object is stored inexc_info.valueexc_info.value, allowing attribute checks like the message.Final Answer:
Usewith pytest.raises(ValueError) as exc_info:and then checkexc_info.value. -> Option DQuick Check:
Exception captured = exc_info.value [OK]
- Not using 'as exc_info' to capture exception
- Trying to access exc_info.message instead of exc_info.value
- Using pytest.raises outside a with block
Solution
Step 1: Access exception instance via
The exception object is stored inexc_info.valueexc_info.value.Step 2: Convert exception to string to get message
Usingstr(exc_info.value)returns the exception message text.Final Answer:
assert str(exc_info.value) == 'error occurred' -> Option CQuick Check:
Exception message = str(exc_info.value) [OK]
- Trying to access exc_info.message which does not exist
- Using exc_info.error which is invalid
- Assuming exc_info.value.message always exists
def divide(x, y):
if y == 0:
raise ZeroDivisionError('Cannot divide by zero')
return x / y
def test_divide():
with pytest.raises(ZeroDivisionError) as exc_info:
divide(5, 0)
assert str(exc_info.value) == 'Cannot divide by zero'Solution
Step 1: The function raises ZeroDivisionError with correct message
Calling divide(5, 0) raises ZeroDivisionError with message 'Cannot divide by zero'.Step 2: The test captures exception and asserts message
Usingpytest.raisescaptures the exception, andstr(exc_info.value)matches the expected message.Final Answer:
The test passes because the exception message matches exactly. -> Option BQuick Check:
Exception type and message match = pass [OK]
- Assuming exception message is accessed by exc_info.message
- Not using 'as exc_info' to capture exception
- Confusing exception type with message
def test_error():
with pytest.raises(ValueError) as exc_info:
raise ValueError('Invalid input')
assert exc_info.message == 'Invalid input'Solution
Step 1: Check how exception message is accessed
The exception message is not stored inexc_info.message, but must be accessed viastr(exc_info.value).Step 2: Correct assertion syntax
Replaceassert exc_info.message == 'Invalid input'withassert str(exc_info.value) == 'Invalid input'.Final Answer:
Usingexc_info.messageinstead ofstr(exc_info.value)to check message. -> Option AQuick Check:
Exception message accessed via str(exc_info.value) [OK]
- Trying to access exc_info.message which does not exist
- Not raising exception inside with block
- Incorrect pytest.raises syntax
MyError that has an attribute code. Which pytest code correctly checks both the exception type and the code attribute value?Solution
Step 1: Capture exception with
This allows access to the exception instance and its attributes.as exc_infoStep 2: Access custom attribute
The exception instance iscodeonexc_info.valueexc_info.value, soexc_info.value.codeaccesses the attribute.Final Answer:
with pytest.raises(MyError) as exc_info: raise MyError('fail', code=404) assert exc_info.value.code == 404 -> Option AQuick Check:
Custom attribute checked via exc_info.value.code [OK]
- Trying to access exc_info.code instead of exc_info.value.code
- Not using 'as exc_info' to capture exception
- Comparing str(exc_info.value) to a number
Ready to prove it?
Pass the test and this pattern moves unknown
