0
0
PyTesttesting~15 mins

pytest.raises context manager - 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 divisor as zero inside pytest.raises context manager
Step 3: Check that ZeroDivisionError is raised
✅ Expected Result: Test passes confirming ZeroDivisionError is raised when dividing by zero
Automation Requirements - pytest
Assertions Needed:
Verify ZeroDivisionError is raised when divisor is zero
Best Practices:
Use pytest.raises as a context manager
Keep test function simple and focused
Do not catch exceptions manually inside the test
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 test_divide_by_zero_raises uses pytest.raises as a context manager to check that calling divide(10, 0) raises a ZeroDivisionError.

This is the correct way to test exceptions in pytest because it clearly shows the expected error and keeps the test clean.

Common Mistakes - 3 Pitfalls
Catching the exception manually with try-except inside the test
Not specifying the exception type in pytest.raises
Placing code outside the pytest.raises block that raises the exception
Bonus Challenge

Now add data-driven testing with 3 different pairs of inputs where division by zero should raise ZeroDivisionError

Show Hint