如何导入Django DoesNotExist异常?
我正在尝试创建一个UnitTest来验证对象是否已被删除如何导入Django DoesNotExist异常?,django,unit-testing,exception,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, An
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.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
从foo.models导入答案
def test_z_Kallie_can_delete_discussion_response(自我)回复:
剪
self.\u驱动程序。获取(“http://localhost:8000/questions/3/want-a-讨论)
尝试:
answer=answer.objects.get(body_u-exact='用户可以回复讨论。'))
self.fail(“不应到达此处!应为无应答对象。找到%s”%Answer
除答案外。DoesNotExist:
通过#一切如期
您不需要导入它-正如您已经正确编写的那样,DoesNotExist
是模型本身的一个属性,在本例中为Answer
您的问题是,您正在调用引发异常的get
方法,然后将其传递给assertRaises
self.assertRaises(Answer.DoesNotExist,Answer.objects.get,body\uu-exact=”用户可以回复讨论。)
或者更好:
with self.assertRaises(Answer.DoesNotExist):
Answer.objects.get(body__exact='<p>User can reply to discussion.</p>')
使用self.assertRaises(Answer.DoesNotExist):
Answer.objects.get(body_u-exact='用户可以回复讨论。)
需要注意的一件事是,assertRaises
的第二个参数需要是可调用的,而不仅仅是属性。例如,我对以下语句有困难:
self.assertRaises(AP.DoesNotExist, self.fma.ap)
但这很管用:
self.assertRaises(AP.DoesNotExist, lambda: self.fma.ap)
self.assertFalse(Answer.objects.filter(body\uu-exact='User…discussion.).exists())
与我下面的答案无关,是get()调用删除了问题中的答案吗?如果是,那真的应该是DELETE,而不是get。好的答案,只有上面的第一个片段会被捕获为无效语法(至少是Python 2.7)。应该是self.assertRaises(Answer.DoesNotExist,Answer.objects.get,body_u-exact='用户可以回复讨论。)
-即使用get
的参数作为单独的kw参数添加,而不是在中()
.Augh,当然!我觉得自己像这里的Dorothy。我到处搜索,却发现它一直伴随着我!Python 3.6/Django 2.2只有with
解决方案对我有效。这并不能完全回答要求的问题。但它仍然是一个很好的解决方案,提供了一种不同的方法来获得所需的结果。
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())