Python测试框架提供以下断言方法来检查是否引发了异常.
assertRaises(exception, callable, *args, **kwds)
测试在使用任何位置或关键字参数调用函数时引发异常(第一个参数).如果引发了预期的异常,则测试通过,如果引发另一个异常则是错误,如果没有引发异常则失败.要捕获任何一组异常,可以将包含异常类的元组作为异常传递.
在下面的示例中,定义了一个测试函数来检查是否引发了ZeroDivisionError./p>
import unittestdef div(a,b): return a/bclass raiseTest(unittest.TestCase): def testraise(self): self.assertRaises(ZeroDivisionError, div, 1,0)if __name__ == '__main__': unittest.main()
testraise()函数使用assertRaises()函数来查看div()函数是否出现除零调用.上面的代码会引发异常.但是更改div()函数的参数如下 :
self.assertRaises(ZeroDivisionError, div, 1,1)
当使用这些更改运行代码时,测试失败,因为ZeroDivisionError没有发生.
================================================================FAIL: testraise (__main__.raiseTest)----------------------------------------------------------------------Traceback (most recent call last): File "raisetest.py", line 7, in testraise self.assertRaises(ZeroDivisionError, div, 1,1)AssertionError: ZeroDivisionError not raised----------------------------------------------------------------------Ran 1 test in 0.000sFAILED (failures = 1)
assertRaisesRegexp(exception, regexp, callable, *args, **kwds)
测试 regexp 匹配字符串表示引发异常的情况. regexp可以是正则表达式对象,也可以是包含适合re.search()使用的正则表达式的字符串.
以下示例显示了assertRaisesRegexp()的使用方式和减号;
import unittestimport reclass raiseTest(unittest.TestCase): def testraiseRegex(self): self.assertRaisesRegexp(TypeError, "invalid", reg,"Point","TutorialsPoint") if __name__ == '__main__': unittest.main()
这里,testraseRegex()测试不会作为第一个参数失败.在第二个参数字符串中找到"Point".
================================================================FAIL: testraiseRegex (__main__.raiseTest)----------------------------------------------------------------------Traceback (most recent call last): File "C:/Python27/raiseTest.py", line 11, in testraiseRegex self.assertRaisesRegexp(TypeError, "invalid", reg,"Point","TutorialsPoint")AssertionError: TypeError not raised----------------------------------------------------------------------
但是,更改如下所示 :
self.assertRaisesRegexp(TypeError, "invalid", reg,123,"TutorialsPoint")
将抛出TypeError异常.因此,将显示以下结果 :
================================================================FAIL: testraiseRegex (__main__.raiseTest)----------------------------------------------------------------------Traceback (most recent call last): File "raisetest.py", line 11, in testraiseRegex self.assertRaisesRegexp(TypeError, "invalid", reg,123,"TutorialsPoint")AssertionError: "invalid" does not match "first argument must be string or compiled pattern"----------------------------------------------------------------------