6

当尝试对我的代码的某些部分进行单元测试时,我需要一个用户登录。为了减少我正在使用 django_factory_boy 用户工厂的装置数量,但生成的用户无法进行身份验证。

from django_factory_boy.auth import UserF
from django.contrib.auth import authenticate

user = UserF()
user.set_password('password')

然后authenticate(username=user.username, password='password')返回None而不是用户。关于这里缺少什么的任何想法?

4

3 回答 3

10

@Andrew-Magee 解决方案有效,但这里的解决方案在文档中描述

import factory
from django.contrib.auth.models import User
#or
#from somewhere import CustomUser as User

class UserFactory(factory.DjangoModelFactory):
    FACTORY_FOR = User

    username = 'UserFactory'
    email = 'test@example.com'
    password = factory.PostGenerationMethodCall('set_password', 'password')

Django控制台:

>>> from tests.factories import UserFactory
>>> from django.contrib.auth.models import check_password
>>> user = UserFactory()
>>> user.email
'test@example.com'
>>> check_password('password', user.password)
True

>>> user2 = UserFactory(username="SecondUserFactory", email='otheremail@example.com', password="ComplexPasswordMuchLonger!")
>>> user2.email
'otheremail@example.com'
>>> check_password('ComplexPasswordMuchLonger!', user2.password)
True
于 2013-12-15T09:29:55.070 回答
9

另一种方法:

import factory
from django.contrib.auth.hashers import make_password
from somewhere import YourUserModel

class UserF(factory.django.DjangoModelFactory):
    FACTORY_FOR = YourUserModel
    first_name = factory.Sequence(lambda n: "First%s" % n)
    last_name = factory.Sequence(lambda n: "Last%s" % n)
    email = factory.Sequence(lambda n: "email%s@example.com" % n)
    username = factory.Sequence(lambda n: "email%s@example.com" % n)
    password = make_password("password")
    is_staff = False

>>> u = UserF.create()
>>> u.check_password("password")
True

>>> p = UserF.create(password=make_password("password2"))
>>> p.check_password("password2")
True
于 2013-07-09T07:15:46.387 回答
4

您应该调用user.save()afteruser.set_password()因为set_password它本身不保存用户,只设置数据。

于 2012-04-17T03:55:06.993 回答