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

浙公网安备 33010602011771号