diff options
author | Raphaël Barrois <raphael.barrois@polytechnique.org> | 2012-11-14 23:15:55 +0100 |
---|---|---|
committer | Raphaël Barrois <raphael.barrois@polytechnique.org> | 2012-11-15 00:03:37 +0100 |
commit | c86d32b892c383fb18b0a5d7cebc7671e4e88ab1 (patch) | |
tree | 2622da13d44f06e819c5705aaf06b22a158143c6 /factory | |
parent | ac90ac4b3425cc79c164b3dc0bd13901bf814ff7 (diff) | |
download | factory-boy-c86d32b892c383fb18b0a5d7cebc7671e4e88ab1.tar factory-boy-c86d32b892c383fb18b0a5d7cebc7671e4e88ab1.tar.gz |
Mix SelfAttribute with ContainerAttribute.
With a very simple syntax.
Signed-off-by: Raphaël Barrois <raphael.barrois@polytechnique.org>
Diffstat (limited to 'factory')
-rw-r--r-- | factory/declarations.py | 15 |
1 files changed, 14 insertions, 1 deletions
diff --git a/factory/declarations.py b/factory/declarations.py index 50a826f..fe1afa4 100644 --- a/factory/declarations.py +++ b/factory/declarations.py @@ -100,7 +100,11 @@ def deepgetattr(obj, name, default=_UNSPECIFIED): class SelfAttribute(OrderedDeclaration): """Specific OrderedDeclaration copying values from other fields. + If the field name starts with two dots or more, the lookup will be anchored + in the related 'parent'. + Attributes: + depth (int): the number of steps to go up in the containers chain attribute_name (str): the name of the attribute to copy. default (object): the default value to use if the attribute doesn't exist. @@ -108,11 +112,20 @@ class SelfAttribute(OrderedDeclaration): def __init__(self, attribute_name, default=_UNSPECIFIED, *args, **kwargs): super(SelfAttribute, self).__init__(*args, **kwargs) + depth = len(attribute_name) - len(attribute_name.lstrip('.')) + attribute_name = attribute_name[depth:] + + self.depth = depth self.attribute_name = attribute_name self.default = default def evaluate(self, sequence, obj, containers=()): - return deepgetattr(obj, self.attribute_name, self.default) + if self.depth > 1: + # Fetching from a parent + target = containers[self.depth - 2] + else: + target = obj + return deepgetattr(target, self.attribute_name, self.default) class Iterator(OrderedDeclaration): |