Tech and travel

Stubbing out open() in Python

2012-05-15

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

<pre lang='python'>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.

Copyright (c) 2024 Michel Hollands