Python unittest:将异常报告为失败

时间:2012-09-20 10:10:48

标签: python unit-testing

我想检查Python unittest中的异常,具有以下要求:

  • 需要报告为失败,而不是错误
  • 不得吞下原始例外

我见过很多形式的解决方案:

try:
    something()
except:
    self.fail("It failed")

不幸的是,这些解决方案吞噬了原始异常。有什么方法可以保留原来的例外吗?

我最终使用了Pierre GM的答案:

try:
   something()
except:
    self.fail("Failed with %s" % traceback.format_exc())

1 个答案:

答案 0 :(得分:2)

根据建议,您可以使用通用异常的上下文:

except Exception, error:
    self.fail("Failed with %s" % error)

您还可以通过sys.exc_info()

检索与例外相关的信息
try:
    1./0
except:
    (etype, evalue, etrace) = sys.exc_info()
    self.fail("Failed with %s" % evalue)

元组(etype, evalue, etrace)在这里(<type 'exceptions.ZeroDivisionError'>, ZeroDivisionError('float division',), <traceback object at 0x7f6f2c02fa70>)

相关问题