Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for KeyError

I'm trying to write a unit test that verifies a KeyError is created when a bad key is passed to a dictionary.

The code that raises the exception:

connections = SettingsManager().get_connections()
try:
    connection = connections[self.conn_name]
except Exception:
    self.log.error("Connection %s does not exist, exiting." % conn_name)
    self.log.error(sys.exc_info()[0])
    raise

I've looked and found KeyError tests using lambda, but I've not had much luck. Here is the test I have thus far, but it errors with the actual KeyError.

def test_bad_connection(self):
    #Testing to see if a non existant connection will fail gracefully.
    records = [1, 2]
    given_result = DataConnector("BadConnection").generate_data(self.table, records)
    expected_result = "BadConnection"

    self.assertRaises(KeyError, given_result[:1])
like image 439
OpenDataAlex Avatar asked Jun 20 '14 15:06

OpenDataAlex


1 Answers

assertRaises() will call the function for you, and assert that that call raises the exception:

records = [1, 2]
connector = DataConnector("BadConnection")

self.assertRaises(KeyError, connector.generate_data, self.table, records)

Alternatively, use assertRaises() as a context manager:

with self.assertRaises(KeyError) as raises:
    DataConnector("BadConnection").generate_data(self.table, records)

which has the added advantage that the context manager then lets you access the raised exception:

self.assertEqual(raises.exception.message, "BadConnection")
like image 193
Martijn Pieters Avatar answered Sep 23 '22 11:09

Martijn Pieters