AssertRaises失败,尽管异常已被抛出

8 投票
1 回答
2640 浏览
提问于 2025-04-16 23:04

我遇到了一个比较奇怪的问题:

我正在开发一个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 个回答

6

这种情况可能发生在你的测试代码和产品代码通过两条不同的路径引入了同一个异常类,这样的话,asserRaises就无法识别你得到的异常是不是你想要的那个。

检查一下你的导入语句,确保在两个地方使用的是相同的方式。如果你的PYTHONPATH中有相同的目录以两种不同的方式出现,就可能导致这个问题。目录中的符号链接也可能让事情变得复杂。

撰写回答