gpt4 book ai didi

python - 如何使用 factory_boy 为 MongoEngine EmbeddedDocument 建模?

转载 作者:太空狗 更新时间:2023-10-30 01:09:19 24 4
gpt4 key购买 nike

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

这是我的 MongoEngine 文档:

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 字段有什么想法吗?问题是 factory-boy 试图创建 Comment EmbeddedDocument。

最佳答案

我不确定这是否是您想要的,但我刚开始研究这个问题,这似乎可行:

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'

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

关于python - 如何使用 factory_boy 为 MongoEngine EmbeddedDocument 建模?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14346177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com