Mario Ishac
Mario Ishac

Reputation: 5907

How to specify specific instance of exception when using `assertRaises`?

I have a custom exception:

class AError(Exception):
    def __init__(self, a):
        self.a = a

and a function that raises this exception:

def raise_a(self):
    raise AError(1)

Using unittest, how do I test that raise_a raises AError with an a == 1? Using:

self.assertRaises(AError, raise_a)

will pass if any instance of AError (such as AError(2)) is raised, but I want it to fail for a != 1.

Upvotes: 1

Views: 59

Answers (1)

user2357112
user2357112

Reputation: 281842

Using assertRaises as a context manager gives you access to the caught exception:

with self.assertRaises(AError) as cm:
    raise_a()

self.assertEqual(cm.exception.a, 1)

Upvotes: 2

Related Questions