如何从视图类测试Django重定向

时间:2015-01-16 13:58:14

标签: python django testing django-unittest

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

我如何测试以下视图?如果用户已登录,则会将其重定向到列表视图。

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'

我做错了什么?

1 个答案:

答案 0 :(得分:5)

好的,我已设法成功完成测试用例,并使用以下代码

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)