Skip to content

Instantly share code, notes, and snippets.

@elebow
Created October 17, 2019 01:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elebow/d3158afd7c5674e4ff95b89271b7ae7d to your computer and use it in GitHub Desktop.
Save elebow/d3158afd7c5674e4ff95b89271b7ae7d to your computer and use it in GitHub Desktop.
factory_boy fixture with a recursive factory
import factory
class Comment:
"""A comment model can have replies, which are also Comments."""
def __init__(self, author, text, replies=[]):
self.author = author
self.text = text
self.replies = replies
class CommentFactory(factory.Factory):
class Meta:
model = Comment
exclude = ("tree_depth",)
author = factory.Sequence(lambda n: f"Comment Author Name {n}")
text = factory.Sequence(lambda n: f"text {n}")
@factory.LazyAttribute
def replies(self):
if self.tree_depth <= 0:
return []
else:
num_children = 3
return [
CommentFactory.build(tree_depth=self.tree_depth - 1)
for m in range(num_children)
]
comment_tree = CommentFactory(tree_depth=2)
assert len(comment_tree.replies) == 3
assert len(comment_tree.replies[0].replies) == 3
assert len(comment_tree.replies[0].replies[0].replies) == 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment