From 715276f3a47b34d40574cb22e806ee1fa2d100f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Barrois?= Date: Fri, 6 Jan 2012 23:13:57 +0100 Subject: Add docs for SubFactory. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Raphaƫl Barrois --- docs/index.rst | 4 ++++ docs/subfactory.rst | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 docs/subfactory.rst diff --git a/docs/index.rst b/docs/index.rst index 69b3b99..17d81c1 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -54,9 +54,13 @@ Once defined, a factory can be instantiated through different methods:: Contents: +:doc:`SubFactory ` + .. toctree:: :maxdepth: 2 + subfactory + Indices and tables ================== diff --git a/docs/subfactory.rst b/docs/subfactory.rst new file mode 100644 index 0000000..8bc1d8f --- /dev/null +++ b/docs/subfactory.rst @@ -0,0 +1,56 @@ +SubFactory +========== + +Some objects may use other complex objects as parameters; in order to simplify this setup, factory_boy +provides the :py:class:`factory.SubFactory` class. + +This should be used when defining a :py:class:`~factory.Factory` attribute that will hold the other complex object:: + + import factory + + # A standard factory + class UserFactory(factory.Factory): + FACTORY_FOR = User + + # Various fields + first_name = 'John' + last_name = factory.Sequence(lambda n: 'D%se' % (o * n)) + email = factory.LazyAttribute(lambda o: '%s.%s@example.org' % (o.first_name.lower(), o.last_name.lower())) + + # A factory for an object with a 'User' field + class CompanyFactory(factory.Factory): + FACTORY_FOR = Company + + name = factory.Sequence(lambda n: 'FactoryBoyz' + z * n) + + # Let's use our UserFactory to create that user, and override its first name. + owner = factory.SubFactory(UserFactory, first_name='Jack') + +Instantiating the external factory will in turn instantiate an object of the internal factory:: + + >>> c = CompanyFactory() + >>> c + + + # Notice that the first_name was overridden + >>> c.owner + + >>> c.owner.email + jack.de@example.org + +Fields of the SubFactory can also be overridden when instantiating the external factory:: + + >>> c = CompanyFactory(owner__first_name='Henry') + >>> c.owner + + + # Notice that the updated first_name was propagated to the email LazyAttribute. + >>> c.owner.email + henry.doe@example.org + + # It is also possible to override other fields of the SubFactory + >>> c = CompanyFactory(owner__last_name='Jones') + >>> c.owner + + >>> c.owner.email + henry.jones@example.org -- cgit v1.2.3