如何用unittest.mock测试下面的代码:
def testme(filepath):
with open(filepath) as f:
return f.read()
如何用unittest.mock测试下面的代码:
def testme(filepath):
with open(filepath) as f:
return f.read()
当前回答
上面的答案很有用,但我对它进行了一些扩展。
如果你想根据传递给open()的参数来设置文件对象的值(f in as f),这里有一种方法:
def save_arg_return_data(*args, **kwargs):
mm = MagicMock(spec=file)
mm.__enter__.return_value = do_something_with_data(*args, **kwargs)
return mm
m = MagicMock()
m.side_effect = save_arg_return_array_of_data
# if your open() call is in the file mymodule.animals
# use mymodule.animals as name_of_called_file
open_name = '%s.open' % name_of_called_file
with patch(open_name, m, create=True):
#do testing here
基本上,open()将返回一个对象,with将在该对象上调用__enter__()。
为了正确地模拟,必须mock open()返回一个模拟对象。然后,该模拟对象应该模拟对其进行的__enter__()调用(MagicMock将为我们完成此操作),以返回我们想要的模拟数据/文件对象(因此是mm.__enter__.return_value)。用上述方法对2个mock执行此操作允许我们捕获传递给open()的参数,并将它们传递给do_something_with_data方法。
我将整个模拟文件作为字符串传递给open(),我的do_something_with_data看起来像这样:
def do_something_with_data(*args, **kwargs):
return args[0].split("\n")
这将字符串转换为一个列表,这样你就可以像处理普通文件一样执行以下操作:
for line in file:
#do action
其他回答
Python 3
补丁内置命令。打开并使用mock_open,它是模拟框架的一部分。用作上下文管理器的Patch返回用于替换补丁的对象:
from unittest.mock import patch, mock_open
with patch("builtins.open", mock_open(read_data="data")) as mock_file:
assert open("path/to/open").read() == "data"
mock_file.assert_called_with("path/to/open")
如果您想使用patch作为装饰器,那么使用mock_open()的结果作为patch的new=参数可能会有点奇怪。相反,使用patch的new_callable=参数,并记住patch不使用的每个额外参数将被传递给new_callable函数,如补丁文档中所述:
Patch()接受任意关键字参数。这些将在构造时传递给Mock(或new_callable)。
@patch("builtins.open", new_callable=mock_open, read_data="data")
def test_patch(mock_file):
assert open("path/to/open").read() == "data"
mock_file.assert_called_with("path/to/open")
记住,在这种情况下,patch将模拟对象作为参数传递给测试函数。
Python 2
你需要修补__builtin__。打开而不是内置。Open和mock不是unittest的一部分,你需要分别安装和导入它:
from mock import patch, mock_open
with patch("__builtin__.open", mock_open(read_data="data")) as mock_file:
assert open("path/to/open").read() == "data"
mock_file.assert_called_with("path/to/open")
如果你不需要进一步的文件,你可以装饰测试方法:
@patch('builtins.open', mock_open(read_data="data"))
def test_testme():
result = testeme()
assert result == "data"
我可能对这个游戏有点晚了,但当我在另一个模块中调用open而不必创建新文件时,这对我来说是有效的。
test.py
import unittest
from mock import Mock, patch, mock_open
from MyObj import MyObj
class TestObj(unittest.TestCase):
open_ = mock_open()
with patch.object(__builtin__, "open", open_):
ref = MyObj()
ref.save("myfile.txt")
assert open_.call_args_list == [call("myfile.txt", "wb")]
MyObj.py
class MyObj(object):
def save(self, filename):
with open(filename, "wb") as f:
f.write("sample text")
通过将__builtin__模块中的open函数修补到mock_open()中,我可以模拟写入文件而无需创建一个文件。
注意:如果你正在使用一个使用cython的模块,或者你的程序以任何方式依赖于cython,你将需要导入cython的__builtin__模块,方法是在你的文件顶部包含import __builtin__。如果你正在使用cython,你将不能模拟通用__builtin__。
上面的答案很有用,但我对它进行了一些扩展。
如果你想根据传递给open()的参数来设置文件对象的值(f in as f),这里有一种方法:
def save_arg_return_data(*args, **kwargs):
mm = MagicMock(spec=file)
mm.__enter__.return_value = do_something_with_data(*args, **kwargs)
return mm
m = MagicMock()
m.side_effect = save_arg_return_array_of_data
# if your open() call is in the file mymodule.animals
# use mymodule.animals as name_of_called_file
open_name = '%s.open' % name_of_called_file
with patch(open_name, m, create=True):
#do testing here
基本上,open()将返回一个对象,with将在该对象上调用__enter__()。
为了正确地模拟,必须mock open()返回一个模拟对象。然后,该模拟对象应该模拟对其进行的__enter__()调用(MagicMock将为我们完成此操作),以返回我们想要的模拟数据/文件对象(因此是mm.__enter__.return_value)。用上述方法对2个mock执行此操作允许我们捕获传递给open()的参数,并将它们传递给do_something_with_data方法。
我将整个模拟文件作为字符串传递给open(),我的do_something_with_data看起来像这样:
def do_something_with_data(*args, **kwargs):
return args[0].split("\n")
这将字符串转换为一个列表,这样你就可以像处理普通文件一样执行以下操作:
for line in file:
#do action
要将mock_open用于一个简单的文件read()(本页上已经给出的原始mock_open片段更适合于write):
my_text = "some text to return when read() is called on the file object"
mocked_open_function = mock.mock_open(read_data=my_text)
with mock.patch("__builtin__.open", mocked_open_function):
with open("any_string") as f:
print f.read()
注意,根据mock_open的文档,这是专门针对read()的,所以不会适用于常见的模式,例如for line in f。
使用python 2.6.6 / mock 1.0.1