55326

Change default faker locale in factory_boy

Question:

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'

Answer1:

Not a good solution, but for now it's as good as it gets. You can change the <a href="https://github.com/FactoryBoy/factory_boy/blob/v2.9.0/factory/faker.py#L58" rel="nofollow">variable</a> 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())

Answer2:

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')

Answer3:

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()

Recommend