Python 模拟打开并检查关闭

Python mocking open and check for close

我正在尝试模拟打开并想检查是否至少调用了一次关闭

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

这是我到目前为止的工作测试代码,现在我想另外检查是否调用了我尝试添加的关闭方法

mock_file.close.assert_called_once()

mock_file.fake_file.close.assert_called_once()

但两者都不会捕捉到方法调用。

简而言之:如果 open 的 return 值不是模拟对象,则无法跟踪正在使用 assert_called_once 调用的函数。因此,我们可以将 return 值设为 StringIO,而不是将其设为 MagicMock,这将像文件句柄一样。

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()