8
我遇到了以下比較奇怪的問題:AssertRaises失敗,即使引發異常
我開發一個Django應用程序,並在我的模型類我定義,當一個驗證失敗,應引發異常:
def validate_required_fields(self):
# Here is the validation code.
if all_fields_present:
return True
else:
raise MissingValueException(errors)
在我的單元測試我創造一個異常應提高的情況下:
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 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沒有抓住它。
任何人有任何想法,爲什麼這可能發生嗎?如果你的測試和產品代碼是通過兩個不同的路徑導入您的異常類
感謝
是的 - 凸起的例外是來自:。 .models.Exception 雖然預期只是: .models.Exception –
BergmannF
呃......我有一個'AssertionError'這個問題 - 我正在使用'self.assertRaises(AssertionError,...) ',它仍然有'AssertionError'失敗。由於這是核心python,這不可能是答案。任何其他可能性? – naught101
沒關係,它是一個獨立的錯誤。課程:非常注意測試失敗輸出中的行號。 – naught101