在Python中如何只模拟文件写入而不模拟文件读取? [英] in python how to mock only the file write but not the file read?

查看:64
本文介绍了在Python中如何只模拟文件写入而不模拟文件读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试其中一个功能

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

将无法读取数据.

谢谢.

推荐答案

我找到了以下解决方案:

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)

这篇关于在Python中如何只模拟文件写入而不模拟文件读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆