官方實例
# 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后的描述信息更靈活。