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 ============================================================== 

https://www.cnblogs.com/congyinew/p/16483675.html

posted @   chuangzhou  阅读(56)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示