0
0
PyTesttesting~15 mins

Checking exception attributes in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify exception type and message when dividing by zero
Preconditions (2)
Step 1: Write a function that divides two numbers
Step 2: Call the function with divisor as zero inside a test
Step 3: Catch the exception using pytest.raises
Step 4: Check that the exception type is ZeroDivisionError
Step 5: Check that the exception message contains 'division by zero'
✅ Expected Result: Test passes confirming the exception type and message are as expected
Automation Requirements - pytest
Assertions Needed:
Assert exception type is ZeroDivisionError
Assert exception message contains 'division by zero'
Best Practices:
Use pytest.raises context manager to catch exceptions
Use 'as exc_info' to access exception attributes
Assert exception message with 'in' operator for flexibility
Automated Solution
PyTest
import pytest

def divide(a: float, b: float) -> float:
    return a / b

def test_divide_by_zero_raises():
    with pytest.raises(ZeroDivisionError) as exc_info:
        divide(10, 0)
    assert 'division by zero' in str(exc_info.value)

This test defines a simple divide function that divides two numbers.

In the test test_divide_by_zero_raises, we use pytest.raises as a context manager to catch the ZeroDivisionError when dividing by zero.

The as exc_info part captures the exception details, allowing us to check the exception message.

We assert that the string 'division by zero' is part of the exception message to confirm the error is as expected.

Common Mistakes - 3 Pitfalls
Not using pytest.raises and instead using try-except manually
{'mistake': 'Asserting exact exception message equality', 'why_bad': 'Exception messages can vary slightly between Python versions or environments, causing fragile tests.', 'correct_approach': "Use 'in' operator to check if expected text is contained in the exception message."}
{'mistake': 'Not accessing exception message via exc_info.value', 'why_bad': 'Without exc_info, you cannot check exception attributes properly.', 'correct_approach': "Use 'as exc_info' in pytest.raises to access exception object and its message."}
Bonus Challenge

Now add data-driven testing to check exception messages for dividing by zero with different numerators

Show Hint