As I haven't seen any detailed explanation on how to check if we got a specific exception among a list of accepted one using context manager, or other exception details I will add mine (checked on python 3.8).
If I just want to check that function is raising for instance TypeError
, I would write:
with self.assertRaises(TypeError):
function_raising_some_exception(parameters)
If I want to check that function is raising either TypeError
or IndexError
, I would write:
with self.assertRaises((TypeError,IndexError)):
function_raising_some_exception(parameters)
And if I want even more details about the Exception raised I could catch it in a context like this:
# Here I catch any exception
with self.assertRaises(Exception) as e:
function_raising_some_exception(parameters)
# Here I check actual exception type (but I could
# check anything else about that specific exception,
# like it's actual message or values stored in the exception)
self.assertTrue(type(e.exception) in [TypeError,MatrixIsSingular])