Django factory-boy custom provider

128 Views Asked by At

I would like to create my own customer Faker provider.

I am using factory-boy which comes already with Faker included, so in my test factories I am using for a UserFactory

name = factory.Faker('name')

My question is, can I somehow implement my own custom provider? So I could use factory.Faker('my_provider')? Or for that I would have to swap all factory.Faker() instances and just use Faker() instance?

1

There are 1 best solutions below

0
Richard Scholtens On

You can inherit the BaseProvider class and define your custom functions. Afterwards you can add it to a Faker object.

There are two possible options:

1. Retrieve factory Faker object from factory library and add custom provider.

In this scenario you retrieve the instantiated Faker object from the factory library using a private get method. Please note, it is bad practice to access private methods outside of a class.

import factory
from faker import providers

class HelloWorldProvider(providers.BaseProvider):
    """Use provider to generate `hello world`.""" 
    def hello_world(self) -> str:
        """Say hello to the world"""
        return "hello world"
factory.Faker.add_provider(HelloWorldProvider)

fake = factory.Faker._get_faker()
print(fake.hello_world())


2. Instantiate new Faker object and add custom provider

With this option you achieve the same result without accessing any private methods outside of the class. I would advise on this course of action.

import faker

fake = faker.Faker()


class HelloWorldProvider(faker.providers.BaseProvider):
    """Use provider to generate `hello world`.""" 

    def hello_world(self) -> str:
        """Say hello to the world"""
        return "hello world"

fake.add_provider(HelloWorldProvider)
print(fake.hello_world())

Faker BaseProvider reference