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.
pytest
docs.pytest.org › en › 7.1.x › how-to › assert.html
How to write and report assertions in tests — pytest documentation
import pytest def test_zero_division(): with pytest.raises(ZeroDivisionError): 1 / 0
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'
Videos
07:55
Pytest Tutorial: Pytest Raises Assertion - YouTube
05:57
How to Test Raising and Not Raising an Exception Using Only One ...
33. Pytest Assert Statement | Assert rewriting | Rajiv
05:52
How do I properly assert that an exception gets raised in pytest?
05:50
How to properly assert that an exception gets raised in pytest? ...
12:13
pytest: testing exceptions (beginner - intermediate) anthony explains ...
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(): ...
pytest
docs.pytest.org › en › 6.2.x › assert.html
The writing and reporting of assertions in tests — pytest documentation
June 7, 2022 - pytest.raises(ExpectedException, func, *args, **kwargs)
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")
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
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'
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
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.