Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User authentication in tests with Django factory_boy

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?

like image 595
sebastibe Avatar asked Apr 17 '12 00:04

sebastibe


1 Answers

@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
like image 132
Guillaume Vincent Avatar answered Nov 15 '22 09:11

Guillaume Vincent