我正在用 Nose 测试异常。这是一个例子:
def testDeleteUserUserNotFound(self):
"Test exception is raised when trying to delete non-existent users"
try:
self.client.deleteUser('10000001-0000-0000-1000-100000000000')
# make nose fail here
except UserNotFoundException:
assert True
如果引发异常则执行断言,但如果没有引发异常则不会执行。
我可以在上面的注释行中添加任何内容,以便在没有异常的情况下 Nose 会报告失败?
最佳答案
nose 提供了测试异常的工具(就像 unittest 一样)。 试试这个例子(并阅读 Nose Testing Tools 上的其他工具
from nose.tools import *
l = []
d = dict()
@raises(Exception)
def test_Exception1():
'''this test should pass'''
l.pop()
@raises(KeyError)
def test_Exception2():
'''this test should pass'''
d[1]
@raises(KeyError)
def test_Exception3():
'''this test should fail (IndexError raised but KeyError was expected)'''
l.pop()
def test_Exception4():
'''this test should fail with KeyError'''
d[1]
我认为这是您正在寻找的正确方法,因为它可以让您具体了解您期望或想要的异常。因此,您实际上会引发错误以查看它是否引发了正确的异常。然后让 nose 评估结果。 (在单元测试中加入尽可能少的逻辑!)
关于python - 我们应该如何用 Nose 测试异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7799593/