I want to check for an exception in Python unittest, with the following requirements:
- Needs to be reported as a failure, NOT an error
- Must not swallow the original exception
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())
As suggested, you could use the context of a generic exception:
You can also retrieve the information relative to the exception through
sys.exc_info()The tuple
(etype, evalue, etrace)is here(<type 'exceptions.ZeroDivisionError'>, ZeroDivisionError('float division',), <traceback object at 0x7f6f2c02fa70>)