【问题标题】:AssertRaises fails even though exception is raised即使引发异常,AssertRaises 也会失败
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

    • 是的,这就是问题所在 - 引发的异常来自:..models.Exception 而预期的只是:.models.Exception
    • 嗯...我遇到了AssertionError 的问题 - 我正在使用self.assertRaises(AssertionError, ...),但AssertionError 仍然失败。由于这是在核心 python 中,所以这不是答案。还有其他可能吗?
    • 没关系,这是一个单独的错误。教训:密切注意测试失败输出中的行号。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多