Reputation: 9329
I want to check for an exception in Python unittest, with the following requirements:
I've seen lots of solutions of the form:
try:
something()
except:
self.fail("It failed")
Unfortunately these solutions swallow the original exception. Any way to retain the original exception?
I ended up using a variant of Pierre GM's answer:
try:
something()
except:
self.fail("Failed with %s" % traceback.format_exc())
Upvotes: 2
Views: 4206
Reputation: 20339
As suggested, you could use the context of a generic exception:
except Exception, error:
self.fail("Failed with %s" % error)
You can also retrieve the information relative to the exception through sys.exc_info()
try:
1./0
except:
(etype, evalue, etrace) = sys.exc_info()
self.fail("Failed with %s" % evalue)
The tuple (etype, evalue, etrace)
is here (<type 'exceptions.ZeroDivisionError'>, ZeroDivisionError('float division',), <traceback object at 0x7f6f2c02fa70>)
Upvotes: 2