如何导入 Django DoesNotExist 异常?

我尝试创建一个 UnitTest 来验证对象是否已被删除。

from django.utils import unittest
def test_z_Kallie_can_delete_discussion_response(self):
...snip...
self._driver.get("http://localhost:8000/questions/3/want-a-discussion")
self.assertRaises(Answer.DoesNotExist, Answer.objects.get(body__exact = '<p>User can reply to discussion.</p>'))

我一直得到这个错误:

DoesNotExist: Answer matching query does not exist.
75333 次浏览

DoesNotExist始终是模型的一个不存在的属性。在这种情况下,它应该是 Answer.DoesNotExist

你也可以从 django.core.exceptions导入 ObjectDoesNotExist,如果你想要一个通用的,独立于模型的方法来捕捉异常:

from django.core.exceptions import ObjectDoesNotExist


try:
SomeModel.objects.get(pk=1)
except ObjectDoesNotExist:
print 'Does Not Exist!'

我就是这样做测试的。

from foo.models import Answer


def test_z_Kallie_can_delete_discussion_response(self):


...snip...


self._driver.get("http://localhost:8000/questions/3/want-a-discussion")
try:
answer = Answer.objects.get(body__exact = '<p>User can reply to discussion.</p>'))
self.fail("Should not have reached here! Expected no Answer object. Found %s" % answer
except Answer.DoesNotExist:
pass # all is as expected

您不需要导入它——正如您已经正确地编写的那样,DoesNotExist是模型本身的一个属性,在本例中是 Answer

您的问题在于,在将异常传递给 assertRaises之前,您正在调用 get方法——它会引发异常。您需要将参数与可调用参数分开,如 单元测试文档单元测试文档中所述:

self.assertRaises(Answer.DoesNotExist, Answer.objects.get, body__exact='<p>User can reply to discussion.</p>')

或者更好:

with self.assertRaises(Answer.DoesNotExist):
Answer.objects.get(body__exact='<p>User can reply to discussion.</p>')

需要注意的一点是,assertRaises 需求的第二个参数是可调用的,而不仅仅是属性。例如,我对这句话有困难:

self.assertRaises(AP.DoesNotExist, self.fma.ap)

但这种方法很有效:

self.assertRaises(AP.DoesNotExist, lambda: self.fma.ap)
self.assertFalse(Answer.objects.filter(body__exact='<p>User...discussion.</p>').exists())