即使引发异常,AssertRaises也会失败

时间:2011-08-07 12:14:01

标签: python django unit-testing

我遇到了以下相当奇怪的问题:

我正在开发一个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没有捕获它。

任何人都知道为什么会发生这种情况?

由于

1 个答案:

答案 0 :(得分:6)

如果您的测试和产品代码通过两个不同的路径导入您的异常类,可能会发生这种情况,因此asRarises没有意识到您获得的异常是您正在寻找的异常。

查看您的导入,确保它们在两个地方都相同。在PYTHONPATH中以两种不同的方式提供相同的目录可以实现这一点。这些条目中的符号链接也会使事情混淆。

相关问题