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

如何为Python unittest类动态添加多个patch装饰器实现批量打桩

实现方案

我们可以自定义一个patch_list批量装饰器,内部遍历所有待补丁的目标路径,依次调用unittest.mock.patch装饰测试类即可,无需修改除test.py外的其他文件,也不需要手动堆叠多个patch装饰器。

完整test.py代码

import unittest
from unittest.mock import patch
import use_source

# 待补丁的目标路径列表,可根据需求动态增减
file_names = ["use_source.example_function", "use_source2.example_function"]


def fake_function():
    print("I want this to run instead")


# 自定义批量patch装饰器
def patch_list(targets, new):
    def decorator(cls):
        # 遍历所有目标路径,依次给测试类应用patch装饰器
        for target in targets:
            cls = patch(target, new=new)(cls)
        return cls
    return decorator


@patch_list(file_names, new=fake_function)
class ExampleTest(unittest.TestCase):
    def test_example(self):
        use_source.call_example_function()
        # 其他调用不同模块example_function的测试用例也会自动使用fake_function


if __name__ == '__main__':
    unittest.main()

实现原理

类装饰器的本质是接收一个类作为输入、返回修改后类的函数。上述patch_list实现中,我们循环对测试类应用所有patch装饰器,效果和手动堆叠多个@patch装饰器完全一致,天然支持长度不固定的动态补丁列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 13:27:03