Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 38 ยท Tests and Assertions

Testing Exceptions

Learn how to test that code raises the right exception with pytest.raises, check messages with match, inspect the exception object, and handle exception groups.

Good code does not only return correct answers; it also refuses bad input in a clear way. A function that divides should raise ZeroDivisionError for a zero divisor. A parser should raise ValueError with a helpful message. If you do not test those paths, they quietly rot, and the first person to discover that your error handling is broken is your user.

pytest gives you one tool for this: the pytest.raises context manager. The test passes only if the code inside the with block raises the exception you named.

The basic pattern

Python pytest.raises basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first test passes. The second fails because a different exception escapes (pytest shows it), and the third fails with DID NOT RAISE. Both failure modes are exactly what you want from a test.

You can name several types in a tuple, pytest.raises((KeyError, IndexError)). A subclass also matches, because the check is isinstance.

Checking the message with match

The type alone is often too vague: dozens of problems raise ValueError. Use match, which applies re.search to the string form of the exception:

Python Matching the message

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

match is a regular expression, not plain text. If your message contains special characters such as (, . or ?, escape them with re.escape(...) or a raw string.

Match on the stable part of a message, the words that identify the problem. Matching the whole sentence makes the test break whenever someone improves the wording.

Inspecting the exception

Sometimes you want to look at attributes of the exception: an error code, the offending value, a nested cause. Bind the context manager with as:

Python excinfo gives access to the exception

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

excinfo is an ExceptionInfo object. The most useful attributes are:

Attribute Meaning
excinfo.value the exception instance
excinfo.type the exception class
excinfo.traceback the traceback entries
excinfo.match(pattern) assert the message matches a regex

Put the assertions after the with block, not inside it. Code after the line that raises inside the block never runs, which is a frequent mistake.

Python
with pytest.raises(ValueError) as excinfo:
    parse("bad")
    assert False   # never reached: parse already raised
assert "bad" in str(excinfo.value)    # correct place

Testing the cause and chained exceptions

Python exceptions can chain with raise ... from error. The original is stored in __cause__:

Python Checking __cause__

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exception groups

Python 3.11 added ExceptionGroup for reporting several errors at once. pytest 8 added pytest.RaisesGroup to test them precisely:

Python
def test_group():
    with pytest.RaisesGroup(ValueError, TypeError):
        raise ExceptionGroup("many", [ValueError("a"), TypeError("b")])

It checks the group's structure instead of requiring you to dig through .exceptions by hand.

Making sure something does NOT raise

You do not need a special context manager. Call the code; if it raises, the test fails by itself:

Python
def test_valid_input_is_accepted():
    set_age(30)          # an exception here fails the test

If you want to show intent, add an assert about the result: assert set_age(30) == 30.

Old style: pytest.fail and try/except

Before pytest.raises people wrote try/except and pytest.fail("DID NOT RAISE"). It works, but it is longer and easy to get wrong. Use pytest.raises for exceptions and pytest.fail("message") only for the cases where you must fail a test explicitly, for example in a branch that should be unreachable.

Testing messages of the exception you do not control

Sometimes the exception comes from the standard library and its wording changes between Python versions. Match only the part you can rely on, or skip matching and assert on the type:

Python
with pytest.raises(ValueError):
    int("not a number")

That is usually better than depending on text such as invalid literal for int() with base 10.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens if the code inside pytest.raises(ValueError) raises nothing?

    pytest.raises requires the exception to occur. If nothing is raised, the test fails with DID NOT RAISE.
  2. 2. What type is the match argument?

    match uses re.search on str(exception), so special regex characters must be escaped.
  3. 3. Where should assertions about excinfo.value be placed?

    Lines after the raising call inside the block never run. Inspect excinfo after the block ends.
  4. 4. How do you assert that a call does NOT raise?

    An unhandled exception fails the test automatically, so no special wrapper is needed.

Summary

  • with pytest.raises(SomeError): passes only if that exception (or a subclass) is raised.
  • match="regex" checks the message with re.search; match the stable part.
  • as excinfo gives excinfo.value, .type and .traceback; inspect them after the block.
  • Check chained errors through excinfo.value.__cause__.
  • pytest.RaisesGroup tests exception groups.
  • To check that code works without raising, just call it.

Next: Comparing Floats with approx