如何在Python中存根上下文管理器close方法?

时间:2015-10-12 00:50:22

标签: python python-3.x mocking python-unittest contextmanager

我需要做一些使用内置模拟模块不能正常工作的操作。 然后我决定自己模仿,使用:

import builtins
import io
from unittest import mock
import my_module

builtins.open = mock.Mock()
builtins.open.return_value = io.StringIO()
builtins.open.return_value.__exit__ = lambda a, b, c, d: None 
my_module.f('foo')
builtins.open.return_value.seek(0)
txt = builtins.open.return_value.read()
print(txt)

而在my_module.py中:

def f(fname):
   with open(fname) as handle:
       g(handle)

def g(fhandle):
    fhandle.write('bar')

使用这种方法,我得到一个ValueError,该消息是"关闭文件"的I / O操作。我希望lambda可以用来存根退出方法,为什么它不起作用?我该如何存根?

1 个答案:

答案 0 :(得分:0)

你有没有尝试使用模拟" mock_open"在任何情况下?这是我前一段时间使用的一些代码,我认为应该可行。如果这有助于您,请告诉我们:

@mock.patch('__builtin__.open', new_callable=mock_open())
def test_foo(self, m_open):
    self.foo()

    m_open.assert_called_once_with("something", 'w')
    m_open().__enter__().write.assert_called_once_with("stuff")

以下是mock_open

的更多文档