gpt4 book ai didi

python - 如何从 View 类测试 Django 重定向

转载 作者:太空宇宙 更新时间:2023-11-03 14:20:56 27 4
gpt4 key购买 nike

我正在学习 Django atm,我一直在创建一个简单的测试用例。

如何测试以下 View ?如果用户已经登录,则将他重定向到 ListView 。

from django.shortcuts import render
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.forms import AuthenticationForm
from django.views.generic import TemplateView
from django.core.urlresolvers import reverse
from django.shortcuts import redirect

class LoginView(TemplateView):
"""
Base class for client area login.
"""
def get(self, request, *args, **kwargs):
"""
Display login form, only if user is not yet authenticated.
Otherwise redirect to tickets index.
:param request:
:param args:
:param kwargs:
:return:
"""
if request.user.is_authenticated():
return redirect(reverse('tickets:index'))

form = AuthenticationForm()

return render(request, 'login.html', {'form': form})

到目前为止,我创建的测试如下所示:

from django.test import TestCase, RequestFactory
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User, AnonymousUser
from app.account.views import LoginView


class TestLoginForm(TestCase):

def setUp(self):
"""
Set up environment
:return:
"""
self.user = User.objects.create_user(username="test", password="test123", email="test@gmail.com")
self.factory = RequestFactory()

def tearDown(self):
"""
Clean created user object
:return:
"""
self.user.delete()
self.factory = None

def test_login_form_redirect(self):
"""
Test login redirect
:return:
"""


request = self.factory.get(reverse('account:login'))
request.user = AnonymousUser()

view = LoginView()
response = view.get(request=request)
self.assertEqual(response.status_code, 200)

request.user = self.user
response = view.get(request=request)
self.assertRedirects(response, expected_url=reverse('tickets:index'), status_code=302, target_status_code=200)

第一个断言通过了,但第二个断言如果用户已经登录则应该重定向到这里抛出这个错误

AttributeError: 'HttpResponseRedirect' object has no attribute 'client'

我做错了什么?

最佳答案

好的,我已经成功地用下面的代码制作了测试用例

def test_login_form_redirect(self):
"""
Test login redirect
:return:
"""

self.client.logout()

response = self.client.get(reverse('account:login'))
self.assertEqual(response.status_code, 200)

self.assertTrue(self.client.login(username='test', password='test123'))
response = self.client.get(reverse('account:login'))
self.assertRedirects(response, expected_url=reverse('tickets:index'), status_code=302, target_status_code=200)

关于python - 如何从 View 类测试 Django 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27985598/

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