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

标签 python django unit-testing testcase

我有以下用于 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/

相关文章:

Python乘法表语法差异

python - 将 UUIDField 转换为 CharField

django - 确认设备 : Invalid device key given 上的 AWS Cognito Boto3 错误

objective-c - 是什么导致 Mac OS X 上找不到合适的图像错误?

java - Mockito 测试 RestClient aSync

python - 在 Python 中输入和打印

python - Django:调用自己的模型方法时出现AttributeError

python - runserver 上的 Django 数据库连接验证

php - PHP 中使用 self::的单元测试类

python - 如何在 Python 和 C 中使用三角函数在 GMP/MPFR 中获得非常高的精度?