What is stopping you importing the specific exception and using it in your with pytest.raises statement? Why is this not working? It would be more helpful if you could provide more detail about what problem you are facing.
# your code
class CustomError(Exception):
pass
def foo():
raise ValueError('everything is broken')
def bar():
raise CustomError('still broken')
#############
# your test
import pytest
# import your module, or functions from it, incl. exception class
def test_fooErrorHandling():
with pytest.raises(ValueError) as excinfo:
foo()
assert excinfo.value.message == 'everything is broken'
def test_barSimpleErrorHandling():
# don't care about the specific message
with pytest.raises(CustomError):
bar()
def test_barSpecificErrorHandling():
# check the specific error message
with pytest.raises(MyErr) as excinfo:
bar()
assert excinfo.value.message == 'oh no!'
def test_barWithoutImportingExceptionClass():
# if for some reason you can't import the specific exception class,
# catch it as generic and verify it's in the str(excinfo)
with pytest.raises(Exception) as excinfo:
bar()
assert 'MyErr:' in str(excinfo)
Answer from pfctdayelise on Stack Overflowpytest
docs.pytest.org › en › stable › how-to › assert.html
How to write and report assertions in tests - pytest documentation
def test_exception_in_group(): ... TypeError("bar")]) It accepts a match parameter, that checks against the group message, and a check parameter that takes an arbitrary callable which it passes the group to, and only succeeds if the callable returns True....
pytest
docs.pytest.org › en › 7.1.x › how-to › assert.html
How to write and report assertions in tests — pytest documentation
then no assertion introspection takes places at all and the message will be simply shown in the traceback. See Assertion introspection details for more information on assertion introspection. In order to write assertions about raised exceptions, you can use pytest.raises() as a context manager like this:
Jaketrent
jaketrent.com › post › verify-error-message-pytest
Assert Exception Message in pytest - Jake Trent
May 28, 2022 - We can write a test that expects the exception to be raised. 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'
Educative
educative.io › answers › how-to-check-if-an-exception-gets-raised-in-pytest
How to check if an exception gets raised in pytest
To do this, we use the pytest.raises() method. We use the match parameter to specify the expected message or the string representation of the exception.
Pybites
pybit.es › articles › guest-pytest-raises
Assertions About Exceptions With pytest.raises() – Pybites
May 18, 2020 - What I didn't think about until recently is how the open()-style context manager and the pytest.raises() style are mirror-world opposites: How does this work under the covers? As the Python documentation notes, entering a with block invokes a context manager's __enter__ method and leaving it invokes __exit__. Check out what happens when the context manager gets created, and what happens inside __enter__: def __init__( self, expected_exception: Union["Type[_E]", Tuple["Type[_E]", ...]], message: str, match_expr: Optional[Union[str, "Pattern"]] = None, ) -> None: ...
PyPI
pypi.org › project › pytest-raises
pytest-raises · PyPI
The implementation details of this limitation are further documented in the _pytest_raises_validation function. Both markers accept the following optional parameters: exception=<Some Exception Class>: the exact exception class that is expected to be raised. message='some string': a verbatim message that is expected to be in the raised exception message. Note that when message is supplied, the check performed is essentially message in exception_message.
» pip install pytest-raises
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
GitHub
github.com › pytest-dev › pytest › issues › 258
pytest.raises makes it impossible to check error messages and it should NOT accept parent classes by default · Issue #258 · pytest-dev/pytest
January 26, 2013 - Find attached a code for simple 'raises' -context manager and three simple tests for both. See the failures in the test run at the end. #!python #!/usr/bin/env python # encoding: utf-8 import pytest from contextlib import contextmanager class StrictTypeError(TypeError): """ Strict type error. """ def __init__(self, message): self.message = message def __str__(self): return str(self.message) def __repr__(self): return "{0}({1})".format(self.__class__.__name__, repr(self.message)) @contextmanager def raises(ExpectedException, message=''): try: yield raise AssertionError("Did not raise expected e
Author pytestbot
GitHub
gist.github.com › thoroc › ff61bfa8c67fbce6619f7b7458978c0b
pytest raises example · GitHub
============================================================================== test session starts =============================================================================== platform darwin -- Python 3.7.10, pytest-6.1.1, py-1.11.0, pluggy-0.13.1 -- /python/.venv/bin/python3 cachedir: .pytest_cache rootdir: /python, configfile: pytest.ini plugins: Faker-13.3.3, anyio-3.5.0, mock-3.3.1, cov-2.10.1, icdiff-0.5 collected 5 items test.py::test__get_status_ok[SUCCESS-True] PASSED [ 20%] test.py::test__get_status_ok[FAILURE-False] PASSED [ 40%] test.py::test__get_status_ok[PENDING-False] PASSED [ 60%] test.py::test__get_status_invalid_payload PASSED [ 80%] test.py::test__get_status_exception PASSED [100%] =============================================================================== 5 passed in 0.12s ================================================================================
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 - Or fail if it doesn’t raise an exception. ... To run the tests, simply run pytest in your terminal or you can provide the path to the file as an argument. Use -v for verbose logging. If you like, you can use the following simple block to assert the exception ... In these examples, we have captured the output in the excinfo object which allows us to assert the actual exception message too. So the following block of code, not only checks that a FileNotFoundError is raised but also asserts our expected message — File non_existent_file.txt not found, which is equally important.
DEV Community
dev.to › ajkerrigan › assertions-about-exceptions-with-pytest-raises-2hpn
Assertions about Exceptions with pytest.raises() - DEV Community
June 24, 2020 - When using pytest.raises as a context manager, it’s worthwhile to note that normal context manager rules apply and that the exception raised must be the final line in the scope of the context manager. Lines of code after that, within the scope of the context manager will not be executed.
Perforce Support
portal.perforce.com › s › article › Work-with-exceptions-using-PyTest
Work with exceptions using PyTest - Perforce Support
April 24, 2024 - Loading · ×Sorry to interrupt · Refresh
Continuously Merging
articles.mergify.com › pytest-assert-raises
Master pytest assert raises for Effective Exception Testing
May 22, 2025 - One effective approach is to test only the key parts of the error message. Instead of checking the entire string, verify the presence of a specific keyword or phrase. This approach offers flexibility while ensuring the correct error type is raised. Accurate scoping of pytest.raises blocks is crucial for scalable exception testing.
pytest
docs.pytest.org › en › 4.6.x › assert.html
The writing and reporting of assertions in tests — pytest documentation
Using pytest.raises is likely to be better for cases where you are testing exceptions your own code is deliberately raising, whereas using @pytest.mark.xfail with a check function is probably better for something like documenting unfixed bugs (where the test describes what “should” happen) or bugs in dependencies.
Top answer 1 of 14
1055
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'
GitHub
github.com › pytest-dev › pytest › blob › main › testing › python › raises.py
pytest/testing/python/raises.py at main · pytest-dev/pytest
pytest.raises(ValueError, tfunc, ... against an empty string will *always* pass. If you want to check for an empty message you " "need to pass '^$'. If you don't want to match you should pass `None` or ...
Author pytest-dev