gpt4 book ai didi

Django 测试DeleteView

转载 作者:行者123 更新时间:2023-12-02 05:10:56 24 4
gpt4 key购买 nike

因此,在DeleteView中,GET请求返回一个确认页面,并且除了csrf_token之外没有任何字段的简单POST请求实际上获取DeleteView来删除对象,用户将被重定向到 success_url

如何测试此功能?在我的 myclass_confirm_delete.html 文件中,我基本上有:

<form action="{% url 'remove_myclass' object.id %}" method="post">
{% csrf_token %}
<p>Are you sure you want to remove {{ object.name }}?</p>
<input type="submit" value="Yes" class="btn btn-primary" />
</form>

其中 {% url 'remove_myclass' object.id %} 是同一页面的 URL。它可以在我的浏览器中运行。当我单击"is"时,它会将我重定向到成功页面,并且 myclass 对象将从数据库中删除。

现在我正在尝试通过单元测试自动测试它。我基本上尝试过

response = self.client.get(reverse('remove_myclass', args=(myobject.id,)), follow=True)
self.assertContains(response, 'Are you sure you want to remove') # THIS PART WORKS
self.client.post(reverse('remove_myclass', args=(myobject.id,)), follow=True)
self.assertRedirects(response, reverse('myclass_removed'), status_code=302) # FAILS; status code is 200

如果我尝试打印响应,我会得到与使用 GET 请求时完全相同的响应。

似乎在单元测试时,无论我尝试在 POST 请求中发送哪种数据,它仍然会被视为 GET 请求...

我的基于类的 View :

class MyclassDelete(DeleteView):
model = myclass
success_url = '/myclass-removed/'

有什么想法吗?

最佳答案

是的,这是因为您忘记将 post 请求分配给 response,因此您检查了相同的响应两次。

response = self.client.get(reverse('remove_myclass', args=(myobject.id,)), follow=True)
self.assertContains(response, 'Are you sure you want to remove') # THIS PART WORKS

post_response = self.client.post(reverse('remove_myclass', args=(myobject.id,)), follow=True)
self.assertRedirects(post_response, reverse('myclass_removed'), status_code=302)

这应该可以解决问题。

另外,只是一个提示,在单元测试时尝试在每个单元测试中多次断言被认为是不好的做法。相反,尝试将其分解,以便一个测试测试 GET,另一个测试测试 POST

from django.test import TestCase

class TestDifferentRequestMethods(TestCase):

def test_my_get_request(self):
response = self.client.get(reverse('remove_myclass', args=(myobject.id,)), follow=True)
self.assertContains(response, 'Are you sure you want to remove') # THIS PART WORKS

def test_my_post_request(self):
post_response = self.client.post(reverse('remove_myclass', args=(myobject.id,)), follow=True)
self.assertRedirects(post_response, reverse('myclass_removed'), status_code=302)

这使得调试更加容易,并且有时可以在遇到此类麻烦时节省时间!

更新意识到我没有完成一个很好的类(class)来完成测试。

关于Django 测试DeleteView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16006401/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com