Python模拟打开并检查关闭

时间:2018-10-09 14:39:57

标签: python mocking python-unittest python-unittest.mock

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

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

mock_file.fake_file.close.assert_called_once()

但两者都无法捕获方法调用。

1 个答案:

答案 0 :(得分:1)

其简短之处在于:如果Create [Table2] like [Table1]; Alter table [Table2] disable keys; Insert into [Table2] select * from [Table1]; Alter table [Table2] enable keys; 的返回值不是模拟对象,则无法跟踪使用assert_called_once调用的函数。因此,除了将返回值设为open之外,我们可以将其设为像文件句柄一样的StringIO

MagicMock
相关问题