如何为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
相关产品推荐
相关产品推荐

