Labs ICT
โญ Pro Login

assertRaises Context Manager

Testing that exceptions are raised correctly

assertRaises Context Manager

assertRaises verifies that a specific exception is raised during code execution. It can be used as a context manager for clean, readable exception testing.

Context Manager Usage

import unittest

class TestExceptions(unittest.TestCase):
    def test_division_by_zero(self):
        with self.assertRaises(ZeroDivisionError):
            1 / 0

    def test_index_error(self):
        my_list = [1, 2, 3]
        with self.assertRaises(IndexError):
            _ = my_list[10]

    def test_value_error(self):
        with self.assertRaises(ValueError):
            int("not_a_number")

Using as a Decorator

class TestDivide(unittest.TestCase):
    @unittest.skip("demonstrating skip")
    def test_divide_by_zero_decorator(self):
        pass

    # Using assertRaises as a decorator
    def test_raises_on_bad_input(self):
        with self.assertRaises(TypeError):
            result = divide("ten", 2)

Capturing the Exception

def test_exception_message(self):
    with self.assertRaises(ValueError) as ctx:
        raise ValueError("Invalid email format")

    self.assertEqual(str(ctx.exception), "Invalid email format")

def test_exception_type(self):
    with self.assertRaises(Exception) as ctx:
        raise ConnectionError("timeout")

    self.assertIsInstance(ctx.exception, ConnectionError)

assertRaisesRegex

def test_error_message_matches(self):
    with self.assertRaisesRegex(ValueError, r"invalid.*email"):
        validate_email("bad-email")

Key Takeaway

Use assertRaises as a context manager to verify exceptions. Capture the exception object with as to inspect its message or attributes.

๐Ÿงช Quick Quiz

assertRaises is used to verify that: