When trying to unit test some part of my code, I need a user to be logged in. For reducing the number of fixtures I am using django_factory_boy User factory but the User generated is unable to 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 None
instead of the User. Any ideas about what is missing here?
@Andrew-Magee solution works, but here the solution 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 = '[email protected]'
password = factory.PostGenerationMethodCall('set_password', 'password')
Django console :
>>> from tests.factories import UserFactory
>>> from django.contrib.auth.models import check_password
>>> user = UserFactory()
>>> user.email
'[email protected]'
>>> check_password('password', user.password)
True
>>> user2 = UserFactory(username="SecondUserFactory", email='[email protected]', password="ComplexPasswordMuchLonger!")
>>> user2.email
'[email protected]'
>>> check_password('ComplexPasswordMuchLonger!', user2.password)
True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With