How to Test Assertions are Raised or Handled in Python

When unit testing Python, how can one assert that exceptions are raised or handled? Here’s how we do it:

First, here is the code we want to test:

def division_raises():
    print(10/0)

def division_doesnt_raise():
    try:
        print(10/0)
    except ZeroDivisionError:
        return None

And here is how we test the code above:

from unittest import TestCase

class TestException(TestCase):
    def test_exception_is_raised(self):
        with self.assertRaises(ZeroDivisionError) as e:
            division_raises()
        self.assertEqual(‘Foo Exception occurred’, e.exception.message)

    def test_exception_is_not_raised(self):
        with self.assertRaises(AssertionError):
            with self.assertRaises(ZeroDivisionError):
                division_doesnt_raise()