what is it?
factory_boy is a fixtures replacement tool based on thoughtbot’s factory_bot
it aims to replace static, hard to maintain fixtures with easy-to-use factories for complex objects
using factory_boy with ORMs
django
all factories for a django model should use the DjangoModelFactory base class
DjangoModelFactory provides the following features
modelattribute also supports the'app.Model'syntaxcreate()usesModel.objects.create()- when using
RelatedFactoryorPostGenerationattributes, the base object will besavedonce all post-generation hooks have run.
class UserFactory(DjangoModelFactory):
class Meta:
model = User
username = Faker("user_name")
email = LazyAttribute(lambda o: '%s@example.com' % o.username)
password = LazyAttribute(lambda o: make_password(o.username))
first_name = Faker("first_name")
last_name = Faker("last_name")- to not save the instance to db and build in memory, use build()
user = UserFactory.build()
LazyAttribute
building block for extending a factory
takes as argument a method to call (usually a lambda); that method should accept the object being built as sole argument, and return a value
class UserFactory(factory.Factory):
class Meta:
model = User
username = 'john'
email = factory.LazyAttribute(lambda o: '%s@example.com' % o.username)Faker
wrapper around faker; its argument is the name of a faker provider
can use previous attribute in Faker:
class TripFactory(factory.Factory):
class Meta:
model = Trip
departure = factory.Faker(
'date',
end_datetime=datetime.date.today(),
)
arrival = factory.Faker(
'date_between_dates',
date_start=factory.SelfAttribute('..departure'),
)