[Solved]-Change default faker locale in factory_boy

9👍

UPD As I said, this solution is suboptimal:

  • factory.Faker._DEFAULT_LOCALE is a private field
  • fake() and faker() use the private interface
  • fake() doesn’t work since factory-boy==3.1.0
  • if I were to use faker, I’d use it directly, not via factory-boy

You should generally prefer the other answer. Leaving this one for posterity.


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 fake
print(fake('random_int'))
print(faker().random_int())
👤x-yuri

13👍

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

As such, to change the default locale for a part of a test:

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

For the whole test:

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

For all the tests (Django):

# settings.py
TEST_RUNNER = 'myproject.testing.MyTestRunner'

# myproject/testing.py
import factory
from django.conf import settings
from django.util import translation
import django.test.runner

class MyTestRunner(django.test.runner.DiscoverRunner):
    def run_tests(self, test_labels, extra_tests=None, **kwargs):
        with factory.Faker.override_default_locale(translation.to_locale(settings.LANGUAGE_CODE)):
            return super().run_tests(test_labels, extra_tests=extra_tests, **kwargs)

More on it here.

👤Xelnor

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

3👍

With Django, you can simply insert the following lines in <myproject>/settings.py:

import factory
factory.Faker._DEFAULT_LOCALE = 'fr_FR'

0👍

Further to @xelnor’s answer, if using pytest (instead of Django manage.py test), add a hookwrapper on the pytest_runtestloop hook in your conftest.py to set the default locale for all the tests:

@pytest.hookimpl(hookwrapper=True)
def pytest_runtestloop(session):
    with factory.Faker.override_default_locale(translation.to_locale(settings.LANGUAGE_CODE)):
        outcome = yield
👤amolbk

Leave a comment