检查 assertRaises 中的异常参数
Check exception parameters in assertRaises
我有以下代码(使用 Django):
def test_validation(self):
with assertRaises(ValidationError):
<do something>
with assertRaises(ValidationError):
<do something else>
但是,这两个 ValidationError
异常之间存在差异,因为我用不同的 code
值提出它们:
raise ValidationError("Some message", code='first_code')
和
raise ValidationError("Another message", code='second_code')
是否可以检查引发的异常的属性,例如在我的例子中 code
属性?添加code='first_code'
好像没有效果。
上下文管理器会将捕捉到的异常对象存储在它的异常属性中。如果打算对引发的异常执行额外检查,这可能很有用:
with self.assertRaises(SomeException) as cm:
do_something()
the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)
我有以下代码(使用 Django):
def test_validation(self):
with assertRaises(ValidationError):
<do something>
with assertRaises(ValidationError):
<do something else>
但是,这两个 ValidationError
异常之间存在差异,因为我用不同的 code
值提出它们:
raise ValidationError("Some message", code='first_code')
和
raise ValidationError("Another message", code='second_code')
是否可以检查引发的异常的属性,例如在我的例子中 code
属性?添加code='first_code'
好像没有效果。
上下文管理器会将捕捉到的异常对象存储在它的异常属性中。如果打算对引发的异常执行额外检查,这可能很有用:
with self.assertRaises(SomeException) as cm:
do_something()
the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)