aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSamuel Paccoud <samuel@sampaccoud.com>2016-04-03 09:42:40 +0200
committerSamuel Paccoud <samuel@sampaccoud.com>2016-04-03 09:42:40 +0200
commit5836329889ac45034978c69b6a6f7de4b0b5b75d (patch)
tree3407a1e904bca49d599aff799c9d161d5b29eb2a
parentc22729d03d291814ae196ce7652954db9e42ed97 (diff)
downloadfactory-boy-5836329889ac45034978c69b6a6f7de4b0b5b75d.tar
factory-boy-5836329889ac45034978c69b6a6f7de4b0b5b75d.tar.gz
Add documentation and test for subfactory using "factory_parent" attribute
Add documentation on how to use a LazyAttribute in a SubFactory and poke the "factory_parent" attribute to indirectly derive the value of a field on the child factory from a field on the parent factory. This commit adds an example to recipes that explains how it can be done. It also adds a test to make sure that this feature continues to work as is now described in the documentation.
-rw-r--r--docs/recipes.rst14
-rw-r--r--tests/test_using.py20
2 files changed, 34 insertions, 0 deletions
diff --git a/docs/recipes.rst b/docs/recipes.rst
index a3df7be..fe18f50 100644
--- a/docs/recipes.rst
+++ b/docs/recipes.rst
@@ -327,7 +327,21 @@ Here, we want:
country = factory.SubFactory(CountryFactory)
owner = factory.SubFactory(UserFactory, country=factory.SelfAttribute('..country'))
+If the value of a field on the child factory is indirectly derived from a field on the parent factory, you will need to use LazyAttribute and poke the "factory_parent" attribute.
+This time, we want the company owner to live in a country neighboring the country of the company:
+
+.. code-block:: python
+
+ class CompanyFactory(factory.django.DjangoModelFactory):
+ class Meta:
+ model = models.Company
+
+ name = "ACME, Inc."
+ country = factory.SubFactory(CountryFactory)
+ owner = factory.SubFactory(UserFactory,
+ country=factory.LazyAttribute(lambda o: get_random_neighbor(o.factory_parent.country)))
+
Custom manager methods
----------------------
diff --git a/tests/test_using.py b/tests/test_using.py
index eaeb8da..0ce29e9 100644
--- a/tests/test_using.py
+++ b/tests/test_using.py
@@ -1268,6 +1268,26 @@ class SubFactoryTestCase(unittest.TestCase):
self.assertEqual('x0x', test_model.two.one)
self.assertEqual('x0xx0x', test_model.two.two)
+ def test_sub_factory_with_lazy_fields_access_factory_parent(self):
+ class TestModel2(FakeModel):
+ pass
+
+ class TestModelFactory(FakeModelFactory):
+ class Meta:
+ model = TestModel
+ one = 3
+
+ class TestModel2Factory(FakeModelFactory):
+ class Meta:
+ model = TestModel2
+ one = 'parent'
+ child = factory.SubFactory(TestModelFactory,
+ one=factory.LazyAttribute(lambda o: '%s child' % o.factory_parent.one),
+ )
+
+ test_model = TestModel2Factory()
+ self.assertEqual('parent child', test_model.child.one)
+
def test_sub_factory_and_sequence(self):
class TestObject(object):
def __init__(self, **kwargs):