pytest.raises(Exception) is what you need.

Code

import pytest

def test_passes():
    with pytest.raises(Exception) as e_info:
        x = 1 / 0

def test_passes_without_info():
    with pytest.raises(Exception):
        x = 1 / 0

def test_fails():
    with pytest.raises(Exception) as e_info:
        x = 1 / 1

def test_fails_without_info():
    with pytest.raises(Exception):
        x = 1 / 1

# Don't do this. Assertions are caught as exceptions.
def test_passes_but_should_not():
    try:
        x = 1 / 1
        assert False
    except Exception:
        assert True

# Even if the appropriate exception is caught, it is bad style,
# because the test result is less informative
# than it would be with pytest.raises(e)
# (it just says pass or fail.)

def test_passes_but_bad_style():
    try:
        x = 1 / 0
        assert False
    except ZeroDivisionError:
        assert True

def test_fails_but_bad_style():
    try:
        x = 1 / 1
        assert False
    except ZeroDivisionError:
        assert True

Output

============================================================================================= test session starts ==============================================================================================
platform linux2 -- Python 2.7.6 -- py-1.4.26 -- pytest-2.6.4
collected 7 items 

test.py ..FF..F

=================================================================================================== FAILURES ===================================================================================================
__________________________________________________________________________________________________ test_fails __________________________________________________________________________________________________

    def test_fails():
        with pytest.raises(Exception) as e_info:
>           x = 1 / 1
E           Failed: DID NOT RAISE

test.py:13: Failed
___________________________________________________________________________________________ test_fails_without_info ____________________________________________________________________________________________

    def test_fails_without_info():
        with pytest.raises(Exception):
>           x = 1 / 1
E           Failed: DID NOT RAISE

test.py:17: Failed
___________________________________________________________________________________________ test_fails_but_bad_style ___________________________________________________________________________________________

    def test_fails_but_bad_style():
        try:
            x = 1 / 1
>           assert False
E           assert False

test.py:43: AssertionError
====================================================================================== 3 failed, 4 passed in 0.02 seconds ======================================================================================

Note that e_info saves the exception object so you can extract details from it. For example, if you want to check the exception call stack or another nested exception inside.

Answer from Murilo Giacometti on Stack Overflow
Top answer
1 of 14
1056

pytest.raises(Exception) is what you need.

Code

import pytest

def test_passes():
    with pytest.raises(Exception) as e_info:
        x = 1 / 0

def test_passes_without_info():
    with pytest.raises(Exception):
        x = 1 / 0

def test_fails():
    with pytest.raises(Exception) as e_info:
        x = 1 / 1

def test_fails_without_info():
    with pytest.raises(Exception):
        x = 1 / 1

# Don't do this. Assertions are caught as exceptions.
def test_passes_but_should_not():
    try:
        x = 1 / 1
        assert False
    except Exception:
        assert True

# Even if the appropriate exception is caught, it is bad style,
# because the test result is less informative
# than it would be with pytest.raises(e)
# (it just says pass or fail.)

def test_passes_but_bad_style():
    try:
        x = 1 / 0
        assert False
    except ZeroDivisionError:
        assert True

def test_fails_but_bad_style():
    try:
        x = 1 / 1
        assert False
    except ZeroDivisionError:
        assert True

Output

============================================================================================= test session starts ==============================================================================================
platform linux2 -- Python 2.7.6 -- py-1.4.26 -- pytest-2.6.4
collected 7 items 

test.py ..FF..F

=================================================================================================== FAILURES ===================================================================================================
__________________________________________________________________________________________________ test_fails __________________________________________________________________________________________________

    def test_fails():
        with pytest.raises(Exception) as e_info:
>           x = 1 / 1
E           Failed: DID NOT RAISE

test.py:13: Failed
___________________________________________________________________________________________ test_fails_without_info ____________________________________________________________________________________________

    def test_fails_without_info():
        with pytest.raises(Exception):
>           x = 1 / 1
E           Failed: DID NOT RAISE

test.py:17: Failed
___________________________________________________________________________________________ test_fails_but_bad_style ___________________________________________________________________________________________

    def test_fails_but_bad_style():
        try:
            x = 1 / 1
>           assert False
E           assert False

test.py:43: AssertionError
====================================================================================== 3 failed, 4 passed in 0.02 seconds ======================================================================================

Note that e_info saves the exception object so you can extract details from it. For example, if you want to check the exception call stack or another nested exception inside.

2 of 14
377

Do you mean something like this:

def test_raises():
    with pytest.raises(Exception) as exc_info:   
        raise Exception('some info')
    # these asserts are identical; you can use either one   
    assert exc_info.value.args[0] == 'some info'
    assert str(exc_info.value) == 'some info'
🌐
pytest
docs.pytest.org › en › stable › how-to › assert.html
How to write and report assertions in tests - pytest documentation
You can pass a match keyword parameter to the context-manager to test that a regular expression matches on the string representation of an exception (similar to the TestCase.assertRaisesRegex method from unittest): import pytest def myfunc(): raise ValueError("Exception 123 raised") def test_match(): with pytest.raises(ValueError, match=r".* 123 .*"): myfunc()
🌐
Better Stack
betterstack.com › community › questions › how-to-assert-if-an-exception-is-raised-with-pytest
How to Assert if an Exception Is Raised With Pytest? | Better Stack Community
May 15, 2024 - When this test is run, it confirms that the divide() function behaves as expected by successfully raising a ZeroDivisionError when dividing by zero, indicated by a passing test result: ... ... collected 1 item test.py::test_zero_division PASSED [100%] ============================== 1 passed in 0.00s =============================== ... This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. ... To debug a pytest test using pdb, you can manually insert a breakpoint by adding import pdb; pdb.set_trace() in your test: import pytest def divide(x, y): return x / y def testzerodivision(): ...
🌐
Miguendes
miguendes.me › how-to-check-if-an-exception-is-raised-or-not-with-pytest
How to Check if an Exception Is Raised (or Not) With pytest
October 31, 2020 - Learn how to use pytest.raises to assert when an exception is raised or to assert no exception is raised, check the error and the exception message.
🌐
Pybites
pybit.es › articles › guest-pytest-raises
Assertions About Exceptions With pytest.raises() – Pybites
May 18, 2020 - We can uses pytest.raises() to assert that a block of code raises a specific exception.
Find elsewhere
🌐
Pytest with Eric
pytest-with-eric.com › introduction › pytest-assert-exception
How To Test Python Exception Handling Using Pytest Assert (A Simple Guide) | Pytest with Eric
July 6, 2023 - In this article, we’ll look at how to test basic exceptions, and use Pytest’s excinfo properties to access exception messages. We’ll look at handling failing cases, no exception raised cases, custom exceptions, and even multiple assertions in the same test.
🌐
Educative
educative.io › answers › how-to-check-if-an-exception-gets-raised-in-pytest
How to check if an exception gets raised in pytest
The pytest framework’s raises() method asserts that a block of code or a function call raises the specified exception.
🌐
Astral
docs.astral.sh › ruff › rules › pytest-unittest-raises-assertion
pytest-unittest-raises-assertion (PT027) | Ruff
import unittest class TestFoo(unittest.TestCase): def test_foo(self): with self.assertRaises(ValueError): raise ValueError("foo") ... import unittest import pytest class TestFoo(unittest.TestCase): def test_foo(self): with pytest.raises(ValueError): raise ValueError("foo")
🌐
Continuously Merging
articles.mergify.com › pytest-assert-raises
Master pytest assert raises for Effective Exception Testing
May 22, 2025 - Using the pytest.raises context manager, pytest assert raises allows tests to explicitly define the anticipated exception. This method gained popularity around 2013-2014 alongside the rise of Pytest as a major testing tool.
🌐
Codefinity
codefinity.com › courses › v2 › 1cf91e45-bf65-468b-8c09-6bc41c46bbe3 › b6e40c5a-2790-4b75-89e6-bad02fbeb123 › 7f08dae5-a04c-46a7-abc0-9c8f3f0958f2
Learn Using the Assert Statement in Pytest: Validating Test Conditions | Mastering Pytest Framework
This assertion checks whether the multiply function returns 10 when multiplying 2 and 5. The custom message clarifies the expected outcome versus the actual result if the test fails.
🌐
GitHub
github.com › pytest-dev › pytest › issues › 10085
Add pytest.raises(..., contains='substring') · Issue #10085 · pytest-dev/pytest
June 27, 2022 - pytest.raises can assert the message content as regexp via the match parameter. However, most of the time, I really only need to check if a substring is present in the message. Regexp is quite a he...
Author   timhoffm
🌐
PyPI
pypi.org › project › pytest-raises
pytest-raises · PyPI
This is different from ... an error. It will allow tests which raise errors to pass. The main usage is to assert that an error of a specific type is raise....
      » pip install pytest-raises
    
Published   Apr 23, 2020
Version   0.11
🌐
DEV Community
dev.to › wangonya › asserting-exceptions-with-pytest-8hl
Asserting Exceptions with Pytest - DEV Community
January 29, 2019 - To test for raised exceptions, pytest offers a handy method: pytest.raises.
🌐
XnView
cryan.com › blog › 20250409.jsp
Using pytest.raises to Validate Exceptions Like a Pro | Pytest
Before pytest.raises, Python developers would clutter tests with try/except blocks and fail manually. Compare: ... def test_safe_divide_old(): try: safe_divide(10, 0) assert False, "Expected ZeroDivisionError" except ZeroDivisionError: pass
🌐
Jaketrent
jaketrent.com › post › verify-error-message-pytest
Assert Exception Message in pytest - Jake Trent
May 28, 2022 - import pytest import my_module def test_exception_raise(): with pytest.raises(Exception) as exc_info: my_module.my_fn() assert str(exc_info.value) == 'Kaboom'
🌐
pytest
docs.pytest.org › en › stable › reference › reference.html
API Reference - pytest documentation
In the context manager form you may use the keyword argument match to assert that the warning matches a text or regex. The context manager produces a list of warnings.WarningMessage objects, one for each warning raised.