Skip to content

Stubbing out open() in Python

Here’s an example that stubs out the open() function in Python using the mock library.

from StringIO import StringIO

from mock import patch

# We are testing these 2 functions :

def read_sys():
    f = open('/sys/something')
    data = f.readline().strip()
    f.close()
    return data

def read_dev():
    f = open('/dev/something')
    data = f.readline().strip()
    f.close()
    return data

# Test helper function

def side_effect_function(path):
    if path.startswith('/sys/something'):
        return StringIO('abcd')
    if path.startswith('/dev/something'):
        return StringIO('zyxw')

# Actual test, this would be in a testcase for a real unit test

with patch('__builtin__.open') as mocked_open:
     mocked_open.side_effect = side_effect_function

     data = read_sys()
     assert data == 'abcd'
     data = read_dev()
     assert data == 'zyxw'

With this kind of mock object you don’t have to create temporary files just for the test.

Uruguay

Here are some photos from a trip to Urugyay :



Uruguay

Correlation or causation

Statistics are easy :

http://www.businessweek.com/magazine/correlation-or-causation-12012011-gfx.html

Yorkshire Sculpture Park

Here are some photos from the Yorkshire Sculpture Park :



YSP