Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Testing exceptions with assertRaises

Use `unittest.TestCase.assertRaises` in callable form or in a `with` block to check that an operation raises the expected exception.

Version: Python 3.12

Syntax

self.assertRaises(exception, callable, *args, **kwds)

with self.assertRaises(exception, msg=None) as cm:
    operation()
# After a matching exception, inspect cm.exception.

In Python 3.12, assertRaises is a method of unittest.TestCase. Pass an exception class, not an instance, or a tuple of classes if several types are acceptable. A subclass of an expected class also matches. A matching exception is caught and the assertion passes. If nothing is raised, the assertion fails. A nonmatching exception propagates and is normally reported as a test error.

In callable form, write self.assertRaises(ValueError, parse_port, "0"). Pass parse_port itself and supply its positional and keyword arguments separately. Don't pass the result of parse_port("0"): that call would happen before the assertion could catch the exception.

In context-manager form, write with self.assertRaises(ValueError) as cm: and put only the operation expected to raise inside the block. Another operation that raises the same type could make the assertion pass for the wrong reason. After the block, cm.exception holds the caught instance. In this form, optional msg= supplies an assertion failure message, not a pattern for the exception text. To match the text with a regular expression, use assertRaisesRegex.

setUp() prepares test data before each test method, not before each subTest() block. assertEqual checks successful results and can also compare the caught exception's text. subTest(invalid=invalid) labels each iteration with the value that will appear in the report if the subtest fails.

Examples

import io
import unittest


def parse_port(text):
    port = int(text)
    if not 1 <= port <= 65535:
        raise ValueError("port must be between 1 and 65535")
    return port


class PortTests(unittest.TestCase):
    def setUp(self):
        self.default_port = "80"
        self.highest_port = "65535"

    def test_context_form(self):
        self.assertEqual(parse_port(self.default_port), 80)
        self.assertEqual(parse_port(self.highest_port), 65535)

        with self.assertRaises(ValueError) as cm:
            parse_port("0")

        self.assertEqual(str(cm.exception), "port must be between 1 and 65535")

    def test_callable_form(self):
        for invalid, valid, expected in (("0", "1", 1), ("65536", self.highest_port, 65535)):
            with self.subTest(invalid=invalid):
                self.assertEqual(parse_port(valid), expected)
                self.assertRaises(ValueError, parse_port, invalid)


if __name__ == "__main__":
    log = io.StringIO()
    suite = unittest.defaultTestLoader.loadTestsFromTestCase(PortTests)
    result = unittest.TextTestRunner(stream=log).run(suite)
    if not result.wasSuccessful():
        raise SystemExit(log.getvalue())
    print(f"OK ({result.testsRun} tests)")

Result

OK (2 tests)

The example checks valid ports, catches the exception for `"0"`, and compares its text. It then checks that `"0"` and `"65536"` are rejected in labeled subtests. The custom summary counts the two test methods, not the subtest iterations.

Related lessons

  • Python · Lesson 37 · Advanced · Version: 5
  • Python · Lesson 34 · Intermediate · Version: 3

Sources