Public Modules and Classes

Note: only public classes and methods interesting to the pyfakfs user are shown. Methods that mimic the behavior of standard Python functions are not listed - you may always use the standard functions.

Style note: most method names conform to the original Google style that does not match PEP-8. In the next version, we plan to change the API to conform to PEP-8 (maintaining upwards compatibility).

Fake filesystem module

A fake filesystem implementation for unit testing.

Includes:
  • FakeFile: Provides the appearance of a real file.
  • FakeDirectory: Provides the appearance of a real directory.
  • FakeFilesystem: Provides the appearance of a real directory hierarchy.
  • FakeOsModule: Uses FakeFilesystem to provide a fake os module replacement.
  • FakePathModule: Faked os.path module replacement.
  • FakeFileOpen: Faked file() and open() function replacements.
Usage:
>>> from pyfakefs import fake_filesystem
>>> filesystem = fake_filesystem.FakeFilesystem()
>>> os_module = fake_filesystem.FakeOsModule(filesystem)
>>> pathname = '/a/new/dir/new-file'

Create a new file object, creating parent directory objects as needed:

>>> os_module.path.exists(pathname)
False
>>> new_file = filesystem.CreateFile(pathname)

File objects can’t be overwritten:

>>> os_module.path.exists(pathname)
True
>>> try:
...   filesystem.CreateFile(pathname)
... except IOError as e:
...   assert e.errno == errno.EEXIST, 'unexpected errno: %d' % e.errno
...   assert e.strerror == 'File already exists in fake filesystem'

Remove a file object:

>>> filesystem.RemoveObject(pathname)
>>> os_module.path.exists(pathname)
False

Create a new file object at the previous path:

>>> beatles_file = filesystem.CreateFile(pathname,
...     contents='Dear Prudence\nWon\'t you come out to play?\n')
>>> os_module.path.exists(pathname)
True

Use the FakeFileOpen class to read fake file objects:

>>> file_module = fake_filesystem.FakeFileOpen(filesystem)
>>> for line in file_module(pathname):
...     print(line.rstrip())
...
Dear Prudence
Won't you come out to play?

File objects cannot be treated like directory objects:

>>> os_module.listdir(pathname)  
Traceback (most recent call last):
  File "fake_filesystem.py", line 291, in listdir
    raise OSError(errno.ENOTDIR,
OSError: [Errno 20] Fake os module: not a directory: '/a/new/dir/new-file'

The FakeOsModule can list fake directory objects:

>>> os_module.listdir(os_module.path.dirname(pathname))
['new-file']

The FakeOsModule also supports stat operations:

>>> import stat
>>> stat.S_ISREG(os_module.stat(pathname).st_mode)
True
>>> stat.S_ISDIR(os_module.stat(os_module.path.dirname(pathname)).st_mode)
True

Fake filesystem classes

class pyfakefs.fake_filesystem.FakeFilesystem(path_separator=’', total_size=None)

Provides the appearance of a real directory tree for unit testing.

path_separator

The path separator, corresponds to os.path.sep.

alternative_path_separator

Corresponds to os.path.altsep.

is_windows_fs

True in a Windows file system, False otherwise.

is_case_sensitive

True if a case-sensitive file system is assumed.

root

The root FakeDirectory entry of the file system.

cwd

The current working directory path.

umask

The umask used for newly created files, see os.umask.

init.

Parameters:
  • path_separator – optional substitute for os.path.sep
  • total_size – if not None, the total size in bytes of the
  • filesystem. (root) –
Example usage to emulate real file systems:
filesystem = FakeFilesystem(
alt_path_separator=’/’ if _is_windows else None)
AddMountPoint(path, total_size=None)

Add a new mount point for a filesystem device. The mount point gets a new unique device number.

Parameters:
  • path – The root path for the new mount path.
  • total_size – The new total size of the added filesystem device in bytes. Defaults to infinite size.
Returns:

The newly created mount point dict.

Raises:

OSError – if trying to mount an existing mount point again.

GetDiskUsage(path=None)

Return the total, used and free disk space in bytes as named tuple, or placeholder values simulating unlimited space if not set. Note: This matches the return value of shutil.disk_usage().

Parameters:path – The disk space is returned for the file system device where path resides. Defaults to the root path (e.g. ‘/’ on Unix systems).
SetDiskUsage(total_size, path=None)

Changes the total size of the file system, preserving the used space. Example usage: set the size of an auto-mounted Windows drive.

Parameters:
  • total_size – The new total size of the filesystem in bytes.
  • path – The disk space is changed for the file system device where path resides. Defaults to the root path (e.g. ‘/’ on Unix systems).
Raises:

IOError – if the new space is smaller than the used size.

ChangeDiskUsage(usage_change, file_path, st_dev)

Change the used disk space by the given amount.

Parameters:
  • usage_change – Number of bytes added to the used space. If negative, the used space will be decreased.
  • file_path – The path of the object needing the disk space.
  • st_dev – The device ID for the respective file system.
Raises:

IOError – if usage_change exceeds the free file system space

CreateDirectory(directory_path, perm_bits=511)

Create directory_path, and all the parent directories.

Helper method to set up your test faster.

Parameters:
  • directory_path – The full directory path to create.
  • perm_bits – The permission bits as set by chmod.
Returns:

The newly created FakeDirectory object.

Raises:

OSError – if the directory already exists.

CreateFile(file_path, st_mode=33206, contents=”, st_size=None, create_missing_dirs=True, apply_umask=False, encoding=None, errors=None)

Create file_path, including all the parent directories along the way.

This helper method can be used to set up tests more easily.

Parameters:
  • file_path – The path to the file to create.
  • st_mode – The stat constant representing the file type.
  • contents – The contents of the file.
  • st_size – The file size; only valid if contents not given.
  • create_missing_dirs – If True, auto create missing directories.
  • apply_umaskTrue if the current umask must be applied on st_mode.
  • encoding – Ff contents is a unicode string, the encoding used for serialization.
  • errors – The error mode used for encoding/decoding errors.
Returns:

The newly created FakeFile object.

Raises:
  • IOError – if the file already exists.
  • IOError – if the containing directory is required and missing.
add_real_file(file_path, read_only=True)

Create file_path, including all the parent directories along the way, for an existing real file. The contents of the real file are read only on demand.

Parameters:
  • file_path – Path to an existing file in the real file system
  • read_only – If True (the default), writing to the fake file raises an exception. Otherwise, writing to the file changes the fake file only.
Returns:

the newly created FakeFile object.

Raises:
  • OSError – if the file does not exist in the real file system.
  • IOError – if the file already exists in the fake file system.

Note

On MacOS and BSD, accessing the fake file’s contents will update both the real and fake files’ atime. (access time). In this particular case, add_real_file() violates the rule that pyfakefs must not modify the real file system. Further, Windows offers the option to enable atime, and older versions of Linux may also modify atime.

add_real_directory(dir_path, read_only=True, lazy_read=True)

Create a fake directory corresponding to the real directory at the specified path. Add entries in the fake directory corresponding to the entries in the real directory.

Parameters:
  • dir_path – The path to the existing directory.
  • read_only – If set, all files under the directory are treated as read-only, e.g. a write access raises an exception; otherwise, writing to the files changes the fake files only as usually.
  • lazy_read – If set (default), directory contents are only read when accessed, and only until the needed subdirectory level. Note: this means that the file system size is only updated at the time the directory contents are read; set this to False only if you are dependent on accurate file system size in your test
Returns:

the newly created FakeDirectory object.

Raises:
  • OSError – if the directory does not exist in the real file system.
  • IOError – if the directory already exists in the fake file system.
add_real_paths(path_list, read_only=True, lazy_dir_read=True)

This convenience method adds multiple files and/or directories from the real file system to the fake file system. See add_real_file() and add_real_directory().

Parameters:
  • path_list – List of file and directory paths in the real file system.
  • read_only – If set, all files and files under under the directories are treated as read-only, e.g. a write access raises an exception; otherwise, writing to the files changes the fake files only as usually.
  • lazy_dir_read – Uses lazy reading of directory contents if set (see add_real_directory)
Raises:
  • OSError – if any of the files and directories in the list does not exist in the real file system.
  • OSError – if any of the files and directories in the list already exists in the fake file system.
class pyfakefs.fake_filesystem.FakeFile(name, st_mode=33206, contents=None, filesystem=None, encoding=None, errors=None)

Provides the appearance of a real file.

Attributes currently faked out:
st_mode: user-specified, otherwise S_IFREG st_ctime: the time.time() timestamp of the file change time (updated each time a file’s attributes is modified). st_atime: the time.time() timestamp when the file was last accessed. st_mtime: the time.time() timestamp when the file was last modified. st_size: the size of the file st_nlink: the number of hard links to the file st_ino: the inode number - a unique number identifying the file st_dev: a unique number identifying the (fake) file system device the file belongs to

Other attributes needed by os.stat are assigned default value of None these include: st_uid, st_gid

init.

Parameters:
  • name – Name of the file/directory, without parent path information
  • st_mode – The stat.S_IF* constant representing the file type (i.e. stat.S_IFREG, stat.S_IFDIR)
  • contents – The contents of the filesystem object; should be a string or byte object for regular files, and a list of other FakeFile or FakeDirectory objects for FakeDirectory objects
  • filesystem – The fake filesystem where the file is created.
  • encoding – If contents is a unicode string, the encoding used for serialization.
  • errors – The error mode used for encoding/decoding errors.
contents

Return the contents as string with the original encoding.

IsLargeFile()

Return True if this file was initialized with size but no contents.

SetContents(contents, encoding=None)

Sets the file contents and size and increases the modification time.

Parameters:
  • contents – (str, bytes, unicode) new content of file.
  • encoding – (str) the encoding to be used for writing the contents if they are a unicode string. If not given, the locale preferred encoding is used.
Raises:

IOError – if the st_size is not a non-negative integer, or if st_size exceeds the available file system space.

GetSize()

Returns the size in bytes of the file contents.

GetPath()

Return the full path of the current object.

SetSize(st_size)

Resizes file content, padding with nulls if new size exceeds the old.

Parameters:st_size – The desired size for the file.
Raises:IOError – if the st_size arg is not a non-negative integer or if st_size exceeds the available file system space
class pyfakefs.fake_filesystem.FakeDirectory(name, perm_bits=511, filesystem=None)

Provides the appearance of a real directory.

init.

Parameters:
  • name – name of the file/directory, without parent path information
  • perm_bits – permission bits. defaults to 0o777.
  • filesystem – if set, the fake filesystem where the directory is created
contents

Return the list of contained directory entries.

GetEntry(pathname_name)

Retrieves the specified child file or directory entry.

Parameters:pathname_name – The basename of the child object to retrieve.
Returns:The fake file or directory object.
Raises:KeyError – if no child exists by the specified name.
RemoveEntry(pathname_name, recursive=True)

Removes the specified child file or directory.

Parameters:
  • pathname_name – Basename of the child object to remove.
  • recursive – If True (default), the entries in contained directories are deleted first. Used to propagate removal errors (e.g. permission problems) from contained entries.
Raises:
  • KeyError – if no child exists by the specified name.
  • OSError – if user lacks permission to delete the file, or (Windows only) the file is open.
GetSize()

Return the total size of all files contained in this directory tree.

Unittest module classes

class pyfakefs.fake_filesystem_unittest.TestCase(methodName=’runTest’, additional_skip_names=None, patch_path=True, special_names=None, modules_to_reload=None, use_dynamic_patch=False)

Test case class that automatically replaces file-system related modules by fake implementations.

Creates the test class instance and the stubber used to stub out file system related modules.

Parameters:
  • methodName – the name of the test method (same as unittest.TestCase)
  • additional_skip_names – names of modules inside of which no module replacement shall be performed, in addition to the names in attribute fake_filesystem_unittest.Patcher.SKIPNAMES.
  • patch_path

    if False, modules named ‘path’ will not be patched with the fake ‘os.path’ module. Set this to False when you need to import some other module named ‘path’, for example:

    from my_module import path
    

    Irrespective of patch_path, module ‘os.path’ is still correctly faked if imported the usual way using import os or import os.path.

  • special_names – A dictionary with module names as key and a dictionary as value, where the key is the original name of the module to be patched, and the value is the name as it is imported. This allows to patch modules where some of the file system modules are imported as another name (e.g. import os as _os).
  • modules_to_reload (experimental) – A list of modules that need to be reloaded to be patched dynamically; may be needed if the module imports file system modules under an alias Note: this is done independently of use_dynamic_patch Caution: this may not work with some Python versions or have unwanted side effects.
  • use_dynamic_patch (experimental) – If True, dynamic patching after setup is used (for example for modules loaded locally inside of functions). Caution: this may not work with some Python versions or have unwanted side effects.

If you specify arguments additional_skip_names or patch_path here and you have DocTests, consider also specifying the same arguments to load_doctests().

Example usage in derived test classes:

class MyTestCase(fake_filesystem_unittest.TestCase):
    def __init__(self, methodName='runTest'):
        super(MyTestCase, self).__init__(
            methodName=methodName, additional_skip_names=['posixpath'])


class AnotherTestCase(fake_filesystem_unittest.TestCase):
    def __init__(self, methodName='runTest'):
        # allow patching a module that imports `os` as `my_os`
        special_names = {'amodule': {'os': 'my_os'}}
        super(MyTestCase, self).__init__(
            methodName=methodName, special_names=special_names)
setUpPyfakefs()

Bind the file-related modules to the pyfakefs fake file system instead of the real file system. Also bind the fake open() function, and on Python 2, the file() function.

Invoke this at the beginning of the setUp() method in your unit test class.

class pyfakefs.fake_filesystem_unittest.Patcher(additional_skip_names=None, patch_path=True, special_names=None)

Instantiate a stub creator to bind and un-bind the file-related modules to the pyfakefs fake modules.

The arguments are explained in TestCase.

Patcher is used in TestCase. Patcher also works as a context manager for PyTest:

with Patcher():
    doStuff()

For a description of the arguments, see TestCase.__init__

setUp(doctester=None)

Bind the file-related modules to the pyfakefs fake modules real ones. Also bind the fake file() and open() functions.

tearDown(doctester=None)

Clear the fake filesystem bindings created by setUp().

Faked module classes

class pyfakefs.fake_filesystem.FakeOsModule(filesystem, os_path_module=None)

Uses FakeFilesystem to provide a fake os module replacement.

Do not create os.path separately from os, as there is a necessary circular dependency between os and os.path to replicate the behavior of the standard Python modules. What you want to do is to just let FakeOsModule take care of os.path setup itself.

# You always want to do this. filesystem = fake_filesystem.FakeFilesystem() my_os_module = fake_filesystem.FakeOsModule(filesystem)

Also exposes self.path (to fake os.path).

Parameters:
  • filesystem – FakeFilesystem used to provide file system information
  • os_path_module – (deprecated) Optional FakePathModule instance
class pyfakefs.fake_filesystem.FakePathModule(filesystem, os_module=None)

Faked os.path module replacement.

FakePathModule should only be instantiated by FakeOsModule. See the FakeOsModule docstring for details.

Init.

Parameters:
  • filesystem – FakeFilesystem used to provide file system information
  • os_module – (deprecated) FakeOsModule to assign to self.os
class pyfakefs.fake_filesystem.FakeFileOpen(filesystem, delete_on_close=False, use_io=False, raw_io=False)

Faked file() and open() function replacements.

Returns FakeFile objects in a FakeFilesystem in place of the file() or open() function.

init.

Parameters:
  • filesystem – FakeFilesystem used to provide file system information
  • delete_on_close – optional boolean, deletes file on close()
  • use_io – if True, the io.open() version is used (ignored for Python 3, where io.open() is an alias to open() )
class pyfakefs.fake_filesystem.FakeIoModule(filesystem)

Uses FakeFilesystem to provide a fake io module replacement.

Currently only used to wrap io.open() which is an alias to open().

You need a fake_filesystem to use this: filesystem = fake_filesystem.FakeFilesystem() my_io_module = fake_filesystem.FakeIoModule(filesystem)

Parameters:filesystem – FakeFilesystem used to provide file system information.
class pyfakefs.fake_filesystem_shutil.FakeShutilModule(filesystem)

Uses a FakeFilesystem to provide a fake replacement for shutil module.

Construct fake shutil module using the fake filesystem.

Parameters:filesystem – FakeFilesystem used to provide file system information
class pyfakefs.fake_pathlib.FakePathlibModule(filesystem)

Uses FakeFilesystem to provide a fake pathlib module replacement.

You need a fake_filesystem to use this: filesystem = fake_filesystem.FakeFilesystem() fake_pathlib_module = fake_filesystem.FakePathlibModule(filesystem)

Initializes the module with the given filesystem.

Parameters:filesystem – FakeFilesystem used to provide file system information