繁体   English   中英

Django 测试 - authenticate() 返回无

[英]Django Testing - authenticate() returns None

使用 Django 进行一些单元测试,并尝试使用登录表单对登录过程进行一些测试。

我使用修改后的User model 只是为了使 email 字段唯一; 否则没有什么不同。

帐户/views.py

def post(self, request):
    # Retrieve the username and password
    username = request.POST['username']
    password = request.POST['password']

    # Create a user object from authentication, or return None
    user = authenticate(username=username, password=password)

    # Check if user was created
    if user is not None:
        # Rest of the code, irrelevant...

帐户/test_views.py

from account.models import User as CustomUser    

# Code snippit

def test_account_login_POST_successful_login(self):
    # Create a user to test login
    CustomUser.objects.create_user(
        username='test_user',
        email='test_user@intranet.com',
        password='flibble'
    )

    response = self.client.post(self.login_url, {
        'username': 'test_user',
        'password': 'flibble'
    })

    self.assertEqual(response.status_code, 301)

帐户/models.py

class User(AbstractUser):
    # Make the email field unique
    email = models.EmailField(unique=True)

项目/settings.py

# Authentication
AUTH_USER_MODEL = 'account.User'

有趣的是,登录在 web 应用程序上正常工作,但在测试时它总是返回None

我尝试使用创建的用户check_password() ,它在测试方法和视图方法中都返回 true。

我也尝试输入AUTHENTICATION_BACKEND = ['django.contrib.auth.backends.ModelBackend'] ,但没有 go。

我遇到了同样的问题。 问题出在is_active model 字段中。 在我的情况下,该字段默认为False ,因此authenticate()始终返回None

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM