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

如何使用mocker.patch测试函数内部定义的testfunction_extra?

问题原因

你用的patch路径根本无效,因为testfunction_extra是test_split_kwargs方法里定义的局部函数,它不属于TestUtil.test_split_kwargs的属性,没法通过「模块-类-方法」的层级路径访问,所以才会抛出AttributeError。

解决方案

分两种场景处理:

场景1:仅在测试逻辑内断言该函数的调用

完全不需要patch,直接用mocker.Mock()创建模拟函数替代原局部函数,调用完成后直接用assert_has_calls断言即可。

示例代码:

import pytest

class TestUtil:
    def test_split_kwargs(self, mocker):
        # 用mock替代原局部函数
        mock_test_func = mocker.Mock(return_value='56')
        
        # 替换成你原本调用testfunction_extra的测试逻辑
        mock_test_func(e='5', f='6')
        mock_test_func(e='10', f='20')
        
        # 断言调用顺序与参数
        expected_calls = [
            pytest.call(e='5', f='6'),
            pytest.call(e='10', f='20')
        ]
        mock_test_func.assert_has_calls(expected_calls, any_order=False)

场景2:被测试的外部代码会调用该函数

需要把testfunction_extra移到模块级别(即TestUtil类外部),让它成为模块的属性,这样就能通过模块路径正常patch了。

调整后的代码:

import pytest

# 移到模块级别,成为模块属性
def testfunction_extra(e='5',f='6'):
    return e+f

class TestUtil:
    def test_split_kwargs(self, mocker):
        # 现在可以正确patch
        mock_func = mocker.patch(__name__ + '.testfunction_extra')
        # 执行会调用testfunction_extra的被测试代码
        # ...
        
        # 断言调用情况
        mock_func.assert_has_calls([pytest.call(e='5', f='6')])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 02:20:38