You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用pytest测试返回函数的函数或方法?

解决函数返回对象的测试问题

你的问题核心是:两次调用methodcaller生成的是不同实例,直接用==比较对象身份会失败。这里提供两种可行的测试思路:

1. 测试函数的实际行为(推荐)

与其纠结对象是否相同,不如测试返回的函数能不能正确完成预期操作。可以用Mock对象模拟依赖,验证函数调用是否符合预期:

首先修正原代码的导入错误(from operator import methodcaller),然后编写测试:

import pytest
from operator import methodcaller
from unittest.mock import Mock
import numpy as np

def foo(info: str):
    imshow = methodcaller("imshow", np.zeros((3,3)))
    a = {'a': imshow}
    return a.get(info)

def test_foo_behavior():
    # 创建模拟的Axes对象
    mock_ax = Mock()
    # 获取foo返回的函数
    imshow_func = foo('a')
    # 调用函数,传入模拟对象
    imshow_func(mock_ax)
    # 验证imshow方法是否被正确调用,参数是否匹配
    mock_ax.imshow.assert_called_once_with(np.zeros((3,3)))

2. 比较methodcaller的内部属性

operator.methodcaller的实例包含_name、_args、_kwargs三个核心属性,分别存储要调用的方法名、位置参数和关键字参数。可以直接比较这些属性来验证一致性:

def test_foo_attributes():
    expected = methodcaller("imshow", np.zeros((3,3)))
    result = foo('a')
    
    # 比较方法名
    assert result._name == expected._name
    # 比较数组参数(用numpy的数组相等判断)
    assert np.array_equal(result._args[0], expected._args[0])
    # 比较关键字参数(这里为空)
    assert result._kwargs == expected._kwargs

注意:第二种方法依赖methodcaller的内部实现细节,若后续Python版本修改这些属性名,测试会失效。因此优先选择行为测试,它更关注业务逻辑而非底层实现。

内容的提问来源于stack exchange,提问作者Samuel Diop

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 17:19:02