Testing for KeyError

OpenDataAlex picture OpenDataAlex · Jun 20, 2014 · Viewed 10.9k times · Source

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])

Answer

Martijn Pieters picture Martijn Pieters · Jun 20, 2014

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")