ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

13、pytest为失败的断言定义自己的解释

2026/9/16 1:03:45 拓冰建站 浏览量
13、pytest为失败的断言定义自己的解释

官方实例

# content of ocnftest.py
from test_foocompare import Foodef pytest_assertrepr_compare(op, left, right):if isinstance(left, Foo) and isinstance(right, Foo) and op == "==":return["Comparing Foo instances:",f"  vals:{left.val} != {right.val}",]
# content of test_foocompare.py
class Foo:def __init__(self, val):self.val = valdef __eq__(self, other):return self.val == other.valdef test_compare():f1 = Foo(1)f2 = Foo(2)assert f1 == f2

解读与实操

可以通过实现pytest_assertrepr_compare钩子来添加自己的详细解释

pytest_assertrepr_compare(config,op,left,right)

返回失败断言表达式中比较的解释

假如没有自定义解释,则返回None,否则返回字符串列表。字符串将由换行符连接,但字符串中的任何换行符都将被输入。除了第一行之外的所有内容都将略微缩进,目的是让第一行作为摘要。

在这里插入图片描述

场景应用

通过实现钩子函数,可以自定义展示详细解释。比assert后的描述信息更灵活。