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

Jas*_*gan 5 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))
Run Code Online (Sandbox Code Playgroud)

这是我部分完成的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
Run Code Online (Sandbox Code Playgroud)

任何想法如何指定comments字段?问题是工厂男孩试图创建CommentEmbeddedDocument.

And*_*gee 5

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

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'
Run Code Online (Sandbox Code Playgroud)

如果我遗漏了什么,我不会感到惊讶。


Jas*_*gan 2

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

class EmbeddedDocumentFactory(factory.Factory):

    ABSTRACT_FACTORY = True

    @classmethod
    def _prepare(cls, create, **kwargs):                                        
        return super(EmbeddedDocumentFactory, cls)._prepare(False, **kwargs)
Run Code Online (Sandbox Code Playgroud)

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

class CommentFactory(EmbeddedDocumentFactory):

    FACTORY_FOR = Comment

    content = "Platinum coins worth a trillion dollars are great"
    name = "John Doe"
Run Code Online (Sandbox Code Playgroud)

这可能不是最好的解决方案,因此我会等待其他人做出回应,然后再接受此答案。