3
我正在學習Django atm,我堅持創建一個簡單的測試用例。如何測試Django從視圖類重定向
我如何測試以下視圖?如果用戶已經登錄,則將其重定向到列表視圖。
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="[email protected]")
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)
第一assertation過去了,但第二個地方,如果已經有登錄的用戶應被重定向拋出這個錯誤
AttributeError: 'HttpResponseRedirect' object has no attribute 'client'
我在做什麼錯?
你從單元測試切換到端到端測試。檢查此答案是否正確檢查單元測試中的重定向方式:http://stackoverflow.com/a/11683427/2638796 –