0
0
Djangoframework~5 mins

Factory Boy for test data in Django

Choose your learning style9 modes available
Introduction

Factory Boy helps you create fake data easily for testing your Django apps. It saves time and keeps tests clean.

When you need to create many test users with different details.
When you want to test how your app works with various data without typing it all manually.
When you want to avoid repeating the same setup code in multiple tests.
When you want your tests to be easy to read and maintain.
When you want to quickly generate related objects, like a blog post with an author.
Syntax
Django
import factory
from myapp.models import MyModel

class MyModelFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = MyModel

    field1 = 'default value'
    field2 = factory.Faker('name')

Define a factory class inheriting from DjangoModelFactory.

Set the Meta.model to the Django model you want to create data for.

Examples
This factory creates fake users with random usernames and emails.
Django
class UserFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = User

    username = factory.Faker('user_name')
    email = factory.Faker('email')
    password = 'testpass'
This factory creates articles with a linked author created by UserFactory.
Django
class ArticleFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Article

    title = factory.Faker('sentence')
    content = factory.Faker('text')
    author = factory.SubFactory(UserFactory)
Sample Program

This test uses Factory Boy to create a user with fake username and email. It checks the user has these fields and prints them.

Django
import factory
from django.test import TestCase
from django.contrib.auth.models import User

class UserFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = User

    username = factory.Faker('user_name')
    email = factory.Faker('email')
    password = 'testpass'

class UserTest(TestCase):
    def test_user_creation(self):
        user = UserFactory()
        self.assertTrue(user.username)
        self.assertTrue(user.email)
        print(f"Created user: {user.username}, email: {user.email}")
OutputSuccess
Important Notes

You can customize fields with Faker or fixed values.

Use SubFactory to create related objects automatically.

Factories help keep tests fast and easy to write.

Summary

Factory Boy creates fake test data easily for Django models.

It helps avoid repetitive setup code in tests.

Use DjangoModelFactory and Faker to define factories.