Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 views
in Technique[技术] by (71.8m points)

python - How to use Faker from Factory_boy

Factory_boy uses fake-factory (Faker) to generate random values, I would like to generate some random values in my Django tests using Faker directly.

Factory_boy docs suggests using factory.Faker and its provider as :

class RandomUserFactory(factory.Factory):
    class Meta:
        model = models.User

    first_name = factory.Faker('first_name')

But this isn't generating any name:

>>> import factory
>>> factory.Faker('name')
<factory.faker.Faker object at 0x7f1807bf5278>
>>> type(factory.Faker('name'))
<class 'factory.faker.Faker'>

From factory_boy faker.py class factory.Faker('ean', length=10) calls faker.Faker.ean(length=10) but Faker docs says it should show a name:

from faker import Faker
fake = Faker()
fake.name()
# 'Lucy Cechtelar'

Is there any other way to use Faker instead of setting an instance directly from Faker?

from faker import Factory
fake = Factory.create()
fake.name()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use faker with factory_boy like this:

class RandomUserFactory(factory.Factory):
    class Meta:
        model = models.User

    first_name = factory.Faker('first_name')

user = RandomUserFactory()

print user.first_name
# 'Emily'

So you need to instantiate a user with factory_boy and it will call Faker for you.

I don't know if you are trying to use this with Django or not, but if you want the factory to save the created user to the database, then you need to extend factory.django.DjangoModelFactory instead of factory.Factory.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...