mockfs – A simple mock filesystem for unit tests

mockfs makes it possible to test filesystem-dependent code by replacing functions from the os and glob modules.

Example Unit Test

import os
import unittest

import mockfs

class ExampleTestCase(unittest.TestCase):
    def setUp(self):
        self.mfs = mockfs.replace_builtins()
        self.mfs.add_entries({'/usr/bin/mockfs-magic': 'magic'})

    def tearDown(self):
        mockfs.restore_builtins()

    def test_using_os_path(self):
        self.assertEqual(os.listdir('/usr/bin'), ['mockfs-magic'])

    def test_using_open(self):
        fh = open('/usr/bin/mockfs-magic')
        content = fh.read()
        fh.close()
        self.assertEqual(data, 'magic')

Currently supported functions:

mockfs.replace_builtins(entries=None)

Replace builtin functions with mockfs.

Parameters:entries – Dictionary mapping paths to content
Returns:Newly installed mockfs.MockFS handler
>>> import os
>>> import mockfs
>>> fs = mockfs.replace_builtins()
>>> fs.add_entries({
...         '/bin/sh': 'contents',
...         '/bin/ls': 'contents',
... })
>>> assert(os.listdir('/bin') == ['ls', 'sh'])
>>> mockfs.restore_builtins()
mockfs.restore_builtins()

Restore the original builtin functions.

Indices and tables

Table Of Contents

Next topic

os.path and glob Implementations

This Page