Django 1.8 中的登录测试用例失败

Login test cases failing in Django 1.8

今天学习用Django写测试用例,写了一个验证有效用户认证的测试用例。

from django.test import TestCase
from django.http import HttpRequest
from aptly_dash.views import newRepo, homePage
from selenium import webdriver
from django.test import Client

class MyTestCase(TestCase):

    def setUp(self):
        self.client = Client()
        self.browser = webdriver.Firefox()
    #
    def tearDown(self):
        self.browser.quit()

    def test_redirect(self):
        response = self.client.get('/admin/')
        self.assertRedirects(response, '/admin/login/?next=/admin/')

    def test_login(self):
        # Issue a GET request.
        response = self.client.login(username='rakesh', password='ranjan')
        print response

我已经创建了 username='rakesh'password='ranjan',但 response 即将成为 False。我对编写测试用例相当陌生,如果有人能告诉我我的 test_login 函数有什么问题,我将不胜感激。我还想编写一个测试用例来检查 django URL 是否对未经身份验证的用户 403 禁止,以及对经过身份验证但不是员工用户 403 禁止。谁能给我一个好的文档。

尝试将用户添加到设置中:

def setUp(self):
    self.client = Client()
    user = User.objects.create_user('rakesh', 'rakesh@rakesh.com', 'ranjan')
        self.browser = webdriver.Firefox()

每次当你 运行 测试时,你都有一个 'new database'。

如果你想登录一个用户,执行一些测试,你需要在每个 TestCase 上创建他。

Finally, you’ll need to remember to create user accounts before you can use this method. As we explained above, the test runner is executed using a test database, which contains no users by default. As a result, user accounts that are valid on your production site will not work under test conditions. You’ll need to create users as part of the test suite – either manually (using the Django model API) or with a test fixture. Remember that if you want your test user to have a password, you can’t set the user’s password by setting the password attribute directly – you must use the set_password() function to store a correctly hashed password. Alternatively, you can use the create_user() helper method to create a new user with a correctly hashed password.

也许看到这个 doc,会有帮助