如何自定义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
相关产品推荐
相关产品推荐

