def setup(entries=None): """ Replace builtin functions with mockfs. :param entries: Dictionary mapping paths to content :rtype MockFS: Newly installed :class:`mockfs.MockFS` handler Example:: import os import mockfs fs = mockfs.setup() fs.add_entries({ '/bin/sh': 'contents', '/bin/ls': 'contents', ]) assert(os.listdir('/bin') == ['ls', 'sh']) mockfs.teardown() """ mfs = MockFS() if entries is not None: mfs.add_entries(entries) # Install functions glob.glob = mfs.glob os.chdir = mfs.cwd.chdir os.getcwd = mfs.cwd.getcwd os.getcwdu = mfs.cwd.getcwdu os.listdir = mfs.listdir os.makedirs = mfs.makedirs os.path.abspath = mfs.abspath os.path.exists = mfs.exists os.path.lexists = mfs.lexists os.path.getsize = mfs.getsize os.path.islink = mfs.islink os.path.isdir = mfs.isdir os.path.isfile = mfs.isfile os.listdir = mfs.listdir os.mkdir = mfs.mkdir os.makedirs = mfs.makedirs os.readlink = mfs.readlink os.remove = mfs.remove os.rmdir = mfs.rmdir os.symlink = mfs.symlink os.unlink = mfs.remove os.walk = mfs.walk glob.glob = mfs.glob shutil.rmtree = mfs.rmtree storage.backend = mfs.backend storage.replace_builtins() return mfs
def replace_builtins(entries=None): """ Replace builtin functions with mockfs. :param entries: Dictionary mapping paths to content :returns: Newly installed :class:`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() """ mfs = MockFS() if entries is not None: mfs.add_entries(entries) # Install functions glob.glob = mfs.glob os.chdir = mfs.cwd.chdir os.getcwd = mfs.cwd.getcwd os.getcwdu = mfs.cwd.getcwdu os.listdir = mfs.listdir os.makedirs = mfs.makedirs os.path.abspath = mfs.abspath os.path.exists = mfs.exists os.path.getsize = mfs.getsize os.path.islink = mfs.islink os.path.isdir = mfs.isdir os.path.isfile = mfs.isfile os.remove = mfs.remove os.rmdir = mfs.rmdir os.unlink = mfs.remove os.walk = mfs.walk shutil.rmtree = mfs.rmtree storage.backend = mfs.backend storage.replace_builtins() return mfs