我正在尝试学习单元测试修补。我有一个文件,它定义了一个函数,然后使用该函数。当我尝试修补此函数时,它的返回值给我的是真实返回值,而不是修补返回值。
如何修补在同一文件中定义和使用的函数?注意:我确实尝试遵循 here 给出的建议,但这似乎并没有解决我的问题。
walk_dir.py
from os.path import dirname, join from os import walk from json import load def get_config(): current_path =dirname(__file__) with open(join(current_path, 'config', 'json', 'folder.json')) as json_file: json_data = load(json_file) return json_data['parent_dir'] def get_all_folders(): dir_to_walk = get_config() for root, dir, _ in walk(dir_to_walk): return [join(root, name) for name in dir]
test_walk_dir.py
from hello_world.walk_dir import get_all_folders from unittest.mock import patch @patch('walk_dir.get_config') def test_get_all_folders(mock_get_config): mock_get_config.return_value = 'C:\\temp\\test\\' result = get_all_folders() assert set(result) == set('C:\\temp\\test\\test_walk_dir')
最佳答案
尝试以这种方式声明补丁:
@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')
不匹配。
关于python - 修补定义函数的文件中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54952836/