如何导入Django DoesNotExist异常?

时间:2012-06-19 21:08:48

标签: django unit-testing exception

我正在尝试创建一个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.

6 个答案:

答案 0 :(得分:163)

如果您想要一种与模型无关的通用方法来捕获异常,您还可以从ObjectDoesNotExist导入django.core.exceptions

from django.core.exceptions import ObjectDoesNotExist

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

答案 1 :(得分:116)

您无需导入它 - 正如您已经正确编写的那样,DoesNotExist是模型本身的属性,在本例中为Answer

您的问题是,在将get方法传递给assertRaises之前,您正在调用self.assertRaises(Answer.DoesNotExist, Answer.objects.get, body__exact='<p>User can reply to discussion.</p>') 方法 - 它会引发异常。您需要将参数与callable分开,如unittest documentation

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

或更好:

{{1}}

答案 2 :(得分:10)

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

答案 3 :(得分:3)

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

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

但这很好用:

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

答案 4 :(得分:1)

self.assertFalse(Answer.objects.filter(body__exact='<p>User...discussion.</p>').exists())

答案 5 :(得分:0)

这就是我做这样一个测试的方式。

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