在定义函数的文件中修补函数
Posted
技术标签:
【中文标题】在定义函数的文件中修补函数【英文标题】:Patching a function in a file where it is defined 【发布时间】:2019-07-23 23:17:51 【问题描述】:我正在尝试学习单元测试补丁。我有一个文件,它都定义了一个函数,然后使用该函数。当我尝试修补这个函数时,它的返回值是 real 返回值,而不是 patched 返回值。
如何修补在同一个文件中定义和使用的函数?注意:我确实尝试遵循here 给出的建议,但似乎并没有解决我的问题。
walk_dir.py
从 os.path 导入目录名,加入 从操作系统导入步行 从 json 导入加载 定义 get_config(): current_path = 目录名(__file__) 使用 open(join(current_path, 'config', 'json', 'folder.json')) 作为 json_file: json_data = 加载(json_file) 返回 json_data['parent_dir'] def get_all_folders(): dir_to_walk = get_config() 对于 root、dir、_ in walk(dir_to_walk): return [join(root, name) for name in dir]test_walk_dir.py
从 hello_world.walk_dir 导入 get_all_folders 从 unittest.mock 导入补丁 @patch('walk_dir.get_config') def test_get_all_folders(mock_get_config): mock_get_config.return_value = 'C:\\temp\\test\\' 结果 = get_all_folders() 断言集(结果)== 集('C:\\temp\\test\\test_walk_dir')【问题讨论】:
【参考方案1】:尝试以这种方式声明补丁:
@patch('hello_world.walk_dir.get_config')
正如您所链接的问题所看到的this answer,建议您的import
语句与您的patch
语句相匹配。在您的情况下,from hello_world.walk_dir import get_all_folders
和 @patch('walk_dir.get_config')
不匹配。
【讨论】:
以上是关于在定义函数的文件中修补函数的主要内容,如果未能解决你的问题,请参考以下文章