Reputation: 2874
I have a module InvalidObj
class InvalidObj(Exception):
def__init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Hello(object):
def __init__(self):
self.a = 10
self.b = 20
def aequalb(self):
if self.a != self.b:
raise InvalidObj("This is an error")
I am trying to do a unittest where a function throws the InvalidObj exception
class test_obj(unittest.TestCase):
def test_obj(self):
at = Hello()
self.assertRaises(InvalidObj("This is an error"), a.aequalb)
On running the above test_obj class, it gives me an error "issubclass() arg 2 must be a class or tuple". But if I change the line to,
self.assertRaises(InvalidObj, at.aequalb)
This runs fine. Isn't the error supposed to return the message passed to it when it is raised?
Upvotes: 2
Views: 10576
Reputation: 137350
No, it is not supposed to work the way you expected. First argument is a class (or a tuple), the second is callable, the rest are as described in the documentation.
Even though exception accepts arguments, unittest
does not give you deep comparisons between exceptions (otherwise, it would be pretty complex to say that two separate instances of the same class are equivalent).
To solve your issue, just test attribute separately:
with self.assertRaises(InvalidObj) as cm:
at.aequalb()
self.assertEqual("This is an error", cm.exception.value)
Note: Above I have used assertRaises()
method as context manager. It behaves like that, when only one argument is given. For more details please visit mentioned documentation.
Upvotes: 3