2012-04-17 47 views
5

當試圖對我的代碼的一部分進行單元測試時,我需要一個用戶才能登錄。爲了減少我使用的燈具數量django_factory_boy用戶工廠,但用戶生成的無法驗證。在使用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,而不是用戶。任何有關這裏失蹤的想法?

回答

3

您應該在user.set_password()之後撥打user.save(),因爲set_password本身不保存用戶,只設置數據。

+0

謝謝!我終於找到了解決方案,但由於我的低信譽而無法回覆自己。 – sebastibe 2012-04-17 05:08:49

8

另一種方式來做到這一點:

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%[email protected]" % n) 
    username = factory.Sequence(lambda n: "email%[email protected]" % 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 
7

@安德魯 - 馬吉解決方案的工作,但這裏的解決方案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的控制檯:

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

我也更喜歡這個解決方案。它清楚地記錄在[factory_boy文檔](https://factoryboy.readthedocs.org/en/latest/reference.html#factory.PostGenerationMethodCall) – Merwan 2015-05-19 09:14:54

+0

謝謝@Merwan,我編輯了我的文章 – 2015-05-19 10:44:48

相關問題