summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRaphaël Barrois <raphael.barrois@polytechnique.org>2016-02-09 23:57:31 +0100
committerRaphaël Barrois <raphael.barrois@polytechnique.org>2016-02-09 23:57:31 +0100
commit229d43874723f36b380eb49e53538bf21511fa5a (patch)
tree2f12ee3eaf241cd05e73a0cff3a85ea519c06a54
parent4172dd686ce483191b33e3189d716f11b3da921e (diff)
downloadfactory-boy-229d43874723f36b380eb49e53538bf21511fa5a.tar
factory-boy-229d43874723f36b380eb49e53538bf21511fa5a.tar.gz
Clarify the use of SelfAttribute in RelatedFactory (Closes #264)
-rw-r--r--docs/reference.rst17
-rw-r--r--tests/test_using.py30
2 files changed, 47 insertions, 0 deletions
diff --git a/docs/reference.rst b/docs/reference.rst
index 6398d9a..b5ccd16 100644
--- a/docs/reference.rst
+++ b/docs/reference.rst
@@ -1412,6 +1412,23 @@ If a value if passed for the :class:`RelatedFactory` attribute, this disables
1
+.. note:: The target of the :class:`RelatedFactory` is evaluated *after* the initial factory has been instantiated.
+ This means that calls to :class:`factory.SelfAttribute` cannot go higher than this :class:`RelatedFactory`:
+
+ .. code-block:: python
+
+ class CountryFactory(factory.Factory):
+ class Meta:
+ model = Country
+
+ lang = 'fr'
+ capital_city = factory.RelatedFactory(CityFactory, 'capital_of',
+ # factory.SelfAttribute('..lang') will crash, since the context of
+ # ``CountryFactory`` has already been evaluated.
+ main_lang=factory.SelfAttribute('capital_of.lang'),
+ )
+
+
PostGeneration
""""""""""""""
diff --git a/tests/test_using.py b/tests/test_using.py
index c7d2b85..0a893c1 100644
--- a/tests/test_using.py
+++ b/tests/test_using.py
@@ -1924,6 +1924,36 @@ class PostGenerationTestCase(unittest.TestCase):
self.assertEqual(3, related.one)
self.assertEqual(4, related.two)
+ def test_related_factory_selfattribute(self):
+ class TestRelatedObject(object):
+ def __init__(self, obj=None, one=None, two=None):
+ obj.related = self
+ self.one = one
+ self.two = two
+ self.three = obj
+
+ class TestRelatedObjectFactory(factory.Factory):
+ class Meta:
+ model = TestRelatedObject
+ one = 1
+ two = factory.LazyAttribute(lambda o: o.one + 1)
+
+ class TestObjectFactory(factory.Factory):
+ class Meta:
+ model = TestObject
+ one = 3
+ two = 2
+ three = factory.RelatedFactory(TestRelatedObjectFactory, 'obj',
+ two=factory.SelfAttribute('obj.two'),
+ )
+
+ obj = TestObjectFactory.build(two=4)
+ self.assertEqual(3, obj.one)
+ self.assertEqual(4, obj.two)
+ self.assertEqual(1, obj.related.one)
+ self.assertEqual(4, obj.related.two)
+
+
class RelatedFactoryExtractionTestCase(unittest.TestCase):
def setUp(self):