Testing for KeyError

I am trying to write a unit test that checks that a KeyError is KeyError when a bad key is passed to the dictionary.

The code that throws 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 looked and found KeyError tests using lambda, but I had no luck. Here is the test I have so far, but these are 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]) 
+7
python unit-testing keyerror
source share
2 answers

assertRaises() will call the function for you and assertRaises() that this call throws an exception:

 records = [1, 2] connector = DataConnector("BadConnection") self.assertRaises(KeyError, connector.generate_data, self.table, records) 

Alternatively, use assertRaises() as the context manager:

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

which has the added benefit that the context manager then allows you to access the raised exception:

 self.assertEqual(raises.exception.message, "BadConnection") 
+9
source share

self.assertRaise() only accepts the called, so for now

self.assertRaises(KeyError, given_result[:1])
will give you the actual KeyError when testing,

self.assertRaises(KeyError, lambda: given_result[:1])
should work.

Generally:
Doesn't work: self.assertRaises(KeyError, mydict[mykey]) #KeyError in tests
Does it work: self.assertRaises(KeyError, lambda: mydict[mykey])
Does it work: self.assertRaises(KeyError, mydict.__getitem__, mykey) #, but this requires an actual dict, not a function

+3
source share

All Articles