python - 修补定义函数的文件中的函数

标签 python unit-testing mocking

我正在尝试学习单元测试修补。我有一个文件,它定义了一个函数,然后使用该函数。当我尝试修补此函数时,它的返回值给我的是真实返回值,而不是修补返回值。

如何修补在同一文件中定义和使用的函数?注意:我确实尝试遵循 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/

相关文章:

c# - C# 中的 Moq Application.Current.MainWindow

java - 具有返回 void 的可运行参数的模拟方法

ruby-on-rails - Rails Fixtures 与 Mocks

python - 在 python 2.7 中设置已弃用

python - 如何使用 Selenium 和 Python 阻止或设置 HTML5 视频自动播放?

python - 为什么 multiprocessing.Pool 不能改变全局变量?

python - 在 Django 中记录请求 URL

unit-testing - Grails使用Spring Security Core插件测试用户角色自定义验证约束

java - 每次和任何测试用例初始化 mockito 时出错

python - 在 Python 中模拟一个类以调用其方法之一