[英]Django test client does not log in
我正在嘗試使用其內置的登錄功能登錄測試客戶端。 我正在嘗試單元測試視圖,需要登錄才能測試其中的一些。 我一直試圖這么做並需要幫助。 幾點說明:
create_user()確實創建了一個有效的用戶,它已在其他位置使用。
從我所看到的client.login()它返回一個布爾值,當我運行我的測試失敗是“假不是真”,所以這似乎是正確的。
我成功登錄的唯一方法是調用client.post(“/ my / login / url”,{dict中的用戶名和密碼。}}但是,出於某種原因它並沒有為我的所有測試用例保持登錄狀態我覺得很奇怪。
def setUp(self):
"""
Initializes the test client and logs it in.
"""
self.user = create_user()
self.logged_in = self.client.login(username=self.user.username, password=self.user.password)
def test_valid(self):
self.assertTrue(self.logged_in)
我已將其更改為以下內容:
def setUp(self):
"""
Initializes the test client and logs it in.
"""
self.password = "password"
self.user = create_user(password=self.password)
self.logged_in = self.client.login(username=self.user.username, password=self.password)
它仍然無法登錄。
create user在類“Static”中並且user_count初始化為0,函數如下:
def create_user(username=None, password=None, email=None, is_superuser=False):
if username is None:
username = "user%d" % Static.user_count
while User.objects.filter(username=username).count() != 0:
Static.user_count += 1
username = "user%d" % Static.user_count
if password is None:
password = "password"
if email is None:
email="user%d@test.com" % Static.user_count
Static.user_count += 1
user = User.objects.create(username=username, password=password, is_superuser=is_superuser)
您無法直接訪問密碼。 password
屬性已加密。 (請參閱Django中的密碼管理 。)
例如,這里是密碼的示例輸出。
>>> user = User.objects.create_user(username='asdf', email='asdf@example.com', password='xxxx')
>>> user.password
'sha1$166e7$4028738f0c0df0e7ec3cec06843c35d2b5a1aae8'
如您所見, user.password
不是我給出的xxxx
。
我修改create_user
以接受可選的密碼參數。 並將密碼傳遞給create_user
和client.login
,如下所示:
def setUp(self):
"""
Initializes the test client and logs it in.
"""
password = 'secret'
self.user = create_user(password=password)
self.logged_in = self.client.login(username=self.user.username, password=password)
UPDATE
create_user
應使用User.objects.create_user
而不是User.objects.create
。 並且應該返回創建的用戶對象:
def create_user(username=None, password=None, email=None, is_superuser=False):
if username is None:
username = "user%d" % Static.user_count
while User.objects.filter(username=username).count() != 0:
Static.user_count += 1
username = "user%d" % Static.user_count
if password is None:
password = "password"
if email is None:
email="user%d@test.com" % Static.user_count
Static.user_count += 1
user = User.objects.create_user(username=username, password=password)
# ^^^^^^^^^^^
user.is_superuser = is_superuser
user.save()
return user # <---
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.