2014-10-10 106 views
0

在Django測試課程中,self.client.login(...)正在返回False,我不明白爲什麼。這是測試模塊在Django測試中無法登錄剛剛創建的用戶

"""Tests for views.""" 
from django.contrib.auth.models    import User 
from .models        import UserProfile 
from django.test       import TestCase 

TEST_USER = {"username": "kermit", "password": "timrek", 
      "first_name": "Kermit", "last_name": "The Frog", 
      "birth_year": 1955,  "email":  "[email protected]"} 

class ViewTestCase(TestCase): 
    """Tests for views.""" 
    def setUp(self_ignored): 
     """Insert demo users.""" 

     user = User(
      username=TEST_USER['username'], password=TEST_USER['password'], 
      first_name=TEST_USER['first_name'], 
      last_name=TEST_USER['last_name'], email=TEST_USER['email']) 
     user.save() 

     profile = UserProfile(user_id=user.id, 
           birth_year=TEST_USER['birth_year']) 
     profile.save() 

試圖登錄用戶中的功能(這是相同的文件的底部):

def test__view_for_logged_in_user(self): 
     """Verify expected content on the main birth-stats page, for a 
      logged-in user. 
     """ 

     print("TEST_USER=" + TEST_USER) 

     did_login_succeed = self.client.login(
      username=TEST_USER['username'], 
      password=TEST_USER['password']) 

     #print the just inserted users 
     users = User.objects.all() 
     print("Total users actually in the database=" + str(users.count())) 
     for user in users: 
      print('Actually-inserted user: ' + str(user)) 

     self.assertTrue(did_login_succeed)  #Fails 

     #test view here 

正如可以在調試輸出看到,測試用戶確實正在插入:

$ python manage.py test auth_lifecycle.test__views2 
Creating test database for alias 'default'... 
TEST_USER={'username': 'kermit', 'email': '[email protected]', 'password': 'timrek', 'birth_year': 1955, 'last_name': 'The Frog', 'first_name': 'Kermit'} 
Total users actually in the database=1 
Actually-inserted user: kermit 
F 
====================================================================== 
FAIL: test__view_for_logged_in_user (auth_lifecycle.test__views2.ViewTestCase) 
Verify expected content on the main birth-stats page, for a 
---------------------------------------------------------------------- 
Traceback (most recent call last): 
    File "/home/jeffy/django_files/django_auth_lifecycle/auth_lifecycle/test__views2.py", line 47, in test__view_for_logged_in_user 
    self.assertTrue(did_login_succeed) 
AssertionError: False is not true 

---------------------------------------------------------------------- 
Ran 1 test in 0.009s 

FAILED (failures=1) 
Destroying test database for alias 'default'... 

爲什麼此登錄失敗(返回False)?


這裏的模型

"""Defines a single extra user-profile field for the user-authentication 
    lifecycle demo project: Birth year. 
""" 
from django.contrib.auth.models import User 
from django.db     import models 

class UserProfile(models.Model): 
    """One piece of extra information about a user: Birth year. 

     ---NOTES--- 

     Useful related SQL: 
      - `select id from auth_user where username <> 'admin';` 
      - `select * from auth_lifecycle_userprofile where user_id=(x,x,...);` 
    """ 
    # This line is required. Links UserProfile to a User model instance. 
    user = models.OneToOneField(User, related_name="profile") 

    # The additional attributes we wish to include. 
    birth_year = models.IntegerField(
     blank=True, 
     verbose_name="Year you were born") 

    # Override the __str__() method to return out something meaningful 
    def __str__(self): 
     return self.user.username 

回答

3

雖然

user = User(
    username=TEST_USER['username'], password=TEST_USER['password'], 
    first_name=TEST_USER['first_name'], 
    last_name=TEST_USER['last_name'], email=TEST_USER['email']) 
user.save() 

節省了用戶對數據庫的密碼不正確哈希和鹽漬(我認爲這就是問題所在)。因此,嘗試使用該密碼登錄失敗(login返回False)。

self.client.login(
    username=TEST_USER['username'], 
    password=TEST_USER['password']) #Not the same as in the database! 

的解決方案是使用create_user function代替:

user = User.objects.create_user(
    username=TEST_USER['username'], password=TEST_USER['password'], 
    first_name=TEST_USER['first_name'], 
    last_name=TEST_USER['last_name'], email=TEST_USER['email']) 
相關問題