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

    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 =
        self.assertEqual(data, 'magic')

Currently supported functions:


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

Restore the original builtin functions.

Indices and tables

Table Of Contents

Next topic

os.path and glob Implementations

This Page