python - 我们应该如何用 Nose 测试异常?

标签 python testing nose

我正在用 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/

相关文章:

python - 如何更改 Python AssertionError 中的消息?

python - Scrapy 不会将数据写入文件

python - 检查命名空间中是否存在变量

python - 如何将数据从Scikit学习Bunch对象转换为Pandas DataFrame?

java - 在命令行上选择测试类别

python - 由于 SSL,使用 easy)install 安装 pip 和其他库失败

python - OpenCV、Python、Blob 检测。如何避免反光表面

unit-testing - GoogleTest中有没有类似于Igloo的LastException的东西?

iOS 配置文件已过期

python Nose : setting description attribute on generated tests