From 030329132892a2ae73f171951d7a18780d23448d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nad=C3=A8ge=20Michel?= Date: Fri, 30 Oct 2020 17:44:28 +0100 Subject: [PATCH] Add documentation --- docs/introduction.rst | 56 ++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 53 insertions(+), 3 deletions(-) diff --git a/docs/introduction.rst b/docs/introduction.rst index d26e4b9f..bf5090a4 100644 --- a/docs/introduction.rst +++ b/docs/introduction.rst @@ -324,10 +324,11 @@ A trait is toggled by a single boolean value: Strategies ---------- -All factories support two built-in strategies: +All factories support three built-in strategies: * ``build`` provides a local object * ``create`` instantiates a local object, and saves it to the database. +* ``create async`` similar to create but can run asynchronous code. .. note:: For 1.X versions, the ``create`` will actually call ``AssociatedClass.objects.create``, as for a Django model. @@ -351,13 +352,62 @@ Calling a :class:`~factory.Factory` subclass will provide an object through the .. code-block:: pycon >>> MyFactory.create() - + + + >>> MyFactory.create_async() + >>> MyFactory.build() - + >>> MyFactory() # equivalent to MyFactory.create() The default strategy can be changed by setting the ``class Meta`` :attr:`~factory.FactoryOptions.strategy` attribute. + + +Async Factories +--------------- + +If your project uses asynchronous code to save objects to database, you +can use that in your factories too. + +You need to override the async method :meth:`factory.Factory._create_model_async` +to define how your objects are created and saved to the database. + +You can then either: +- use :meth:`factory.Factory.create_async` +- inherit from `:class:`~factory.AsyncFactory` instead of `:class:`~factory.Factory` + to make ``create async`` the default strategy and then call the factory. + +.. code-block:: python + class MyClass: + ... + + @classmethod + async def write_in_db(*args, **kwargs): + ... + + + class MyFactory(factory.AsyncFactory): + class Meta: + model = MyClass + + @classmethod + async def _create_model_async(cls, model_class, *args, **kwargs): + await model_class.write_in_db(*args, **kwargs) + +.. code-block:: pycon + + >>> MyFactory.create() + + + >>> MyFactory.create_async() + + + >>> MyFactory.build() + + + >>> MyFactory() # equivalent to MyFactory.create_async() + \ No newline at end of file