Created
October 17, 2019 01:03
-
-
Save elebow/d3158afd7c5674e4ff95b89271b7ae7d to your computer and use it in GitHub Desktop.
factory_boy fixture with a recursive factory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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