0
0
PyTesttesting~3 mins

Why Asserting exceptions (pytest.raises)? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your tests could catch hidden errors automatically, saving you hours of frustration?

The Scenario

Imagine you have a calculator app and you want to check if it stops when dividing by zero. You try it yourself every time, typing numbers and watching for errors.

The Problem

Doing this by hand is slow and easy to miss mistakes. You might forget to check some cases or not notice the error message. It's tiring and not reliable.

The Solution

Using pytest.raises lets you write a small test that automatically checks if the error happens. It runs fast and never forgets to check, so you catch problems early.

Before vs After
Before
try:
    divide(5, 0)
except ZeroDivisionError:
    print('Error caught')
After
import pytest

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

def test_divide_zero():
    with pytest.raises(ZeroDivisionError):
        divide(5, 0)
What It Enables

You can trust your code to handle errors correctly without testing each case by hand.

Real Life Example

When building a website, you want to be sure it shows a friendly message if a user enters wrong data. Using pytest.raises helps test those error cases automatically.

Key Takeaways

Manual error checks are slow and unreliable.

pytest.raises automates checking for expected errors.

This makes tests faster, clearer, and more trustworthy.