gpt4 book ai didi

django-testing - HttpResponseRedirect' 对象没有属性 'client'

转载 作者:行者123 更新时间:2023-12-03 13:58:19 24 4
gpt4 key购买 nike

Django 1.9.6

我想编写一些单元测试来检查重定向。

你能帮我理解我在这里做错了什么吗?

先感谢您。

考试:

from django.test import TestCase
from django.core.urlresolvers import reverse
from django.http.request import HttpRequest
from django.contrib.auth.models import User

class GeneralTest(TestCase):

def test_anonymous_user_redirected_to_login_page(self):
user = User(username='anonymous', email='vvv@mail.ru', password='ttrrttrr')
user.is_active = False
request = HttpRequest()
request.user = user
hpv = HomePageView()
response = hpv.get(request)
self.assertRedirects(response, reverse("auth_login"))

结果:

错误:test_anonymous_user_redirected_to_login_page (general.tests.GeneralTest)

回溯(最近一次调用最后一次):
文件“/home/michael/workspace/photoarchive/photoarchive/general/tests.py”,第 44 行,在 test_anonymous_user_redirected_to_login_page
self.assertRedirects(响应,反向(“auth_login”))
文件“/home/michael/workspace/venvs/photoarchive/lib/python3.5/site-packages/django/test/testcases.py”,第326行,在assertRedirects
redirect_response = response.client.get(path, QueryDict(query),
AttributeError: 'HttpResponseRedirect' 对象没有属性 'client'

在 0.953 秒内运行 3 个测试

pdb 说什么:
-> self.assertRedirects(response, reverse("auth_login"))
(Pdb) response
<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/accounts/login/">

最佳答案

您需要向响应对象添加一个客户端。请参阅下面的更新代码。

from django.test import TestCase, Client
from django.core.urlresolvers import reverse
from django.http.request import HttpRequest
from django.contrib.auth.models import User

class GeneralTest(TestCase):

def test_anonymous_user_redirected_to_login_page(self):
user = User(username='anonymous', email='vvv@mail.ru', password='ttrrttrr')
user.is_active = False
request = HttpRequest()
request.user = user
hpv = HomePageView()
response = hpv.get(request)
response.client = Client()
self.assertRedirects(response, reverse("auth_login"))

关于django-testing - HttpResponseRedirect' 对象没有属性 'client',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37553590/

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