你如何使用factory_boy来建模MongoEngine EmbeddedDocument?

时间:2013-01-15 20:22:32

标签: python django mongoengine factory-boy

我正在尝试使用factory_boy帮助为我的测试生成一些MongoEngine文档。我在定义EmbeddedDocumentField个对象时遇到了麻烦。

这是我的MongoEngine Document

class Comment(EmbeddedDocument):
    content = StringField()
    name = StringField(max_length=120)

class Post(Document):
    title = StringField(required=True)
    tags = ListField(StringField(), required=True)
    comments = ListField(EmbeddedDocumentField(Comment))

这是我部分完成的factory_boy Factory

class CommentFactory(factory.Factory):
    FACTORY_FOR = Comment
    content = "Platinum coins worth a trillion dollars are great"
    name = "John Doe"

class BlogFactory(factory.Factory):
    FACTORY_FOR = Blog
    title = "On Using MongoEngine with factory_boy"
    tags = ['python', 'mongoengine', 'factory-boy', 'django']
    comments = [factory.SubFactory(CommentFactory)] # this doesn't work

有关如何指定comments字段的任何想法?问题是工厂男孩试图创建Comment EmbeddedDocument。

2 个答案:

答案 0 :(得分:3)

我不确定这是不是你想要的但是我刚刚开始研究这个问题,这似乎有效:

from mongoengine import EmbeddedDocument, Document, StringField, ListField, EmbeddedDocumentField
import factory

class Comment(EmbeddedDocument):
    content = StringField()
    name = StringField(max_length=120)

class Post(Document):
    title = StringField(required=True)
    tags = ListField(StringField(), required=True)
    comments = ListField(EmbeddedDocumentField(Comment))


class CommentFactory(factory.Factory):
    FACTORY_FOR = Comment
    content = "Platinum coins worth a trillion dollars are great"
    name = "John Doe"

class PostFactory(factory.Factory):
    FACTORY_FOR = Post
    title = "On Using MongoEngine with factory_boy"
    tags = ['python', 'mongoengine', 'factory-boy', 'django']
    comments = factory.LazyAttribute(lambda a: [CommentFactory()])

>>> b = PostFactory()
>>> b.comments[0].content
'Platinum coins worth a trillion dollars are great'

如果我遗失某些东西,我不会感到惊讶。

答案 1 :(得分:2)

我现在正在做的方法是阻止基于EmbeddedDocuments的工厂构建。所以,我已经设置了一个EmbeddedDocumentFactory,如下所示:

class EmbeddedDocumentFactory(factory.Factory):

    ABSTRACT_FACTORY = True

    @classmethod
    def _prepare(cls, create, **kwargs):                                        
        return super(EmbeddedDocumentFactory, cls)._prepare(False, **kwargs)

然后我继承了为EmbeddedDocuments创建工厂:

class CommentFactory(EmbeddedDocumentFactory):

    FACTORY_FOR = Comment

    content = "Platinum coins worth a trillion dollars are great"
    name = "John Doe"

这可能不是最好的解决方案,所以在接受其他人作为答案之前,我会等待别人回复。