I want to write a test to establish that an Exception is not raised in a given circumstance.
It\'s straightforward to test if an Exception is raise
I've found it useful to monkey-patch unittest as follows:
def assertMayRaise(self, exception, expr):
if exception is None:
try:
expr()
except:
info = sys.exc_info()
self.fail('%s raised' % repr(info[0]))
else:
self.assertRaises(exception, expr)
unittest.TestCase.assertMayRaise = assertMayRaise
This clarifies intent when testing for the absence of an exception:
self.assertMayRaise(None, does_not_raise)
This also simplifies testing in a loop, which I often find myself doing:
# ValueError is raised only for op(x,x), op(y,y) and op(z,z).
for i,(a,b) in enumerate(itertools.product([x,y,z], [x,y,z])):
self.assertMayRaise(None if i%4 else ValueError, lambda: op(a, b))