pytest.raises()

Assert that a block of code raises a specific exception — the standard way to test error handling itself, not just successful results.

                with pytest.raises(ExceptionType):
              

Purpose

A plain assert checks a returned value — it has no way to check that code raised an exception, since raising skips the rest of the function entirely, including any assert after the call. pytest.raises(ExceptionType) is a context manager built specifically to test that case: the code inside the with block is expected to raise, and the test fails if it doesn’t.

Example

import pytest


def test_parse_positive_int_rejects_negative():
    with pytest.raises(ValueError):
        parse_positive_int("-5")


def test_parse_positive_int_error_message():
    with pytest.raises(ValueError, match="not positive"):
        parse_positive_int("-5")

Behavior notes

  • The test passes when the expected exception is raised inside the block, and fails if no exception is raised at all, or if a different exception type is raised instead — both count as the code not behaving as expected.
  • match="..." (a regular expression checked against str(exception)) additionally verifies the exception’s message, not just its type — useful when a function can raise the same exception type for more than one distinct reason.
  • The result of pytest.raises(...) can be captured with as exc_info to inspect the exception object afterward (exc_info.value), for cases where checking the type and message alone isn’t enough.

Common mistakes

  • Wrapping more code than necessary inside the with pytest.raises(...): block — if setup code that shouldn’t raise is included, the test could pass even though the setup (not the actual function under test) is what raised.
  • Forgetting match= when a function can raise the same exception type for multiple different reasons, which makes it possible to pass a test in error even though the wrong branch of the function under test was actually exercised.

Implementation notes

pytest.raises is provided by the third-party pytest package, not the standard library — unittest’s built-in assertRaises serves the same purpose in that alternative framework.

Taught in these lessons

Related reference