在模拟函数时无法返回元组

Var*_*ath 8 python unit-testing mocking

我试图熟悉Python中的模拟,而我在尝试模拟以下函数时遇到了绊脚石.

helpers.py

from path import Path

def sanitize_line_ending(filename):
    """ Converts the line endings of the file to the line endings
        of the current system.
    """
    input_path = Path(filename)

    with input_path.in_place() as (reader, writer):
        for line in reader:
            writer.write(line)
Run Code Online (Sandbox Code Playgroud)

test_helpers.py

@mock.patch('downloader.helpers.Path')
def test_sanitize_line_endings(self, mock_path):
    mock_path.in_place.return_value = (1,2)
    helpers.sanitize_line_ending('varun.txt')
Run Code Online (Sandbox Code Playgroud)

但是我不断收到以下错误:

ValueError: need more than 0 values to unpack

鉴于我已将返回值设置为元组,我不明白为什么Python无法解压缩它.

然后我将我的代码更改为具有test_sanitize_line_endings存储打印返回值,input_path.in_place()并且我可以看到返回值是一个MagicMock对象.特别是它打印的东西 <MagicMock name='Path().in_place()' id='13023525345'> 如果我理解正确的东西,我想要的是mock_path具有in_place函数返回元组的MagicMock.

我做错了什么,我怎样才能正确地替换input_path.in_place()in 的返回值sanitize_line_ending.

Var*_*ath 7

经过多次摸索和参加聚会后,我终于看到这篇博文,最终解决了我的问题。

问题的关键是我没有嘲笑正确的价值。由于我想替换函数调用的结果,因此我需要编写的代码是:

@mock.patch('downloader.helpers.Path')
def test_sanitize_line_endings(self, mock_path):
    mock_path.return_value.in_place.return_value = (1,2)
    helpers.sanitize_line_ending('varun.txt')
Run Code Online (Sandbox Code Playgroud)

这正确地导致函数能够解包元组,然后它立即失败,因为像@didi2002 提到这不是上下文管理器。然而,我专注于让解包工作,在我能够实现之后,用适当的方法用构造替换元组。