Pytest - 钩子函数
- pytest_assertrepr_compare(op,left,right):
class Foo:
def __init__(self,value):
self.value = value
def test_foo_commpare():
f1 = Foo(1)
f2 = Foo(2)
assert f1 == f2
运行结果:断言失败提示信息不够清晰
如何解决?
方式一:
重写__repr__方法:
class Foo:
def __init__(self,value):
self.value = value
def __repr__(self):
return self.__class__.__name__ + f"({self.value})"
def test_foo_commpare():
f1 = Foo(1)
f2 = Foo(2)
assert f1 == f2
方法二:
# @File:conftest.py
from test_scripts.test_assert_hook import Foo
def pytest_assertrepr_compare(op,left,right):
if isinstance(left, Foo) and isinstance(right,Foo) and op == '==':
return [
"比较两个实例的值",
f'{left.value} != {right.value}'
]
运行结果:
======================================================================= test session starts =======================================================================
platform win32 -- Python 3.10.1, pytest-7.2.0, pluggy-1.0.0 -- e:\pyproject\pytestdemo\venv\scripts\python.exe
cachedir: .pytest_cache
rootdir: E:\PyProject\pytestDemo
collected 3 items
test_scripts/test_assert_hook.py::test_foo_commpare FAILED [ 33%]
test_scripts/test_importtoskip.py::test_sample[4-2] PASSED [ 66%]
test_scripts/test_importtoskip.py::test_sample[XPASS] XPASS [100%]
============================================================================ FAILURES =============================================================================
________________________________________________________________________ test_foo_commpare ________________________________________________________________________
def test_foo_commpare():
f1 = Foo(1)
f2 = Foo(2)
> assert f1 == f2
E assert 比较两个实例的值
E 1 != 2
test_scripts\test_assert_hook.py:17: AssertionError
===================================================================== short test summary info =====================================================================
FAILED test_scripts/test_assert_hook.py::test_foo_commpare - assert 比较两个实例的值
============================================================= 1 failed, 1 passed, 1 xpassed in 0.10s ==============================================================
本文来自博客园,作者:chuangzhou,转载请注明原文链接:https://www.cnblogs.com/czzz/p/16939582.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!