os.path
and glob
Implementations¶
mockfs: A simple mock filesystem for unit tests.
- class mockfs.mfs.MockFS(entries=None)¶
MockFS implementation object
Provides stubs for functions in
os
,os.path
, andglob
.- 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.
- islink(path)¶
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.
- class mockfs.mfs.StorageBackend(mfs)¶
- CheckForFile(filename)¶
- DeleteFile(filename)¶
- LoadFile(filename)¶
- SaveFile(filename, data)¶
- mockfs.mfs.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.mfs.restore_builtins()¶
Restore the original builtin functions.
Utility Functions¶
- mockfs.util.build_nested_dict(entries)¶
Convert a flat dict of paths to a nested dict
- Parameters:
entries (dict) – Path to entry dictionary
e.g. {‘/unix/path’: ‘content’, ‘/unix/dir’: {},}
- mockfs.util.build_nested_dir_dict(dirpath)¶
Build a nested dict of dicts from a directory path
- Parameters:
dirpath (str) – Directory path
- mockfs.util.is_dir(entry)¶
- mockfs.util.is_file(value)¶
Is value a file? Equivalent to checking for strings
- mockfs.util.is_string(value)¶
Is value a string?
- mockfs.util.merge_dicts(src, dst)¶
Merge entries from ‘src’ into ‘dst’.
- Parameters:
src – source dictionary
dst – destination dictionary
- mockfs.util.sanitize(path)¶
Clean up path arguments for use with MockFS
MockFS isn’t happy with trailing slashes since it uses a dict to simulate the file system.
File Storage and IO¶
- class mockfs.storage.backend¶
Example backend.
- static CheckForFile(filename)¶
- static DeleteFile(filename)¶
- static LoadFile(filename)¶
- static SaveFile(filename, data)¶
- class mockfs.storage.file(name[, mode])¶
Open a file. The mode can be ‘r’, ‘w’ or ‘a’ for reading (default), writing or appending. The file will be created if it doesn’t exist when opened for writing or appending; it will be truncated when opened for writing. Add a ‘b’ to the mode for binary files. Add a ‘+’ to the mode to allow simultaneous reading and writing. The preferred way to open a file is with the builtin open() function.
- close()¶
Returns None or (perhaps) an integer. Close the file.
Sets data attribute .closed to True. A closed file cannot be used for further I/O operations. close() may be called more than once without error. Some kinds of file objects (for example, opened by popen()) may return an exit status upon closing.
- property closed¶
True if the file is closed
- property encoding¶
file encoding
- property errors¶
Unicode error handler
- fileno()¶
file descriptor
This is needed for lower-level file interfaces, such os.read().
- flush()¶
Flush the internal I/O buffer.
- isatty()¶
Is the file connected to a tty device? mockfs always returns False.
- property mode¶
file mode, one of r(+)(b), w(+)(b) or a(+)(b)
- property name¶
file name
- property newlines¶
end-of-line convention used in this file
- next()¶
Return the next value, or raise StopIteration.
- read(size=DEFAULT)¶
Read at most size bytes, returned as a string.
If the size argument is negative or omitted, read until EOF is reached. Notice that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given.
- readline(size=DEFAULT)¶
Return the next line from the file, as a string.
Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then). Return an empty string at EOF.
- readlines(size=DEFAULT)¶
Return a list of strings, each a line from the file.
Call readline() repeatedly and return a list of the lines so read. The optional size argument, if given, is an approximate bound on the total number of bytes in the lines returned.
- seek(position, whence=0)¶
Move to new file position.
Argument offset is a byte count. Optional argument whence defaults to 0 (offset from start of file, offset should be >= 0); other values are 1 (move relative to current position, positive or negative), and 2 (move relative to end of file, usually negative, although many platforms allow seeking beyond the end of a file). If the file is opened in text mode, only offsets returned by tell() are legal. Use of other offsets causes undefined behavior. Note that not all file objects are seekable.
- property softspace¶
flag indicating that a space needs to be printed; used by print
- tell()¶
Return the current file position, an integer (may be a long integer).
- truncate(size=DEFAULT)¶
Truncate the file to at most size bytes.
Size defaults to the current file position, as returned by tell().
- write(data)¶
Write data to the file.
Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written.
- writelines(sequence)¶
Write the strings to the file.
Note that newlines are not added. The sequence can be any iterable object producing strings. This is equivalent to calling write() for each string.
- xreadlines()¶
Returns self for backward compatibility.
File objects now include the performance optimizations previously implemented in the xreadlines module.
- mockfs.storage.get_new_fileno()¶
- mockfs.storage.open(name, mode='r', encoding=None, errors=None)¶
Open a file using the file() type, returns a file object.
This is the preferred way to open a file.
- mockfs.storage.replace_builtins()¶
replace file and open in the builtin module
- mockfs.storage.restore_builtins()¶
restore the original file and open to the builtin module