Faker and Factory Boy

Testing Django App with faker and factory_boy

Faker: Generate fake data

Factory Boy: Create factories of our models

Factory Boy is an alternative to Django testing fixtures. When testing a Django application you often need to populate the test database with some sample data. The standard Django TestCase has support for fixture loading but there are a number of problems with using fixtures. Factory boy is a fixture replacement tool, it aims to replace static, hard to maintain fixtures with easy-to-use factories for complex objects.

factory_boy provides a class DjangoModelFactory as a base class for Django unit test factories.

pip install factory_boy
# factories.py

import factory

class CompanyFactory(factory.DjangoModelFactory):
    """
       | id  | name      |
       |:----|:----------|
       |  1  | X Company |
    """
    class Meta:
        model = 'core.Company'
        django_get_or_create = ('name',)
        
    name = factory.Faker('name')
    created = factory.Faker('date', end_datetime=datetime.date.today())    

The factory’s Meta has django_get_or_create set, which means the factory will call the Django built-in `Company.objects.get_or_create` method.

We can create more objects:

Create Batch

Features of Factory Boy:

circle-check

Sequence

circle-check

LazyAttribute

circle-check

LazyFunction

circle-check

SubFactories

circle-check

Many-to-many relationship

Last updated