我正在尝试模拟打开并想检查关闭是否至少被调用一次
class MyObject():
def __init__(self,path):
fp = open(path)
self.file_list = []
for line in fp:
self.file_list.append(line.strip())
fp.close()
def testsimpleFile():
fake_file = io.StringIO("data.csv\ndata2.csv")
with patch("builtins.open",return_value=fake_file,create=True) as mock_file:
f = MyObject("path/to/open/test.f")
mock_file.assert_called_once_with("/path/to/open/test.f")
golden_list = ["data.csv","data2.csv"]
assert f.file_list == golden_list
这是我到目前为止的工作测试代码,现在我想另外检查是否调用了我尝试添加的 close 方法
mock_file.close.assert_used_once()
和
mock_file.fake_file.close.assert_called_once()
但是两者都不会捕获方法调用。
最佳答案
缺点是:如果 open
的返回值不是模拟对象,则无法跟踪使用 assert_used_once
调用该函数。因此,我们可以将返回值设置为像文件句柄一样的MagicMock
,而不是将返回值设置为StringIO
。
import io
from unittest.mock import patch, MagicMock
class MyObject():
def __init__(self,path):
fp = open(path)
self.file_list = []
for line in fp:
self.file_list.append(line.strip())
fp.close()
def testsimpleFile():
fake_file = MagicMock()
fake_file.__iter__.return_value = ["data.csv", "data2.csv"]
with patch("builtins.open", return_value=fake_file, create=True) as mock_file:
f = MyObject("/path/to/open/test.f")
mock_file.assert_called_once_with("/path/to/open/test.f")
golden_list = ["data.csv", "data2.csv"]
assert f.file_list == golden_list
fake_file.close.assert_called_once()
关于Python 模拟打开并检查关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52723672/