Change default faker locale in factory_boy

邮差的信 提交于 2019-12-10 14:59:05

问题


How can I set the default locale in Python's factory_boy for all of my Factories?

In docs says that one should set it with factory.Faker.override_default_locale but that does nothing to my fakers...

import factory
from app.models import Example
from custom_fakers import CustomFakers

# I use custom fakers, this indeed are added
factory.Faker.add_provider(CustomFakers)
# But not default locales
factory.Faker.override_default_locale('es_ES')

class ExampleFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Example

    name = factory.Faker('first_name')


>>> from example import ExampleFactory
>>> e1 = ExampleFactory()
>>> e1.name
>>> u'Chad'

回答1:


Not a good solution, but for now it's as good as it gets. You can change the variable that holds the value:

import factory
factory.Faker._DEFAULT_LOCALE = 'xx_XX'

Moreover, you can create a file like this (app/faker.py):

import factory
from faker.providers import BaseProvider

factory.Faker._DEFAULT_LOCALE = 'xx_XX'

def fake(name):
    return factory.Faker(name).generate({})

def faker():
    return factory.Faker._get_faker()

class MyProvider(BaseProvider):
    def category_name(self):
        return self.random_element(category_names)
    ...
factory.Faker.add_provider(MyProvider)

category_names = [...]

Then, once you import the file, the locale changes. Also, you get your providers and an easy way to use factory_boy's faker outside of the factories:

from app.faker import f
print(fake('random_int'))
print(faker().random_int())



回答2:


The Faker.override_default_locale() is a context manager, although it's not very clear from the docs.

This means that you should use one of those forms in your code:

with factory.Faker.override_default_locale('es_ES'):
    ExampleFactory()

Or:

@factory.Faker.override_default_locale('es_ES')
def test_foo(self):
    user = ExampleFactory()



回答3:


I'm having same issue as yours. For a temporary solution try passing locale in factory.Faker.

For example:

name = factory.Faker('first_name', locale='es_ES')


来源:https://stackoverflow.com/questions/45773954/change-default-faker-locale-in-factory-boy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!