0
0
PyTesttesting~5 mins

Asserting exceptions (pytest.raises)

Choose your learning style9 modes available
Introduction

We use pytest.raises to check if a piece of code correctly causes an error. This helps us make sure our program handles bad situations safely.

When you want to confirm that a function stops and shows an error for wrong input.
When testing that your code raises the right error type in a problem case.
When you want to catch and check error messages during testing.
When you want to avoid your program crashing silently and instead handle errors properly.
Syntax
PyTest
with pytest.raises(ExpectedException):
    code_that_should_raise()

Use with to start a block where you expect an error.

Replace ExpectedException with the specific error type you expect, like ValueError.

Examples
This checks that dividing by zero raises a ZeroDivisionError.
PyTest
with pytest.raises(ZeroDivisionError):
    x = 1 / 0
This confirms that converting a bad string to int raises a ValueError.
PyTest
with pytest.raises(ValueError):
    int('abc')
This captures the KeyError so you can check its message if needed.
PyTest
with pytest.raises(KeyError) as exc_info:
    d = {}
    d['missing']
Sample Program

This test script has two tests. One checks that dividing by zero raises the right error with the correct message. The other checks normal division works fine.

PyTest
import pytest

def divide(a, b):
    if b == 0:
        raise ZeroDivisionError('Cannot divide by zero')
    return a / b

def test_divide_by_zero():
    with pytest.raises(ZeroDivisionError) as exc_info:
        divide(10, 0)
    assert str(exc_info.value) == 'Cannot divide by zero'

def test_divide_normal():
    assert divide(10, 2) == 5
OutputSuccess
Important Notes

Always specify the exact exception type to avoid catching unexpected errors.

You can capture the exception info with as exc_info to check error messages.

Use pytest.raises inside test functions only.

Summary

pytest.raises helps check if code raises expected errors.

Use it with a with block around code that should fail.

You can also check the error message by capturing the exception info.