在python中,如何模拟只写文件而不模拟读取文件?

2024-04-25 07:18:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在测试一个函数

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

被使用。但我只想嘲笑写作部分。有可能吗?或者应该使用其他策略来测试这种功能?在

^{pr2}$

无法读取数据。在

提前谢谢。在


Tags: 函数功能inputoutputfoodefaswith
1条回答
网友
1楼 · 发布于 2024-04-25 07:18:48

我找到了以下解决方案:

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)

相关问题 更多 >