Christof Vermeersch Christof Vermeersch - 1 year ago 85
Python Question

Error while testing the raise of self-defined exceptions (using assertRaises())

I am creating tests for a python project. The normal tests work just fine, however I want to test if in a certain condition my function raises a self-defined exception. Therefor I want to use assertRaises(Exception, Function). Any ideas?

The function that raises the exception is:

def connect(comp1, comp2):
if comp1 == comp2:
raise e.InvalidConnectionError(comp1, comp2)

The exception is:

class InvalidConnectionError(Exception):
def __int__(self, connection1, connection2):
self._connection1 = connection1
self._connection2 = connection2

def __str__(self):
string = '...'
return string

The test method is the following:

class TestConnections(u.TestCase):
def test_connect_error(self):
comp = c.PowerConsumer('Bus', True, 1000)
self.assertRaises(e.InvalidConnectionError, c.connect(comp, comp))

However I get the following error:

Traceback (most recent call last):
File "C:\Users\t5ycxK\PycharmProjects\ElectricPowerDesign\", line 190, in test_connect_error
self.assertRaises(e.InvalidConnectionError, c.connect(comp, comp))
File "C:\Users\t5ycxK\PycharmProjects\ElectricPowerDesign\", line 428, in connect
raise e.InvalidConnectionError(comp1, comp2)
InvalidConnectionError: <unprintable InvalidConnectionError object>

Answer Source

assertRaises expects to actually perform the call. Yet, you already perform it by yourself, thereby throwing the error before assertRaises actually executes.

self.assertRaises(e.InvalidConnectionError, c.connect(comp, comp))
# run this ^ with first static argument ^ and second argument ^ from `c.connect(comp, comp)`

Use either of those instead:

self.assertRaises(e.InvalidConnectionError, c.connect, comp, comp)

with self.assertRaises(e.InvalidConnectionError):
    c.connect(comp, comp)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download