当我尝试对我的代码的某些部分进行单元测试时,我需要一个用户才能登录。为了减少我使用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
而不是用户。关于这里缺少什么的想法?
答案 0 :(得分: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
答案 1 :(得分:9)
@ Andrew-Magee解决方案有效,但这里解决方案describe in the doc:
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
答案 2 :(得分:4)
您应该在user.save()
之后致电user.set_password()
,因为set_password
本身不会保存用户,只会设置数据。