assertRaises in table-driven tests

This is what I want to do but it fails passing None to assertRaises:

tests = [
   (0, None),
   (1, None),
   (-1, TooFewException),
   (99, None),
   (100, TooManyException),
]
for n, exc in tests:
    with self.assertRaises(exc):
        results = my_code(n)
        assert len(results) == n

Here’s a version of assertRaises that will let you do that:

    def assert_raises(self, exception: Type[Exception]):
        if exception:
            return self.assertRaises(exception)
        return contextlib.nullcontext()

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.