1. Home
  2. Blog
  3. Test Automation

Test Automation

Pytest raises: Testing Exceptions, match and excinfo

pytest raises lets a test assert that code fails in exactly the way it should. Learn the context manager, matching messages with regular expressions, inspecting the exception with excinfo, custom exceptions and chained causes, parametrized error cases, pytest.warns, and the three mistakes that make exception tests lie, with every test run.

9 min read
Pytest raises: testing exceptions, match and excinfo

Key takeaways

  • with pytest.raises(ValueError): passes only if the block raises that exception type or a subclass.
  • match= takes a regular expression searched in the message; use re.escape for literal text with brackets or dots.
  • as exc gives you the exception object to check custom attributes and causes.
  • Code after the line that raises never runs, so keep only the failing call inside the block.

Good code fails loudly and predictably: withdrawing more than the balance should raise an error, not quietly produce a negative number. Those failure paths deserve tests as much as the happy path, and pytest raises is the tool pytest provides for them. It is simple, but a couple of details decide whether your exception tests protect you or silently pass.

All tests ran with Python 3.13.6 and pytest 9.2.0. The main suite produced 11 passed, and a second file of deliberate mistakes produced the failures shown below. New to pytest? Start with our pytest tutorial.

Why test exceptions?

  • They prove that invalid input is rejected instead of corrupting data.
  • They pin down the error type and message that callers and API clients depend on.
  • They stop regressions where a refactor accidentally removes a validation check.

The code under test

# bank.py
class InsufficientFunds(ValueError):
    def __init__(self, balance, amount):
        super().__init__(f"balance {balance} is less than {amount}")
        self.balance, self.amount = balance, amount

def withdraw(balance, amount):
    if amount <= 0:
        raise ValueError("amount must be positive")
    if amount > balance:
        raise InsufficientFunds(balance, amount)
    return balance - amount

def parse_qty(s):
    try:
        return int(s)
    except ValueError as e:
        raise TypeError(f"qty must be a whole number, got {s!r}") from e

A custom exception that subclasses ValueError, carries useful attributes and chains from a lower-level error: typical of real code. Our exception handling guide covers how to design exceptions like this.

Basic usage: the context manager

import pytest
from bank import withdraw

def test_raises_type():
    with pytest.raises(ValueError):
        withdraw(100, -5)

The test passes because withdraw raised ValueError inside the with block. If no exception is raised, or a different type escapes, the test fails. The context manager form is the one to use; an older form, pytest.raises(ValueError, func, *args), still exists but is harder to read.

Matching the error message

def test_match_message():
    with pytest.raises(ValueError, match="must be positive"):
        withdraw(100, 0)

Checking the type alone can pass for the wrong reason: many things raise ValueError. Adding match ties the test to the specific failure. The pattern is searched within the message, like re.search, so a distinctive fragment is enough; you do not need the whole sentence.

match is a regular expression

def test_match_is_regex():
    with pytest.raises(InsufficientFunds, match=r"balance \d+ is less than 150"):
        withdraw(100, 150)

Because match is a regex, you can match variable parts like \d+. Use raw strings (r"...") so backslashes reach the regex engine untouched. The flip side: characters like (, ., [ and $ have special meaning, which causes one of the mistakes shown below. Our Python regex guide explains the syntax.

Inspecting the exception with excinfo

def test_excinfo_attributes():
    with pytest.raises(InsufficientFunds) as exc:
        withdraw(100, 150)
    assert exc.value.amount == 150
    assert exc.type is InsufficientFunds
    assert "less than" in str(exc.value)

as exc gives you an ExceptionInfo object. exc.value is the exception instance, exc.type its class, and exc.traceback the traceback. Put the extra assertions after the with block; inside it, nothing after the raising call would run.

Subclasses count as a match

def test_subclass_is_accepted():
    with pytest.raises(ValueError):
        withdraw(100, 150)   # raises InsufficientFunds, a ValueError subclass

Like an except clause, pytest.raises(ValueError) also accepts subclasses. That is convenient but can hide a change in behaviour. If the exact type matters, assert it with exc.type is InsufficientFunds. Never write pytest.raises(Exception): almost anything, including a typo that causes NameError, would pass.

Testing chained exceptions

def test_chained_cause():
    with pytest.raises(TypeError, match="whole number") as exc:
        parse_qty("two")
    assert isinstance(exc.value.__cause__, ValueError)

When code uses raise ... from e, the original error is stored in __cause__. Testing it confirms that debugging context is preserved, which matters when logs are your only clue in production.

Many error cases with parametrize

@pytest.mark.parametrize("amount,msg", [(0, "positive"), (-1, "positive"), (500, "less than")])
def test_many(amount, msg):
    with pytest.raises(ValueError, match=msg):
        withdraw(100, amount)

Combining raises with parametrize gives one readable table of invalid inputs and expected messages, and each row is reported as its own test. Boundary values like 0 and -1 belong here.

Accepting one of several types

def test_tuple_of_types():
    with pytest.raises((TypeError, KeyError)):
        {}["missing"]

Pass a tuple when more than one type is acceptable, for example when a function may raise KeyError or TypeError depending on input. Use it sparingly; a precise type usually makes a better contract.

Testing warnings with pytest.warns

import warnings

def test_warns():
    with pytest.warns(DeprecationWarning, match="old"):
        warnings.warn("old api", DeprecationWarning)

Warnings are not exceptions, so pytest.raises does not catch them. pytest.warns works the same way, including match. For messages written with the logging module, use the caplog fixture instead.

Three mistakes our tests caught

We wrote a second test file containing common mistakes. The result: 3 failed, 2 passed.

1. Nothing was raised.

with pytest.raises(ValueError):
    withdraw(100, 50)        # valid withdrawal, no exception
# Failed: DID NOT RAISE ValueError

This is the main safety feature: if a validation check is deleted, the test fails.

2. Wrong message.

with pytest.raises(ValueError, match="insufficient"):
    withdraw(100, 0)
# AssertionError: Regex pattern did not match.
#   Expected regex: 'insufficient'
#   Actual message: 'amount must be positive'

The right exception type but the wrong reason. Without match, this test would have passed and hidden the bug.

3. Special characters in the message.

with pytest.raises(ValueError, match="balance 100 is less than 150 (USD)"):
    raise ValueError("balance 100 is less than 150 (USD)")
# AssertionError: Regex pattern did not match.
#  Did you mean to `re.escape()` the regex?

with pytest.raises(ValueError, match=re.escape("less than 150 (USD)")):   # passes
    raise ValueError("balance 100 is less than 150 (USD)")

The message and pattern look identical, but (USD) is a regex group that matches USD without brackets. pytest even suggests the fix: wrap literal text in re.escape().

One more: code after the raising line inside the block never runs. Our test with assert False after withdraw(100, 0) passed, because execution jumped straight out of the block. Put follow-up assertions after the with.

Tip: keep exactly one statement inside a pytest.raises block, the call you expect to fail. Setup goes before it; assertions go after it.

Alternatives: try/except and unittest

A manual try/except with assert False in the try works but is longer and easy to get wrong. In unittest-style tests, self.assertRaises and self.assertRaisesRegex do the same job; pytest runs those tests too. See our Python unittest guide. For faking the dependency that should fail, combine raises with monkeypatch to make a function raise on demand.

Tips for reliable exception tests

  • Always add match for built-in exception types.
  • Use custom exception classes in your code; they make tests precise without long messages.
  • Use re.escape for literal messages.
  • Test boundaries: 0, negative numbers, empty strings, None.
  • Assert attributes and causes through exc.value.

Exception testing checklist

Use this list when reviewing a test file that covers error paths:

  • Every public function has at least one test for invalid input, not only the happy path.
  • Each pytest.raises names the most specific exception type available.
  • Built-in exception types are paired with a match pattern that identifies the real reason.
  • Literal messages containing brackets, dots or question marks use re.escape.
  • Only the failing call sits inside the with block; assertions on exc.value come after it.
  • Boundary values are covered: zero, negative numbers, empty strings, missing keys and None.
  • Chained causes are checked where debugging context matters.
  • Warnings are tested with pytest.warns and logs with caplog, not with raises.

A suite that ticks these boxes fails for the right reasons and tells you exactly which validation broke.

Final thoughts

pytest raises turns “this should fail” into an executable promise. Use the context manager with the most specific exception type, add a match regex for the message, inspect exc.value for details, and keep only the failing call inside the block. Our deliberate mistakes showed how each rule protects you: a missing exception, a wrong message and an unescaped bracket were all caught. Pair it with fixtures to set up the state that triggers each error.

Frequently asked questions

How do I test that a function raises an exception in pytest?

Wrap the call in with pytest.raises(ExpectedError): and call the function inside the block. The test passes only if that exception type, or a subclass, is raised.

How do I check the exception message in pytest?

Pass match with a regular expression, for example the pattern must be positive. pytest searches the exception message for the pattern and fails if it is not found.

Why does my match fail even though the message looks the same?

match is a regular expression, so characters like brackets and dots have special meaning. Wrap literal text in re.escape to match it exactly.

How do I access the exception object in pytest?

Use with pytest.raises(MyError) as exc: and then read exc.value after the block. exc.type gives the class and exc.value gives the instance with its attributes.

Does pytest.raises catch subclasses?

Yes. Like an except clause it matches the given type and any subclass. Check exc.type after the block if the exact class matters.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Random Forest in Python: Bagging, Feature Sampling and OOB From Scratch

Random forest in Python from scratch: bootstrap sampling, feature sampling, number of trees, out-of-bag evaluation and impurity vs permutation importance.

Read article →
Software Development

MIME Types Explained: Content-Type, nosniff and a Common Types List

MIME types explained and tested in a browser: Content-Type, nosniff, scripts and stylesheets with wrong types, a common MIME types…

Read article →
DevOps

Git Clean Explained: Remove Untracked Files Without Regret

Git clean explained with dry runs: -n, -f, -d, -x, -X, exclusions, paths, nested repositories and interactive mode, plus a…

Read article →
Test Automation

Pytest approx: Comparing Floats With rel, abs and Collections

Pytest approx explained: default tolerances, the near-zero trap, rel and abs, lists and dicts, NaN, NumPy, and how it differs…

Read article →
Software Testing

Accessibility Testing: WCAG Checklist, Automated Tools and Manual Checks

Accessibility testing explained: WCAG basics, an axe-core scan of a broken and a fixed page, what automation missed, contrast checks…

Read article →
Databases & SQL

SQL UNPIVOT: Turn Columns Into Rows, 4 Ways Tested

SQL UNPIVOT explained: turn columns into rows with UNION ALL, CROSS JOIN with CASE, JSON functions or native UNPIVOT, with…

Read article →
Software Development

Intl NumberFormat in JavaScript: Currency, Compact, Percent and Units

Intl.NumberFormat in JavaScript: locales, currency, compact notation, percent, units, rounding, formatToParts, the non-breaking space trap and formatter reuse.

Read article →
Software Development

Python Abstract Class: ABC, abstractmethod and When to Use Them

Python abstract class explained: ABC and abstractmethod, abstract properties, shared logic with super, register, collections.abc and ABC vs Protocol, tested.

Read article →
Software Development

Python Subprocess Explained: run, Capture Output, Timeouts and Safety

Python subprocess explained with tested examples: run, capture_output, check, timeouts, input, environment, shell injection, encoding on Windows and Popen streaming.

Read article →
Databases & SQL

SQL EXPLAIN Plan: How to Read Query Plans and Fix Slow Queries

SQL EXPLAIN plan explained: read scans, index searches, covering indexes and temporary sorts, with before and after timings for five…

Read article →
Artificial Intelligence

Decision Tree in Python: Gini, Entropy and Overfitting From Scratch

Decision tree in Python from scratch: Gini impurity, entropy, information gain, best splits, readable rules, and how depth and leaf…

Read article →
Software Development

URL Query Parameters: Encoding, URLSearchParams and Common Traps

URL query parameters explained: reading and building them with URLSearchParams and urllib, percent encoding, plus signs, repeated keys and nine…

Read article →
DevOps

Git Blame Explained: Find Who Changed a Line, and Why

Git blame explained with a real repository: ignore whitespace, line ranges and functions, ignore-revs files for formatting commits, moved code…

Read article →
Test Automation

Pytest Benchmark: Measure Speed and Catch Performance Regressions

Pytest benchmark tutorial: the benchmark fixture, reading results, parametrized and pedantic benchmarks, saving baselines and failing the build on regressions.

Read article →
Software Testing

Defect Density: Formula, Worked Examples and How to Use It

Defect density explained: the formula, a five-module worked example, per KLOC vs per function point, severity weighting, defect removal efficiency…

Read article →
Databases & SQL

Case Insensitive Search in SQL: LOWER, LIKE, COLLATE and Indexes

Case insensitive search in SQL: LOWER, LIKE, COLLATE NOCASE and expression indexes compared with query plans, plus accented letters and…

Read article →
Databases & SQL

ON DELETE CASCADE in SQL: CASCADE vs SET NULL vs RESTRICT

ON DELETE CASCADE in SQL tested: CASCADE vs SET NULL vs RESTRICT, multi-level cascades, the SQLite foreign key pragma, row…

Read article →
Software Development

JavaScript BigInt Explained: Big Numbers, Division and JSON

JavaScript BigInt explained: the 2^53 limit, creating and converting BigInt, division, mixing types, JSON stringify and parse without losing digits,…

Read article →
Artificial Intelligence

Logistic Regression in Python: Sigmoid, Log Loss and Gradient Descent From Scratch

Logistic regression in Python from scratch: sigmoid, log loss, gradient descent, odds ratios, thresholds, sigmoid overflow and separable data, tested…

Read article →
DevOps

Git Worktree Explained: Work on Two Branches at Once

Git worktree explained: add, list, remove, prune, lock and detached worktrees, a hotfix workflow, and the errors you will hit,…

Read article →
Test Automation

Pytest ini Explained: addopts, markers, testpaths and Precedence

Pytest ini explained: testpaths, addopts, strict markers, xfail_strict, filterwarnings, minversion, config file precedence and command-line overrides, tested.

Read article →
Software Testing

Test Estimation Techniques: WBS, Three Point PERT and Monte Carlo

Test estimation techniques worked through: WBS, three point PERT, total uncertainty, a Monte Carlo check, percentage rules and Wideband Delphi.

Read article →
Databases & SQL

Gaps and Islands in SQL: Find Streaks and Missing Ranges

Gaps and islands in SQL: find login streaks and missing ranges with ROW_NUMBER, DENSE_RANK, LAG and LEAD, plus the duplicate…

Read article →
Databases & SQL

INSERT INTO SELECT in SQL: Copy Rows Between Tables Safely

INSERT INTO SELECT in SQL: copy rows between tables with chosen columns, joins and summaries, avoid duplicates on reruns, upsert,…

Read article →
Artificial Intelligence

Linear Regression in Python: Least Squares From Scratch, With R Squared

Linear regression in Python from scratch: closed form, NumPy least squares and gradient descent, R squared, RMSE, outliers and curved…

Read article →
DevOps

Git Remote Explained: Add, Set-URL, Rename, Remove and Push URLs

Git remote explained: add, set-url, separate push URLs, rename, remove and prune, plus how to avoid leaking tokens in remote…

Read article →
Test Automation

Pytest Mock: mocker.patch, spy, side_effect and autospec Explained

Pytest mock explained: mocker.patch, return_value, side_effect, spy, autospec and PropertyMock, with tested examples for APIs, clocks and retries.

Read article →
Software Testing

System Testing Explained: Types, Process and a Real End-to-End Example

System testing explained: types, entry and exit criteria, the process, and a real end-to-end test suite run against a small…

Read article →
Artificial Intelligence

Naive Bayes Classifier Explained: Build a Spam Filter in Python

Naive Bayes classifier explained by building a spam filter in Python: Bayes rule, the naive assumption, Laplace smoothing, log probabilities…

Read article →
DevOps

Git Branch Explained: Create, Switch, Rename, Delete and Recover

Git branch explained with tested commands: list, create, switch, rename, delete, merged checks, recovering deleted branches, remote tracking and naming.

Read article →
Test Automation

Pytest raises: Testing Exceptions, match and excinfo

Pytest raises explained with tested examples: match regexes, excinfo, custom and chained exceptions, parametrized error cases, pytest.warns and common mistakes.

Read article →
Software Testing

Non Functional Testing: Types, Metrics and a Real Load Test

Non functional testing explained: 10 key types, measurable requirements, latency percentiles and what a small real load test revealed about…

Read article →
Artificial Intelligence

K Means Clustering Explained: How It Works, With Python Code

K means clustering explained: the algorithm, a from-scratch NumPy version, choosing k with the elbow and silhouette methods, k-means++, scaling…

Read article →
DevOps

Git Log Explained: 15 Useful Commands and Pretty Formats

Git log explained with 15 tested commands: oneline, graph, filters by author, date, message and code, file history, stats, pretty…

Read article →
Test Automation

Pytest conftest.py Explained: Shared Fixtures, Hooks and Overrides

Pytest conftest.py explained with a tested suite: shared fixtures, scope and teardown, folder overrides, autouse, custom options, markers and useful…

Read article →
Software Testing

Usability Testing: Methods, Metrics, SUS Score and Checklist

Usability testing explained: methods, planning, writing tasks, running sessions, metrics, SUS scoring, how many users you need and a practical…

Read article →