【问题标题】:What exception does the unittest framework raise in Python?Python 中的 unittest 框架会引发什么异常?
【发布时间】:2014-04-09 20:43:59
【问题描述】:

我有一个 python 脚本 (main.py),它调用另一个 python 脚本 (tester.py) 中的一个方法,该脚本使用 unittest 框架执行一堆测试并返回。 main.py 在 try 中寻找什么异常,除了块?

我尝试了以下方法,但从未触发异常。

try:
  tester.run()
except Exception, ex:
  print ex

根据文档,它会引发 AssertionError。但是,我尝试过 AssertionError、Exception,但都不起作用。

任何想法。

【问题讨论】:

  • 它不会引发异常......你在哪里看到它呢?它只是返回一个东西,告诉你什么通过了,什么失败了......
  • docs.python.org/2/library/unittest.html 为了使迁移现有测试套件更容易,unittest 支持测试引发 AssertionError 以指示测试失败。但是,建议您改用显式 TestCase.fail*() 和 TestCase.assert*() 方法,因为未来版本的 unittest 可能会以不同的方式处理 AssertionError。
  • 异常 AssertionError 在断言语句失败时引发。
  • unittest 源代码中 case.py 的第 166 行给出以下内容:faiureException = AssertionError
  • 那是一个测试用例..你在谈论一个测试运行器......它只是返回信息(它缓存异常并将数据记录为失败)一个测试运行器运行一套测试......在第一个错误上崩溃不会有多大好处

标签: python unit-testing exception assertions python-unittest


【解决方案1】:

取决于引发的异常。

方法引发异常:

def some(self):
    try:
        msg = "My Exception"
        raise HTTPNotFound(msg)
    except Exception as e:
         raise e

方法捕获异常

try:
    some()
except HTTPNotFound as e:
    print "Not found exception"
except Exception as e:
    print "Generic Exception"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多