Python 单元测试:将异常报告为失败 [英] Python unittest: Reporting Exception as Failure

查看:34
本文介绍了Python 单元测试:将异常报告为失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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

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:

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

您还可以通过sys.exc_info()<检索与异常相关的信息/code>

try:
    1./0
except:
    (etype, evalue, etrace) = sys.exc_info()
    self.fail("Failed with %s" % evalue)

元组 (etype, evalue, etrace) 在这里 (, ZeroDivisionError('float Division',), )

这篇关于Python 单元测试:将异常报告为失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆