0
0
PyTesttesting~15 mins

Asserting exceptions (pytest.raises) - Build an Automation Script

Choose your learning style9 modes available
Verify that dividing by zero raises a ZeroDivisionError
Preconditions (2)
Step 1: Write a function that divides two numbers
Step 2: Call the function with the second number as zero
Step 3: Check that calling the function raises a ZeroDivisionError
✅ Expected Result: The test should pass only if ZeroDivisionError is raised when dividing by zero
Automation Requirements - pytest
Assertions Needed:
Assert that ZeroDivisionError is raised when dividing by zero
Best Practices:
Use pytest.raises context manager to catch exceptions
Keep test functions simple and focused
Name test functions starting with 'test_'
Avoid catching exceptions manually with try-except in tests
Automated Solution
PyTest
import pytest

def divide(a, b):
    return a / b

def test_divide_by_zero_raises():
    with pytest.raises(ZeroDivisionError):
        divide(10, 0)

The divide function simply divides two numbers.

The test function test_divide_by_zero_raises uses pytest.raises as a context manager to check that dividing by zero raises a ZeroDivisionError.

If the exception is raised, the test passes. If not, pytest fails the test.

This approach is clean and clear, following pytest best practices.

Common Mistakes - 3 Pitfalls
Using try-except block manually to catch exceptions in test
Not specifying the exception type in pytest.raises
{'mistake': "Writing test function names that do not start with 'test_'", 'why_bad': 'pytest will not discover or run these tests automatically.', 'correct_approach': "Name test functions starting with 'test_'."}
Bonus Challenge

Now add data-driven testing to check that dividing by zero raises ZeroDivisionError for multiple numerators: 10, -5, and 0

Show Hint