Search code examples
pythonunit-testingmockingpython-2.5

Mocking builtin read() function in Python so it throws Exception


I am trying to test the error handling of a class and I need to simulate read() raising a MemoryError. This is a simplified example.

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

When I run this I get the following traceback.

# ./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'

It appears that I can't patch the builtin read function. Is there a way to trick it? Is it possible to do what I want?

ANSWER

Here's the updated code based on Ben's suggestion below.

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

Solution

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