0
0
PyTesttesting~5 mins

pytest.raises context manager

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 mistakes well.

When you want to test if a function raises an error for bad input.
When you want to confirm that your code stops running and shows the right error message.
When you want to catch specific exceptions during testing to avoid crashes.
When you want to verify that your error handling works as expected.
When you want to write tests that expect failures to happen safely.
Syntax
PyTest
with pytest.raises(ExpectedException):
    code_that_should_raise()

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

Put the code that should cause the error inside the with block.

Examples
This test passes if dividing by zero raises a ZeroDivisionError.
PyTest
with pytest.raises(ZeroDivisionError):
    x = 1 / 0
This test checks that converting a non-number string to int raises a ValueError.
PyTest
with pytest.raises(ValueError):
    int('abc')
This test expects a KeyError when accessing a missing dictionary key.
PyTest
with pytest.raises(KeyError):
    d = {}
    value = d['missing']
Sample Program

This test checks that dividing by zero in the divide function raises a ZeroDivisionError. The test will pass if the error happens as expected.

PyTest
import pytest

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

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

if __name__ == '__main__':
    pytest.main([__file__])
OutputSuccess
Important Notes

Always specify the exact exception you expect to catch for clear tests.

If the code inside with pytest.raises() does not raise the error, the test fails.

You can also check the error message by using as exc_info after raises().

Summary

pytest.raises helps test if code raises expected errors.

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

This makes your tests safer and your code more reliable.