gpt4 book ai didi

python - Django 单元测试在登录时提供匿名用户

转载 作者:行者123 更新时间:2023-12-04 11:48:03 27 4
gpt4 key购买 nike

我有以下用于 Django 登录单元测试的代码。

"""This is the unit test case for form element"""
from django.test import TestCase
from django.contrib.auth.models import User


class TestForm(TestCase):
def setUp(self):
self.credentials = {
'username': 'abhishek',
'password': 'Abhishek@12345'}
User.objects.create_user(**self.credentials)

def test_login(self):
# send login data
response = self.client.post('/accounts/login', self.credentials, follow=True)
# should be logged in now
print(response.context['user'])
self.assertTrue(response.context['user'].is_authenticated)

当我通过我的命令 python ../manage.py test accounts.tests.test_form.TestForm 执行这个单元测试时,它给出了以下错误。
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
AnonymousUser
F
======================================================================
FAIL: test_login (accounts.tests.test_form.TestForm)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Django\webapplication\accounts\tests\test_form.py", line 18, in test_login
self.assertTrue(response.context['user'].is_authenticated)
AssertionError: False is not true

----------------------------------------------------------------------
Ran 1 test in 3.391s

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

这是我的登录views.py
from django.shortcuts import render, redirect, render_to_response
from django.contrib import auth
from accounts.forms import UserAttributeModelForm, UserModelForm

LOG = logging.getLogger(__name__)

def login(request):
"""This is the function to Login authenticated user"""
LOG.debug("Inside Login function")
message = ""
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = auth.authenticate(username=username, password=password)
if user is not None:
# correct username and password login the user
auth.login(request, user)
return redirect("/crudapplication/show")
else:
message = "Error wrong username/password"
return render(request, 'registration/login.html', {'message': message})

有人可以帮我吗!!!!

最佳答案

替换 self.assertTrue(response.context['user'].is_authenticated)self.assertTrue(response.context['user'].is_active)希望这对您有所帮助,否则您可以回复我,我将分享完整的登录测试用例。

关于python - Django 单元测试在登录时提供匿名用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59532005/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com