如何测试以下代码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()
补丁builtins.open
和使用mock_open
,这是mock
框架的一部分。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()
's result 作为new=
参数patch
可能会有点奇怪。相反,使用patch
'new_callable=
参数并记住每个patch
不使用的额外参数都将传递给new_callable
函数,如patch
文档中所述:
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
会将模拟对象作为参数传递给您的测试函数。
您需要修补__builtin__.open
而不是builtins.open
并且mock
不是 的一部分unittest
,您需要pip install
单独导入它:
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")
这样做的方法在 mock 0.7.0 中发生了变化,最终支持模拟 python 协议方法(魔术方法),特别是使用 MagicMock:
http://www.voidspace.org.uk/python/mock/magicmock.html
作为上下文管理器模拟打开的示例(来自模拟文档中的示例页面):
>>> open_name = '%s.open' % __name__
>>> with patch(open_name, create=True) as mock_open:
... mock_open.return_value = MagicMock(spec=file)
...
... with open('/some/path', 'w') as f:
... f.write('something')
...
<mock.Mock object at 0x...>
>>> file_handle = mock_open.return_value.__enter__.return_value
>>> file_handle.write.assert_called_with('something')
使用最新版本的 mock,您可以使用真正有用的mock_open助手:
mock_open(mock=None,read_data=None)
一个辅助函数创建一个 mock 来代替 open 的使用。它适用于直接调用或用作上下文管理器的打开。
mock 参数是要配置的模拟对象。如果 None (默认值),那么将为您创建一个 MagicMock,API 仅限于标准文件句柄上可用的方法或属性。
read_data 是要返回的文件句柄的读取方法的字符串。默认情况下这是一个空字符串。
>>> from mock import mock_open, patch
>>> m = mock_open()
>>> with patch('{}.open'.format(__name__), m, create=True):
... with open('foo', 'w') as h:
... h.write('some stuff')
>>> m.assert_called_once_with('foo', 'w')
>>> handle = m()
>>> handle.write.assert_called_once_with('some stuff')
要将mock_open用于一个简单的文件(此页面上已经给出read()
的原始 mock_open 片段更适合写入):
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
最佳答案很有用,但我对其进行了扩展。
如果要根据传递给的参数设置文件对象的值( f
in ),这是一种方法:as f
open()
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__()
该对象。
为了正确地模拟,我们必须模拟open()
返回一个模拟对象。然后,该模拟对象应该模拟__enter__()
对它的调用(MagicMock
将为我们执行此操作)以返回我们想要的模拟数据/文件对象(因此mm.__enter__.return_value
)。以上述方式使用 2 个模拟来执行此操作允许我们捕获传递给的参数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
我可能玩游戏有点晚了,但这在调用open
另一个模块而无需创建新文件时对我有用。
测试.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")]
我的对象.py
class MyObj(object):
def save(self, filename):
with open(filename, "wb") as f:
f.write("sample text")
open
通过将模块内的函数修补__builtin__
到 my mock_open()
,我可以模拟写入文件而不创建文件。
注意:如果您正在使用一个使用 cython 的模块,或者您的程序以任何方式依赖于 cython,则需要通过在文件顶部包含来导入cython 的__builtin__
模块。如果您使用的是 cython,import __builtin__
您将无法模拟通用。__builtin__
如果您不再需要任何文件,则可以装饰测试方法:
@patch('builtins.open', mock_open(read_data="data"))
def test_testme():
result = testeme()
assert result == "data"
这适用于读取 json 配置的补丁。
class ObjectUnderTest:
def __init__(self, filename: str):
with open(filename, 'r') as f:
dict_content = json.load(f)
模拟对象是 open() 函数返回的 io.TextIOWrapper 对象
@patch("<src.where.object.is.used>.open",
return_value=io.TextIOWrapper(io.BufferedReader(io.BytesIO(b'{"test_key": "test_value"}'))))
def test_object_function_under_test(self, mocker):
源自 github 片段,用于修补 python 中的读写功能。
源链接在这里
import configparser
import pytest
simpleconfig = """[section]\nkey = value\n\n"""
def test_monkeypatch_open_read(mockopen):
filename = 'somefile.txt'
mockopen.write(filename, simpleconfig)
parser = configparser.ConfigParser()
parser.read(filename)
assert parser.sections() == ['section']
def test_monkeypatch_open_write(mockopen):
parser = configparser.ConfigParser()
parser.add_section('section')
parser.set('section', 'key', 'value')
filename = 'somefile.txt'
parser.write(open(filename, 'wb'))
assert mockopen.read(filename) == simpleconfig
带有断言的简单@patch
如果你想使用@patch。open() 在处理程序内部被调用并被读取。
@patch("builtins.open", new_callable=mock_open, read_data="data")
def test_lambda_handler(self, mock_open_file):
lambda_handler(event, {})