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


def test_context_manager():
    """The MockFS class can be used as context manager"""
    with mockfs.MockFS(entries={'/tmp/does/not/exist': 'mockfs'}) as mfs:
        assert os.path.exists('/tmp/does/not/exist')
        with open('/tmp/does/not/exist', 'r', encoding='utf-8') as fh:
            content = fh.read()
        assert content == 'mockfs'
        mfs.add_entries({'/tmp/does/not/exist-2': 'mockfs'})
        assert os.path.exists('/tmp/does/not/exist-2')
    # Context manager scope ends: everything is back to normal now.
    assert not os.path.exists('/tmp/does/not/exist')
    assert not os.path.exists('/tmp/does/not/exist-2')


class ExampleTestCase(unittest.TestCase):
    """The mockfs module can be used in setUp() and tearDown()"""
    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:

Developer Documentation

class mockfs.MockFS(entries=None)

Bases: object

MockFS implementation object

Provides stubs for functions in os, os.path, and glob.

abspath(path)
add_entries(entries)

Add new entries to mockfs.

copytree(src, dst)

Copy a directory subtree

Implements the shutil.copytree() interface.

exists(path)

Return True if path exists

Implements the os.path.exists() interface.

getsize(path)

Return the size of a file, reported by os.stat().

glob(pattern)

Implementation of glob.glob()

isdir(path)

Return True if path is a directory

Implements the os.path.isdir() interface.

isfile(path)

Return True if path is a file

Implements the os.path.isfile() interface.

Return True if path is a symlink

Note

Currently hard-wired to return False

listdir(path)

Return the directory contents of ‘path’

Implements the os.listdir() interface. :param path: filesystem path

makedirs(path)

Create directory entries for a path

Raise OSError if the path already exists.

read(path)
remove(path)

Remove the entry for a file path

Implements the os.remove() interface.

rmdir(fspath)

Remove the entry for a directory path

Implements the os.rmdir() interface.

rmtree(path, ignore_errors=False, onerror=None)

Recursively delete a directory tree.

If ignore_errors is set, errors are ignored; otherwise, if onerror is set, it is called to handle the error with arguments (func, path, exc_info) where func is os.listdir, os.remove, or os.rmdir; path is the argument to that function that caused it to fail; and exc_info is a tuple returned by sys.exc_info(). If ignore_errors is false and onerror is None, an exception is raised.

walk(path)

Walk a filesystem path

Implements the os.walk() interface.

mockfs.replace_builtins(entries=None, context=None)

Replace builtin functions with mockfs.

Parameters:

entries – Dictionary mapping paths to content

Returns:

Newly installed mockfs.mfs.MockFS instance.

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