【发布时间】:2015-07-17 14:10:39
【问题描述】:
我正在尝试熟悉 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)
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')
但是我经常收到以下错误:
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。
我做错了什么,我该如何正确替换sanitize_line_ending 中input_path.in_place() 的返回值。
【问题讨论】:
标签: python unit-testing mocking