Performance: Factory Boy for test data
This affects test suite execution speed and memory usage during automated testing.
Jump into concepts and practice - no test required
import factory class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User username = factory.Faker('user_name') email = factory.Faker('email') def test_user_creation(): user = UserFactory() assert user.username is not None
def test_user_creation(): user = User.objects.create(username='testuser', email='test@example.com') assert user.username == 'testuser'
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Direct model creation in tests | N/A | N/A | N/A | [X] Bad |
| Using Factory Boy for test data | N/A | N/A | N/A | [OK] Good |
Factory Boy in Django testing?Book using Factory Boy?DjangoModelFactory as the base class for Django models.Meta class with attribute model.class UserFactory(factory.DjangoModelFactory):
class Meta:
model = User
username = factory.Faker('user_name')
email = factory.Faker('email')UserFactory().username return?factory.Faker('user_name') generates a random username string each time the factory is called.UserFactory() creates a User instance with a random username, so .username returns that random string.class ProductFactory(factory.DjangoModelFactory):
class Meta:
model = Product
name = factory.Faker('product_name')
price = factory.Faker('float')factory.Faker('float') without arguments causes an error because Faker's float provider needs parameters.Order that has a foreign key to User. How do you correctly define the user field in OrderFactory to use UserFactory?factory.SubFactory with the related factory class.UserFactory() assigns an instance at class load time, not per object. RelatedFactory is for reverse relations. Faker does not create model instances.