Faker is a Python package that generates fake data for you. Whether you need to bootstrap your database, create good-looking XML documents, fill-in your persistence to stress test it, or anonymize data taken from a production service, Faker is for you.
If you use factoryboy you'd probably have it. If you don't use
pip install faker
Or add it to the project
Faker includes a
faker fixture for pytest.
def test_faker(faker): assert isinstance(faker.name(), str)
By default it's populated with a seed of
0, to set a random seed add the following to your test configuration.
from random import SystemRandom @pytest.fixture(scope="session", autouse=True) def faker_seed() -> int: """Create a random seed for the Faker library.""" return SystemRandom().randint(0, 999999)
Generate fake number⚑
If you want to specify max and min values use:
Generate a fake dictionary⚑
fake.pydict(nb_elements=5, variable_nb_elements=True, *value_types)
*value_types can be
If you want a CIDR, use
Sadly, there is no official provider for
Enums, but NazarioJL made a custom provider.
pip install faker-enum
from enum import Enum from faker import Faker from faker_enum import EnumProvider fake = Faker() fake.add_provider(EnumProvider) class Color(Enum): RED = 1 GREEN = 2 BLUE = 3 fake.enum(Color) # One of [Color.RED, Color.GREEN, Color.BLUE]
pip install fake-optional
from faker import Faker from faker_optional import OptionalProvider fake = Faker() fake.add_provider(OptionalProvider) fake.optional_int() # None fake.optional_int() # 1234
OptionalProvider uses existent faker providers to create the data, so you can use the provider method arguments.
optional_int uses the
python provider pyint, so you can use the
step arguments. Every
optional_ method accepts the float
ratio argument between
1, with a default value of
0.5 to define what percent of results should be
None, a greater value will mean that less results will be
Check the supported methods.
Providers are just classes which define the methods we call on
Faker objects to generate fake data.
To define a provider, you need to create a class that inherits from the
BaseProvider. That class can then define as many methods as you want.
Once your provider is ready, add it to your
import random from faker import Faker from faker.providers import BaseProvider fake = Faker() # Our custom provider inherits from the BaseProvider class TravelProvider(BaseProvider): def destination(self): destinations = ['NY', 'CO', 'CA', 'TX', 'RI'] # We select a random destination from the list and return it return random.choice(destinations) # Add the TravelProvider to our faker object fake.add_provider(TravelProvider) # We can now use the destination method: print(fake.destination())
If you want to give arguments when calling the provider, add them to the provider method.