【发布时间】: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')【问题讨论】:
标签: python unit-testing mocking