I'd like to have FactoryBoy create a Django model instance for me, and then also create a temporary directory.
I've tried a few things:
class OrganizationFactory(factory.DjangoModelFactory):
class Meta:
model = Organization
some_directory = tempfile.mkdtemp
and
some_directory = tempfile.mkdtemp()
and
@factory.lazy_attribute
def some_directory(self):
return tempfile.mkdtemp()
When I try to use some_directory in my tests, the value is always None.
In order to understand what happens, the best will be to dive into factory_boy's internals.
factory_boy internals
There are separate phases in a
Factory's life:When Python imports the module containing a
class Factorydeclaration, that class's definition is handled to a special metaclass in factory_boy's source code. The metaclass reads all defined class attributes and methods, analyses them, and stores them in a specific way.When your code uses
MyFactory(), the class starts building an instance, according to the following steps:LazyAttribute,SubFactory, etc. is asked to generate its value;Meta.modelclass constructor — this provides an instance of said class;RelatedFactoryand co) to work on the generated object — note that any value returned from those declarations is thrown awaySolving your issue
In your case, I believe the issue might be that
some_directoryis either not a valid kwarg for your model's__init__, or replaced by some magic on your model class.The simplest way would be to work on the post-generation level: