【发布时间】:2011-08-07 12:14:01
【问题描述】:
我遇到了以下相当奇怪的问题:
我正在开发一个 django 应用程序,并且在我的模型类中我定义了一个在验证失败时应该引发的异常:
class MissingValueException(Exception):
"""Raise when a required attribute is missing."""
def __init__(self, message):
super(MissingValueException, self).__init__()
self.message = message
def __str__(self):
return repr(self.message)
此代码在验证方法中从发布类调用:
def validate_required_fields(self):
# Here is the validation code.
if all_fields_present:
return True
else:
raise MissingValueException(errors)
在我的单元测试中,我创建了一个应该引发异常的案例:
def test_raise_exception_incomplete_publication(self):
publication = Publication(publication_type="book")
self.assertRaises(MissingValueException, publication.validate_required_fields)
这会产生以下输出:
======================================================================
ERROR: test_raise_exception_incomplete_publication (core_knowledge_platform.core_web_service.tests.logic_tests.BusinessLogicTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/media/data/Dokumente/Code/master_project/core_knowledge_platform/../core_knowledge_platform/core_web_service/tests/logic_tests.py", line 45, in test_raise_exception_incomplete_publication
self.assertRaises(MissingValueException, method, )
File "/usr/lib/python2.7/unittest/case.py", line 465, in assertRaises
callableObj(*args, **kwargs)
File "/media/data/Dokumente/Code/master_project/core_knowledge_platform/../core_knowledge_platform/core_web_service/models.py", line 150, in validate_required_fields
raise MissingValueException(errors)
MissingValueException: 'Publication of type book is missing field publisherPublication of type book is missing field titlePublication of type book is missing field year'
所以看起来异常被引发了(就是这种情况——我什至在交互式 IPython 会话中检查了它),但似乎 assertRaises 没有捕捉到它。
有人知道为什么会发生这种情况吗?
谢谢
【问题讨论】:
标签: python django unit-testing