问题描述
Factory_boy
使用 fake-factory(Faker)
生成随机值,我想直接在Faker的Django测试中生成一些随机值.
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文档建议使用 factory.Faker
及其提供者为:
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'>
从 factory_boy
faker.py
类中 factory.Faker('ean',length = 10)
调用 faker.Faker.ean(length = 10)
,但是 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'
还有其他方法可以使用 Faker
代替直接从 Faker
设置实例吗?
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()
推荐答案
我知道这是一个老问题,但对于可能遇到此问题的任何人,这是您可以使用的另一种方法.
I know this is an old question but for anyone who might come across this, here's another approach that you can use.
>>> from factory.faker import faker
>>> FAKE = faker.Faker()
>>> FAKE.name()
'Scott Rodriguez'
>>> FAKE.address()
'PSC 5061, Box 1673\nAPO AP 53007'
>>>
这篇关于如何从Factory_boy使用Faker的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!