如何编写授权测试?

时间:2014-04-16 16:53:20

标签: python django

请帮助修复单元测试以获得授权。

views.py:

from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.template import loader, RequestContext
from django.contrib import auth
from django import forms

def auth_view(request):
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')
    user = auth.authenticate(username=username, password=password)

    if user is not None:
        auth.login(request, user)
        return HttpResponseRedirect('/accounts/loggedin/')
    else:
        return HttpResponseRedirect('/accounts/invalid_login/')

login.html:

{% extends "base.html" %}

{% block title %}Login{% endblock %}

{% block content %}
    {# {{ form.as_p }} #}

    {% if form.errors %}
        <p>errors!</p>
    {% endif %}

    <form action="/accounts/auth/" method="post">{% csrf_token %}
        <input type="text" name="username" id="isername" value="" />

        <input type="password" name="password" id="password" value="" />

        <input type="submit" value="login" />
    </form>
{% endblock %}

urls.py:

from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from django.conf import settings

admin.autodiscover()

urlpatterns = patterns('accounts',
    url(r'^login/$', 'views.login'),
    url(r'^auth/$', 'views.auth_view'),
)

tests.py:

from django.test import TestCase
from django.test.client import Client


class TestLogin(TestCase):
    def test_login(self):
        client = Client()
        response = client.post('/accounts/auth/', {'username': 'qwe', 'password': 'qwe'})
        print(response.content)
        self.assertEqual(response.status_code, 302)

我正在进行2项测试:一项针对现有用户(用户名:qwe,密码:qwe),2位针对不存在的用户(用户名:qwerty,密码:qwe)。由于控制台显示相同的message

所以我不知道是否成功

1 个答案:

答案 0 :(得分:0)

我假设您正在测试身份验证,因为这就是您的代码所说的内容。由于您返回相同的HTTP状态代码,因此您的用户都会在测试中传递断言。更改auth_view方法可以执行此操作:

 if user is not None:
       auth.login(request, user)
       return HttpResponseRedirect('/accounts/loggedin/')
   else:
       return HttpResponseForbidden()

所以当你这样做时:

self.assertEqual(response.status_code, 302)

它只会传递给现有用户。