User Authentication in Tests with Django factory_boy

When trying to unit test some part of my code, I need a user to log in. To reduce the number of devices, I use the django_factory_boy User factory, but the created user cannot authenticate.

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

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

then authenticate(username=user.username, password='password')return Noneinstead of user. Any ideas on what's missing here?

+5
source share
3 answers

You should call user.save()after user.set_password(), because set_passwordit does not save the user, sets only the data.

+3
source

Another way to do this:

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
+8
source

@ 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
+7

All Articles