Mocking file objects or iterables in python

醉酒当歌 提交于 2019-12-01 02:47:49

You're looking for a MagicMock. This supports iteration.

In mock 0.80beta4, patch returns a MagicMock. So this simple example works:

import mock

def foo():
    for line in open('myfile'):
        print line

@mock.patch('__builtin__.open')
def test_foo(open_mock):
    foo()
    assert open_mock.called

If you're running mock 0.7.x (It looks like you are), I don't think you can accomplish this with patch alone. You'll need to create the mock separately, then pass it into patch:

import mock

def foo():
    for line in open('myfile'):
        print line

def test_foo():
    open_mock = mock.MagicMock()
    with mock.patch('__builtin__.open', open_mock):
        foo()
        assert open_mock.called

Note - I've run these with py.test, however, these same approaches will work with unittest as well.

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