2

如果我为测试创建示例用户帐户,则会出现此错误:

未知密码散列算法“password1”。您是否在 PASSWORD_HASHERS 设置中指定了它?

class ExampleTest(TestCase):
    def test_sample_data(self):
        for i in range(0,1):
            user = content.factories.UserFactory.create()

工厂.py:

class UserFactory(factory.Factory):
    FACTORY_FOR = User

    username = factory.Sequence(lambda n: 'User' + n)
    email = 'mail@gmail.com'
    password = 'password1'

如何解决?

编辑:

解决方案:

user = content.factories.UserFactory.create()
user.set_password('yourpassword')
user.save()
4

2 回答 2

1

更新。它在文档中有所描述,您应该使用factory.PostGenerationMethodCall

class UserFactory(factory.Factory):
    class Meta:
        model = User

    username = 'user'
    password = factory.PostGenerationMethodCall('set_password',
                                                'defaultpassword')

旧答案。实际上,这在factory-boy 文档中有所描述:

class UserFactory(factory.Factory):
    @classmethod
    def _prepare(cls, create, **kwargs):
        password = kwargs.pop('password', None)
        user = super(UserFactory, cls)._prepare(create, **kwargs)
        if password:
            user.set_password(password)
            if create:
                user.save()
        return user

最好使用这个解决方案,这样你就可以正确使用UserFactory.build(),UserFactory.create()UserFactory.attributes()(稍后会返回未哈希的密码)

于 2013-06-20T05:05:26.300 回答
0
class UserFactory(factory.Factory):
    FACTORY_FOR = User

    username = 'user'
    password = factory.PostGenerationMethodCall('set_password',
                                            'defaultpassword')

请参阅此处的文档https://factoryboy.readthedocs.org/en/v1.3.0/reference.html#postgenerationmethodcall

于 2013-08-20T10:12:01.110 回答