Use TestCase.assertRaises from the unittest module, for example:
import mymod
class MyTestCase(unittest.TestCase):
def test1(self):
self.assertRaises(SomeCoolException, mymod.myfunc)
Answer from Moe on Stack Overflow Top answer 1 of 16
1047
Use TestCase.assertRaises from the unittest module, for example:
import mymod
class MyTestCase(unittest.TestCase):
def test1(self):
self.assertRaises(SomeCoolException, mymod.myfunc)
2 of 16
728
Since Python 2.7 you can use context manager to get ahold of the actual Exception object thrown:
import unittest
def broken_function():
raise Exception('This is broken')
class MyTestCase(unittest.TestCase):
def test(self):
with self.assertRaises(Exception) as context:
broken_function()
self.assertTrue('This is broken' in context.exception)
if __name__ == '__main__':
unittest.main()
assertRaises
In Python 3.5, you have to wrap context.exception in str, otherwise you'll get a TypeError
self.assertTrue('This is broken' in str(context.exception))
pytest
docs.pytest.org › en › 7.1.x › how-to › assert.html
How to write and report assertions in tests — pytest documentation
and if you need to have access to the actual exception info you may use: def test_recursion_depth(): with pytest.raises(RuntimeError) as excinfo: def f(): f() f() assert "maximum recursion" in str(excinfo.value)
python assert exception
Assert statement in Python Exception Handling
05:44
Assertions and Try/Except (Video) – Real Python
Exceptions in Python: Test if Condition is True (ASSERT in ...
raising exceptions, assertions, creating custom exceptions ...
18:26
2 - Python pratique : assert, raise, try, except, else, finally...
Medium
medium.com › data-science › python-exception-testing-clean-and-effective-methods-86799da86b90
Python Exception Testing: Clean and Effective Methods | by Naomi Kriger | TDS Archive | Medium
July 24, 2023 - from contextlib import nullcontext as does_not_raise import pytest from operations import divide @pytest.mark.parametrize( "num_1, num_2, expected_result, exception, message", [ (30, 2.5, 12.0, does_not_raise(), None), (10.5, 0, None, pytest.raises(ZeroDivisionError), "float division by zero"), ("a", 10.5, None, pytest.raises(TypeError), "at least one of the inputs is not a number: a, 10.5") ], ids=["valid inputs", "divide by zero", "not a number input"] ) def test_division(num_1, num_2, expected_result, exception, message): with exception as e: result = divide(num_1, num_2) assert message is None or message in str(e) if expected_result is not None: assert result == expected_result
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
March 23, 2026 - But, with more exception handling comes challenges in testing. How do you handle unpredictability in code execution and flow? What about error propagation to the rest of the stack? Do you raise errors or handle them? And how do you ensure to display the correct and helpful type of error? This is very important, particularly when dealing with User facing tooling like APIs and response codes. Pytest assert exception handling can help with this.
Codecademy
codecademy.com › learn › learn-intermediate-python-3-exceptions-and-unit-testing › modules › unit-testing-course › cheatsheet
Learn Intermediate Python 3: Exceptions and Unit Testing: Unit Testing Cheatsheet | Codecademy
In Python’s unittest framework, the assertRaises TestCase method is used to test that a specific exception is raised.
pytest
docs.pytest.org › en › stable › how-to › assert.html
How to write and report assertions in tests - pytest documentation
In order to write assertions about raised exceptions, you can use pytest.raises() as a context manager like this:
Python.org
discuss.python.org › ideas
Asserting exact exception instances - Ideas - Discussions on Python.org
March 9, 2025 - There are two helpers in unittest.TestCase for asserting that exceptions are raised and properties of them: assertRaises checks that an exception is raised and asserts its type assertRaisesRegex checks that an exception is raised and matches its type and str I generally try to assert something about the message just to make sure the test doesn’t accidentally pass by raising the same exception in a different way, so I almost always use assertRaisesRegex.
Tutorialspoint
tutorialspoint.com › python › python_assertions.htm
Python - Assertions
Assertions can be caught and handled like any other exception using a try-except block.
pytest
docs.pytest.org › en › 6.2.x › assert.html
The writing and reporting of assertions in tests — pytest documentation
and if you need to have access to the actual exception info you may use: def test_recursion_depth(): with pytest.raises(RuntimeError) as excinfo: def f(): f() f() assert "maximum recursion" in str(excinfo.value)
W3Schools
w3schools.com › python › ref_exception_assertionerror.asp
Python AssertionError Exception
The AssertionError exception occurs when an assert statement fails.
TutorialsPoint
tutorialspoint.com › unittest_framework › unittest_framework_exceptions_test.htm
UnitTest Framework - Exceptions Test
To catch any of a group of exceptions, a tuple containing the exception classes may be passed as exception. In the example below, a test function is defined to check whether ZeroDivisionError is raised. import unittest def div(a,b): return a/b class raiseTest(unittest.TestCase): def testraise(self): self.assertRaises(ZeroDivisionError, div, 1,0) if __name__ == '__main__': unittest.main()
Gitlab
ongspxm.gitlab.io › blog › 2016 › 11 › assertraises-testing-for-errors-in-unittest
assertRaises - testing for errors in unittest
November 16, 2016 - import unittest def func(): raise Exception('lets see if this works') class ExampleTest(unittest.TestCase): def test_error(self): self.assertRaises(Exception, lambda:func()) if __name__=='__main__': unittest.main() But lambda is a whole new monster on its own. It doesn't seem to be the right tool to use just as a wrapper for the function. This is a much more appropriate and pythonic way of using assertRaises.