in python how to mock only the file write but not the file read?

泪湿孤枕 提交于 2021-02-08 10:05:10

问题


I am testing a function in which both

def foo():
    with open('input.dat', 'r') as f:
        ....
    with open('output.dat', 'w') as f:
        ....

are used. But I only want to mock the write part. Is it possible to do that? Or some other strategy should be used for testing such a function?

with patch('__builtin__.open') as m:
    foo()

would fail to read the data.

Thanks in advance.


回答1:


I found the following solution:

from mock import patch, mock_open

with open('ref.dat') as f:
    ref_output = f.read()
with open('input.dat') as f:
    input = f.read()

with patch('__builtin__.open', mock_open(read_data=input)) as m:
    foo()
    m.assert_called_with('output.dat', 'w')
    m().write.assert_called_once_with(ref_output)


来源:https://stackoverflow.com/questions/45617202/in-python-how-to-mock-only-the-file-write-but-not-the-file-read

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!