You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何自定义pytest打印对象的方式?适配MongoEngine Document对象

自定义pytest中MongoEngine Document对象的打印逻辑

方法1:通过pytest钩子自定义断言时的对象展示

如果主要想在断言失败时让Document对象输出更有意义的内容,可在项目根目录的conftest.py中添加pytest_assertrepr_compare钩子:

def pytest_assertrepr_compare(config, op, left, right):
    from mongoengine import Document
    # 检查是否涉及MongoEngine Document实例
    if isinstance(left, Document) or isinstance(right, Document):
        def format_doc(doc):
            if isinstance(doc, Document):
                return f"<Document: {doc.to_json(indent=2)}>"
            return repr(doc)
        return [
            f"断言失败: {format_doc(left)} {op} {format_doc(right)}",
        ]

这样当包含Document对象的断言失败时,pytest会输出to_json()生成的结构化内容,替代默认的<Document: Document object>。

方法2:全局覆盖Document类的__repr__方法

如果希望所有场景(包括pytest打印、直接print对象)都生效,可直接给Document类替换自定义的__repr__方法。在项目初始化文件(如__init__.py或测试入口文件)中添加:

from mongoengine import Document

# 保存原始repr方法用于异常回退
original_repr = Document.__repr__

def custom_doc_repr(self):
    try:
        return f"<Document: {self.to_json(indent=2)}>"
    except Exception:
        return original_repr(self)

Document.__repr__ = custom_doc_repr

这种方式无需修改pytest配置,所有地方打印Document对象都会使用自定义输出。

注意事项

  • 若Document有子类已重写__repr__,需单独对子类做相同处理
  • 可调整to_json()的参数,比如去掉indent=2让输出更紧凑,或指定fields参数只打印关键字段

内容的提问来源于stack exchange,提问作者Aviad Rozenhek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 08:22:42