如何导入Django DidNotExist异常?


122

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

与下面的答案无关,是get()调用删除了有问题的答案吗?如果是这样,那确实应该是DELETE,而不是GET。
史蒂夫·贾林

Answers:


136

您无需导入它- DoesNotExist在这种情况下,因为您已经正确编写了它,所以它是模型本身的属性Answer

您的问题是您在将get方法传递给之前调用了引发异常的方法assertRaises。您需要将参数与可调用对象分开,如unittest文档中所述

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>')

1
好的答案是,只有上述片段中的第一个会被视为无效语法(至少在Python 2.7中是这样),self.assertRaises(Answer.DoesNotExist, Answer.objects.get, body__exact = '<p>User can reply to discussion.</p>')即- get的参数作为单独的kw args添加,而不是在内()
Martin B.

1
啊,当然!我在这里感觉像多萝西。我一直在寻找高低,直到发现它一直伴随着我!
尼克S

Python 3.6 / Django 2.2仅with适用于我的解决方案。
Theruss

182

如果希望使用通用的,与模型无关的方式来捕获异常,也可以ObjectDoesNotExist从导入django.core.exceptions

from django.core.exceptions import ObjectDoesNotExist

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

10

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


3

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

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

但这工作正常:

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

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

这不能完全按照要求回答问题。但这仍然是一个不错的解决方案,提供了一种不同的方法来获得所需的结果。
塞萨尔

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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.