Bird
Raised Fist0
Djangoframework~20 mins

Factory Boy for test data in Django - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Factory Boy Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What does this Factory Boy factory produce?
Given the following factory definition, what will be the value of user.email after user = UserFactory() is executed?
Django
import factory
from myapp.models import User

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

    username = factory.Sequence(lambda n: f'user{n}')
    email = factory.LazyAttribute(lambda obj: f'{obj.username}@example.com')

user = UserFactory()
A"user0@example.com"
BRaises an AttributeError
C"user1@example.com"
D"user@example.com"
Attempts:
2 left
💡 Hint
Look at how the username is generated and how email uses it.
📝 Syntax
intermediate
2:00remaining
Which factory definition has a syntax error?
Identify the factory definition that will cause a syntax error when run.
A
class ProductFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Product
    price = factory.Faker('random_number', digits=3)
B
)3=stigid ,'rebmun_modnar'(rekaF.yrotcaf = ecirp    
tcudorP = ledom        
:ateM ssalc    
:)yrotcaFledoMognajD.ognajd.yrotcaf(yrotcaFtcudorP ssalc
C
class ProductFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Product
    name = factory.Faker('word')
    price = factory.Faker('random_number', digits=3)
D
class ProductFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Product
    name = factory.Faker('word')
Attempts:
2 left
💡 Hint
Check the commas between arguments in function calls.
state_output
advanced
2:00remaining
What is the value of order.total after creation?
Given this factory and model, what will order.total be after order = OrderFactory()?
Django
import factory
from myapp.models import Order

class OrderFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Order

    quantity = 3
    price_per_item = 10
    total = factory.LazyAttribute(lambda o: o.quantity * o.price_per_item)

order = OrderFactory()
A0
BNone
CRaises AttributeError
D30
Attempts:
2 left
💡 Hint
Look at how total is calculated using LazyAttribute.
🔧 Debug
advanced
2:00remaining
Why does this factory raise a RecursionError?
Examine the factory below. Why does creating an instance with profile = ProfileFactory() cause a RecursionError?
Django
import factory
from myapp.models import Profile, User

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

    username = factory.Sequence(lambda n: f'user{n}')

class ProfileFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Profile

    user = factory.SubFactory(UserFactory)
    friend = factory.SubFactory('myapp.factories.ProfileFactory')

profile = ProfileFactory()
ABecause UserFactory is missing a required field
BBecause factory.SubFactory requires a callable, not a string
CBecause ProfileFactory references itself in friend causing infinite recursion
DBecause Profile model does not have a friend field
Attempts:
2 left
💡 Hint
Look at the friend field in ProfileFactory.
🧠 Conceptual
expert
3:00remaining
Which option correctly uses Factory Boy to create related objects with different attributes?
You want to create a Book with two Author objects, each having different names. Which factory setup achieves this correctly?
Django
from myapp.models import Book, Author
import factory

class AuthorFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Author

    name = factory.Sequence(lambda n: f'Author {n}')

class BookFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Book

    title = 'My Book'
    authors = factory.RelatedFactoryList(AuthorFactory, related_name='book', size=2)
AUse SubFactory twice in BookFactory for authors with fixed names
BUse RelatedFactoryList with size=2 and AuthorFactory with Sequence for names
CUse RelatedFactoryList with size=2 but AuthorFactory has fixed name 'Author'
DUse a post_generation hook to add two authors with different names manually
Attempts:
2 left
💡 Hint
Think about how to create multiple related objects with unique attributes.

Practice

(1/5)
1. What is the main purpose of using Factory Boy in Django testing?
easy
A. To create reusable fake data for tests easily
B. To speed up the Django server
C. To replace Django's ORM
D. To deploy Django applications automatically

Solution

  1. Step 1: Understand Factory Boy's role

    Factory Boy is designed to generate fake data for tests, making test setup easier and less repetitive.
  2. Step 2: Eliminate unrelated options

    Speeding up the server, replacing ORM, or deployment are unrelated to test data creation.
  3. Final Answer:

    To create reusable fake data for tests easily -> Option A
  4. Quick Check:

    Factory Boy = reusable fake test data [OK]
Hint: Factory Boy = fake test data creator [OK]
Common Mistakes:
  • Thinking Factory Boy speeds up the server
  • Confusing Factory Boy with deployment tools
  • Assuming Factory Boy replaces Django ORM
2. Which of the following is the correct way to define a basic factory for a Django model Book using Factory Boy?
easy
A. class BookFactory(factory.DjangoModelFactory): class Meta: model = Book
B. class BookFactory(factory.Factory): model = Book
C. class BookFactory(factory.ModelFactory): model = Book
D. class BookFactory(factory.DjangoFactory): class Meta: model = Book

Solution

  1. Step 1: Identify correct base class

    Factory Boy uses DjangoModelFactory as the base class for Django models.
  2. Step 2: Check Meta class usage

    The model must be specified inside a nested Meta class with attribute model.
  3. Final Answer:

    class BookFactory(factory.DjangoModelFactory): class Meta: model = Book -> Option A
  4. Quick Check:

    DjangoModelFactory + Meta.model = correct syntax [OK]
Hint: Use DjangoModelFactory with Meta.model for Django models [OK]
Common Mistakes:
  • Using factory.Factory instead of DjangoModelFactory
  • Not using a Meta class for model assignment
  • Using incorrect base class names
3. Given this factory definition:
class UserFactory(factory.DjangoModelFactory):
    class Meta:
        model = User
    username = factory.Faker('user_name')
    email = factory.Faker('email')

What will UserFactory().username return?
medium
A. None, because username is not set
B. The literal string 'user_name'
C. An error because Faker is not imported
D. A random username string generated by Faker

Solution

  1. Step 1: Understand Faker usage in Factory Boy

    Using factory.Faker('user_name') generates a random username string each time the factory is called.
  2. Step 2: Evaluate the expression UserFactory().username

    Calling UserFactory() creates a User instance with a random username, so .username returns that random string.
  3. Final Answer:

    A random username string generated by Faker -> Option D
  4. Quick Check:

    Faker('user_name') = random username string [OK]
Hint: Faker fields produce random data, not literals [OK]
Common Mistakes:
  • Thinking Faker returns the field name as string
  • Assuming missing imports cause runtime error here
  • Expecting None if not explicitly set
4. What is wrong with this factory code?
class ProductFactory(factory.DjangoModelFactory):
    class Meta:
        model = Product
    name = factory.Faker('product_name')
    price = factory.Faker('float')
medium
A. Faker does not have a 'product_name' provider
B. The 'float' provider requires arguments to specify range
C. Missing import of factory module
D. Meta class should be outside the factory class

Solution

  1. Step 1: Check Faker providers used

    Faker has no built-in 'product_name' provider, but this is a common custom name; however, 'float' requires arguments like min and max.
  2. Step 2: Identify the error cause

    Using factory.Faker('float') without arguments causes an error because Faker's float provider needs parameters.
  3. Final Answer:

    The 'float' provider requires arguments to specify range -> Option B
  4. Quick Check:

    Faker float needs min/max args [OK]
Hint: Faker float needs range arguments to work [OK]
Common Mistakes:
  • Assuming 'product_name' is always valid
  • Ignoring required arguments for Faker float
  • Thinking Meta class placement is wrong
5. You want to create a factory for a Django model Order that has a foreign key to User. How do you correctly define the user field in OrderFactory to use UserFactory?
hard
A. user = UserFactory()
B. user = factory.RelatedFactory(UserFactory)
C. user = factory.SubFactory(UserFactory)
D. user = factory.Faker('user')

Solution

  1. Step 1: Understand foreign key factory usage

    To link a foreign key to another factory, use factory.SubFactory with the related factory class.
  2. Step 2: Evaluate options

    Directly calling UserFactory() assigns an instance at class load time, not per object. RelatedFactory is for reverse relations. Faker does not create model instances.
  3. Final Answer:

    user = factory.SubFactory(UserFactory) -> Option C
  4. Quick Check:

    Foreign key uses SubFactory [OK]
Hint: Use SubFactory for foreign key relations [OK]
Common Mistakes:
  • Calling UserFactory() directly in factory field
  • Using RelatedFactory for foreign keys
  • Using Faker for model relations