在Python中模拟内置的read()函数,因此抛出异常

时间:2016-02-11 15:02:40

标签: python unit-testing mocking python-2.5

我正在尝试测试类的错误处理,我需要模拟read()引发MemoryError。这是一个简化的例子。

import mock

def memory_error_read():
    raise MemoryError

def read_file_by_filename(filename):
    try:
        handle = open(filename)
        content = handle.read()
    except MemoryError:
        raise Exception("%s is too big" % self.filename)
    finally:
        handle.close()

    return content

@mock.patch("__builtin__.file.read", memory_error_read)
def testfunc():
    try:
        read_file_by_filename("/etc/passwd")
    except Exception, e:
        return
    print("Should have received exception")

testfunc()

当我运行时,我得到以下追溯。

# ./read_filename.py 
Traceback (most recent call last):
  File "./read_filename.py", line 34, in <module>
    testfunc()
  File "build/bdist.linux-i686/egg/mock.py", line 1214, in patched
  File "build/bdist.linux-i686/egg/mock.py", line 1379, in __exit__
TypeError: can't set attributes of built-in/extension type 'file'

看来我无法修补内置读取功能。有办法欺骗它吗? 可以做我想做的事吗?

ANSWER

以下是基于Ben的建议的更新代码。

from __future__ import with_statement

...

def test_func():
    with mock.patch("__builtin__.open", new_callable=mock.mock_open) as mo:
        mock_file = mo.return_value
        mock_file.read.side_effect = MemoryError

        try:
            read_file_by_filename("/etc/passwd")
        except Exception, e:
            if "is too big" in str(e):
                return
            else:
                raise

        print("Should have caught an exception")

1 个答案:

答案 0 :(得分:3)

Have you looked at mock_open?

You should be able to have that return a mock object that has an Exception raising side effect on read().