2

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())

1 Answer 1

2

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>)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.