【问题标题】:in python how to mock only the file write but not the file read?在python中如何只模拟文件写入而不模拟文件读取?
【发布时间】:2017-08-10 14:58:16
【问题描述】:

我正在测试一个函数,其中两个

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

被使用。但我只想模拟写部分。有可能这样做吗?还是应该使用其他策略来测试这样的功能?

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

将无法读取数据。

提前致谢。

【问题讨论】:

标签: python unit-testing testing file-io mocking


【解决方案1】:

我找到了以下解决方案:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-13
    • 1970-01-01
    • 2012-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多