Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django的单元测试。如何从assertRaises()获取异常消息?_Django_Unit Testing - Fatal编程技术网

Django的单元测试。如何从assertRaises()获取异常消息?

Django的单元测试。如何从assertRaises()获取异常消息?,django,unit-testing,Django,Unit Testing,我使用assertRaises()来验证是否会引发异常,这没有问题 我的问题是,有没有办法从assertRaises()获取异常消息?我还想通过解析异常消息来断言不同类型的异常n。如果不同的异常消息构成不同的可测试条件,那么它们可能是两个不同的异常。但是,它们可以很容易地从相同的基本异常类继承,因此您的其他异常处理代码不一定需要更改。我刚刚想出了解决方案,只需创建一个包装类,并使用它来断言异常 @staticmethod def assertRaises(exception, apicall,

我使用assertRaises()来验证是否会引发异常,这没有问题


我的问题是,有没有办法从assertRaises()获取异常消息?我还想通过解析异常消息来断言不同类型的异常n。

如果不同的异常消息构成不同的可测试条件,那么它们可能是两个不同的异常。但是,它们可以很容易地从相同的基本异常类继承,因此您的其他异常处理代码不一定需要更改。

我刚刚想出了解决方案,只需创建一个包装类,并使用它来断言异常

@staticmethod
def assertRaises(exception, apicall, *args, **kwargs):
    try:
        apicall(*args, **kwargs)
    except exception as e:
        return e
    finally:
        pass;

我使用了以下装饰师,其灵感来源于:

所以我可以这样做:

class TestMyThing(TestCase):
    @raises(ValueError, "T should not exceed 100, but has value 120")
    def test(self):
        some_code_that_provoke_exception()
@decorator
来自软件包。如果出于某种原因不想引入依赖项,可以手工编写decorator

class TestMyThing(TestCase):
    @raises(ValueError, "T should not exceed 100, but has value 120")
    def test(self):
        some_code_that_provoke_exception()