code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
if self._context is None:
self._context = {}
res = super(RoomReservationSummary, self).default_get(fields)
# Added default datetime as today and date to as today + 30.
from_dt = datetime.today()
dt_from = from_dt.strftime(dt)
to_dt = from_dt + relativedelta(days=30)
dt_to = to_dt.strftime(dt)
res.update({'date_from': dt_from, 'date_to': dt_to})
if not self.date_from and self.date_to:
date_today = datetime.datetime.today()
first_day = datetime.datetime(date_today.year,
date_today.month, 1, 0, 0, 0)
first_temp_day = first_day + relativedelta(months=1)
last_temp_day = first_temp_day - relativedelta(days=1)
last_day = datetime.datetime(last_temp_day.year,
last_temp_day.month,
last_temp_day.day, 23, 59, 59)
date_froms = first_day.strftime(dt)
date_ends = last_day.strftime(dt)
res.update({'date_from': date_froms, 'date_to': date_ends})
return res | def default_get(self, fields) | To get default values for the object.
@param self: The object pointer.
@param fields: List of fields for which we want default values
@return: A dictionary which of fields with values. | 2.678645 | 2.754668 | 0.972402 |
'''
When you change checkout or checkin it will check whether
Checkout date should be greater than Checkin date
and update dummy field
-----------------------------------------------------------
@param self: object pointer
@return: raise warning depending on the validation
'''
if self.check_out and self.check_in:
if self.check_out < self.check_in:
raise ValidationError(_('Checkout date should be greater \
than Checkin date.')) | def on_change_check_out(self) | When you change checkout or checkin it will check whether
Checkout date should be greater than Checkin date
and update dummy field
-----------------------------------------------------------
@param self: object pointer
@return: raise warning depending on the validation | 9.361034 | 2.074994 | 4.511356 |
if self._context is None:
self._context = {}
res = super(QuickRoomReservation, self).default_get(fields)
if self._context:
keys = self._context.keys()
if 'date' in keys:
res.update({'check_in': self._context['date']})
if 'room_id' in keys:
roomid = self._context['room_id']
res.update({'room_id': int(roomid)})
return res | def default_get(self, fields) | To get default values for the object.
@param self: The object pointer.
@param fields: List of fields for which we want default values
@return: A dictionary which of fields with values. | 3.026831 | 3.302015 | 0.916662 |
hotel_res_obj = self.env['hotel.reservation']
for res in self:
rec = (hotel_res_obj.create
({'partner_id': res.partner_id.id,
'partner_invoice_id': res.partner_invoice_id.id,
'partner_order_id': res.partner_order_id.id,
'partner_shipping_id': res.partner_shipping_id.id,
'checkin': res.check_in,
'checkout': res.check_out,
'warehouse_id': res.warehouse_id.id,
'pricelist_id': res.pricelist_id.id,
'adults': res.adults,
'reservation_line': [(0, 0,
{'reserve': [(6, 0,
[res.room_id.id])],
'name': (res.room_id and
res.room_id.name or '')
})]
}))
return rec | def room_reserve(self) | This method create a new record for hotel.reservation
-----------------------------------------------------
@param self: The object pointer
@return: new record set for hotel reservation. | 2.805351 | 2.740473 | 1.023674 |
dirs = []
files = []
for entry in filesystem.listdir(root):
if filesystem.isdir(filesystem.joinpaths(root, entry)):
dirs.append(entry)
else:
files.append(entry)
return root, dirs, files | def _classify_directory_contents(filesystem, root) | Classify contents of a directory as files/directories.
Args:
filesystem: The fake filesystem used for implementation
root: (str) Directory to examine.
Returns:
(tuple) A tuple consisting of three values: the directory examined,
a list containing all of the directory entries, and a list
containing all of the non-directory entries.
(This is the same format as returned by the `os.walk` generator.)
Raises:
Nothing on its own, but be ready to catch exceptions generated by
underlying mechanisms like `os.listdir`. | 2.454451 | 2.868496 | 0.855658 |
def do_walk(top_dir, top_most=False):
top_dir = filesystem.normpath(top_dir)
if not top_most and not followlinks and filesystem.islink(top_dir):
return
try:
top_contents = _classify_directory_contents(filesystem, top_dir)
except OSError as exc:
top_contents = None
if onerror is not None:
onerror(exc)
if top_contents is not None:
if topdown:
yield top_contents
for directory in top_contents[1]:
if not followlinks and filesystem.islink(directory):
continue
for contents in do_walk(filesystem.joinpaths(top_dir,
directory)):
yield contents
if not topdown:
yield top_contents
return do_walk(top, top_most=True) | def walk(filesystem, top, topdown=True, onerror=None, followlinks=False) | Perform an os.walk operation over the fake filesystem.
Args:
filesystem: The fake filesystem used for implementation
top: The root directory from which to begin walk.
topdown: Determines whether to return the tuples with the root as
the first entry (`True`) or as the last, after all the child
directory tuples (`False`).
onerror: If not `None`, function which will be called to handle the
`os.error` instance provided when `os.listdir()` fails.
followlinks: If `True`, symbolic links are followed.
Yields:
(path, directories, nondirectories) for top and each of its
subdirectories. See the documentation for the builtin os module
for further details. | 2.986758 | 2.99848 | 0.996091 |
if self._inode is None:
self.stat(follow_symlinks=False)
return self._inode | def inode(self) | Return the inode number of the entry. | 4.470258 | 3.819265 | 1.17045 |
if follow_symlinks:
if self._statresult_symlink is None:
file_object = self._filesystem.resolve(self.path)
if self._filesystem.is_windows_fs:
file_object.st_nlink = 0
self._statresult_symlink = file_object.stat_result.copy()
return self._statresult_symlink
if self._statresult is None:
file_object = self._filesystem.lresolve(self.path)
self._inode = file_object.st_ino
if self._filesystem.is_windows_fs:
file_object.st_nlink = 0
self._statresult = file_object.stat_result.copy()
return self._statresult | def stat(self, follow_symlinks=True) | Return a stat_result object for this entry.
Args:
follow_symlinks: If False and the entry is a symlink, return the
result for the symlink, otherwise for the object it points to. | 2.656302 | 2.705036 | 0.981984 |
return walk(self.filesystem, top, topdown, onerror, followlinks) | def walk(self, top, topdown=True, onerror=None, followlinks=False) | Perform a walk operation over the fake filesystem.
Args:
top: The root directory from which to begin walk.
topdown: Determines whether to return the tuples with the root as
the first entry (`True`) or as the last, after all the child
directory tuples (`False`).
onerror: If not `None`, function which will be called to handle the
`os.error` instance provided when `os.listdir()` fails.
followlinks: If `True`, symbolic links are followed.
Yields:
(path, directories, nondirectories) for top and each of its
subdirectories. See the documentation for the builtin os module
for further details. | 5.082217 | 10.822596 | 0.469593 |
@Deprecator(func.__name__, deprecated_name)
def _old_function(*args, **kwargs):
return func(*args, **kwargs)
setattr(clss, deprecated_name, _old_function) | def add(clss, func, deprecated_name) | Add the deprecated version of a member function to the given class.
Gives a deprecation warning on usage.
Args:
clss: the class where the deprecated function is to be added
func: the actual function that is called by the deprecated version
deprecated_name: the deprecated name of the function | 3.655627 | 4.341335 | 0.842051 |
# pylint: disable=protected-access
FakePath.filesystem = filesystem
FakePathlibModule.PureWindowsPath._flavour = _FakeWindowsFlavour(
filesystem)
FakePathlibModule.PurePosixPath._flavour = _FakePosixFlavour(filesystem) | def init_module(filesystem) | Initializes the fake module with the fake file system. | 6.094135 | 5.886249 | 1.035317 |
if sep is None:
sep = self.filesystem.path_separator
if self.filesystem.is_windows_fs:
return self._splitroot_with_drive(path, sep)
return self._splitroot_posix(path, sep) | def splitroot(self, path, sep=None) | Split path into drive, root and rest. | 3.398806 | 3.391845 | 1.002052 |
if self.filesystem.is_windows_fs:
return [p.lower() for p in parts]
return parts | def casefold_parts(self, parts) | Return the lower-case version of parts for a Windows filesystem. | 5.835855 | 3.423949 | 1.704422 |
if self.filesystem.is_windows_fs:
return self._resolve_windows(path, strict)
return self._resolve_posix(path, strict) | def resolve(self, path, strict) | Make the path absolute, resolving any symlinks. | 3.893409 | 3.759514 | 1.035615 |
if sys.version_info >= (3, 6) or pathlib2:
if strict is None:
strict = False
else:
if strict is not None:
raise TypeError(
"resolve() got an unexpected keyword argument 'strict'")
strict = True
if self._closed:
self._raise_closed()
path = self._flavour.resolve(self, strict=strict)
if path is None:
self.stat()
path = str(self.absolute())
path = self.filesystem.absnormpath(path)
return FakePath(path) | def resolve(self, strict=None) | Make the path absolute, resolving all symlinks on the way and also
normalizing it (for example turning slashes into backslashes
under Windows).
Args:
strict: If False (default) no exception is raised if the path
does not exist.
New in Python 3.6.
Raises:
IOError: if the path doesn't exist (strict=True or Python < 3.6) | 4.015443 | 3.896875 | 1.030426 |
if self._closed:
self._raise_closed()
return FakeFileOpen(self.filesystem, use_io=True)(
self._path(), mode, buffering, encoding, errors, newline) | def open(self, mode='r', buffering=-1, encoding=None,
errors=None, newline=None) | Open the file pointed by this path and return a fake file object.
Raises:
IOError: if the target object is a directory, the path is invalid
or permission is denied. | 8.256112 | 7.874536 | 1.048457 |
if self._closed:
self._raise_closed()
if self.exists():
if exist_ok:
self.filesystem.utime(self._path(), None)
else:
self.filesystem.raise_os_error(errno.EEXIST, self._path())
else:
fake_file = self.open('w')
fake_file.close()
self.chmod(mode) | def touch(self, mode=0o666, exist_ok=True) | Create a fake file for the path with the given access mode,
if it doesn't exist.
Args:
mode: the file mode for the file if it does not exist
exist_ok: if the file already exists and this is True, nothing
happens, otherwise FileExistError is raised
Raises:
OSError: (Python 2 only) if the file exists and exits_ok is False.
FileExistsError: (Python 3 only) if the file exists and exits_ok is
False. | 3.423176 | 3.464244 | 0.988145 |
saved = sys.modules.pop(old.__name__, None)
new = __import__(old.__name__)
sys.modules[old.__name__] = saved
return new | def _copy_module(old) | Recompiles and creates new module object. | 3.248013 | 3.148623 | 1.031566 |
if not IS_PY2 and isinstance(self.byte_contents, bytes):
return self.byte_contents.decode(
self.encoding or locale.getpreferredencoding(False),
errors=self.errors)
return self.byte_contents | def contents(self) | Return the contents as string with the original encoding. | 3.937292 | 3.440978 | 1.144236 |
self._check_positive_int(st_size)
if self.st_size:
self.size = 0
if self.filesystem:
self.filesystem.change_disk_usage(st_size, self.name, self.st_dev)
self.st_size = st_size
self._byte_contents = None | def set_large_file_size(self, st_size) | Sets the self.st_size attribute and replaces self.content with None.
Provided specifically to simulate very large files without regards
to their content (which wouldn't fit in memory).
Note that read/write operations with such a file raise
:py:class:`FakeLargeFileIoException`.
Args:
st_size: (int) The desired file size
Raises:
IOError: if the st_size is not a non-negative integer,
or if st_size exceeds the available file system space | 5.077024 | 5.347377 | 0.949442 |
contents = self._encode_contents(contents)
changed = self._byte_contents != contents
st_size = len(contents)
if self._byte_contents:
self.size = 0
current_size = self.st_size or 0
self.filesystem.change_disk_usage(
st_size - current_size, self.name, self.st_dev)
self._byte_contents = contents
self.st_size = st_size
self.epoch += 1
return changed | def _set_initial_contents(self, contents) | Sets the file contents and size.
Called internally after initial file creation.
Args:
contents: string, new content of file.
Returns:
True if the contents have been changed.
Raises:
IOError: if the st_size is not a non-negative integer,
or if st_size exceeds the available file system space | 4.791617 | 4.827044 | 0.992661 |
self.encoding = encoding
changed = self._set_initial_contents(contents)
if self._side_effect is not None:
self._side_effect(self)
return changed | def set_contents(self, contents, encoding=None) | Sets the file contents and size and increases the modification time.
Also executes the side_effects if available.
Args:
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 `st_size` is not a non-negative integer,
or if it exceeds the available file system space. | 5.139163 | 5.482925 | 0.937303 |
names = []
obj = self
while obj:
names.insert(0, obj.name)
obj = obj.parent_dir
sep = self.filesystem._path_separator(self.name)
if names[0] == sep:
names.pop(0)
dir_path = sep.join(names)
# Windows paths with drive have a root separator entry
# which should be removed
is_drive = names and len(names[0]) == 2 and names[0][1] == ':'
if not is_drive:
dir_path = sep + dir_path
else:
dir_path = sep.join(names)
dir_path = self.filesystem.absnormpath(dir_path)
return dir_path | def path(self) | Return the full path of the current object. | 3.96312 | 3.821557 | 1.037043 |
self._check_positive_int(st_size)
current_size = self.st_size or 0
self.filesystem.change_disk_usage(
st_size - current_size, self.name, self.st_dev)
if self._byte_contents:
if st_size < current_size:
self._byte_contents = self._byte_contents[:st_size]
else:
if IS_PY2:
self._byte_contents = '%s%s' % (
self._byte_contents, '\0' * (st_size - current_size))
else:
self._byte_contents += b'\0' * (st_size - current_size)
self.st_size = st_size
self.epoch += 1 | def size(self, st_size) | Resizes file content, padding with nulls if new size exceeds the
old size.
Args:
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 | 3.221198 | 3.046973 | 1.05718 |
return [item[0] for item in sorted(
self.byte_contents.items(), key=lambda entry: entry[1].st_ino)] | def ordered_dirs(self) | Return the list of contained directory entry names ordered by
creation order. | 8.429183 | 6.329671 | 1.331694 |
if (not is_root() and not self.st_mode & PERM_WRITE and
not self.filesystem.is_windows_fs):
exception = IOError if IS_PY2 else OSError
raise exception(errno.EACCES, 'Permission Denied', self.path)
if path_object.name in self.contents:
self.filesystem.raise_os_error(errno.EEXIST, self.path)
self.contents[path_object.name] = path_object
path_object.parent_dir = self
self.st_nlink += 1
path_object.st_nlink += 1
path_object.st_dev = self.st_dev
if path_object.st_nlink == 1:
self.filesystem.change_disk_usage(
path_object.size, path_object.name, self.st_dev) | def add_entry(self, path_object) | Adds a child FakeFile to this directory.
Args:
path_object: FakeFile instance to add as a child of this directory.
Raises:
OSError: if the directory has no write permission (Posix only)
OSError: if the file or directory to be added already exists | 3.286717 | 3.220625 | 1.020521 |
pathname_name = self._normalized_entryname(pathname_name)
return self.contents[pathname_name] | def get_entry(self, pathname_name) | Retrieves the specified child file or directory entry.
Args:
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. | 6.277727 | 12.94245 | 0.485049 |
pathname_name = self._normalized_entryname(pathname_name)
entry = self.get_entry(pathname_name)
if self.filesystem.is_windows_fs:
if entry.st_mode & PERM_WRITE == 0:
self.filesystem.raise_os_error(errno.EACCES, pathname_name)
if self.filesystem.has_open_file(entry):
self.filesystem.raise_os_error(errno.EACCES, pathname_name)
else:
if (not is_root() and (self.st_mode & (PERM_WRITE | PERM_EXE) !=
PERM_WRITE | PERM_EXE)):
self.filesystem.raise_os_error(errno.EACCES, pathname_name)
if recursive and isinstance(entry, FakeDirectory):
while entry.contents:
entry.remove_entry(list(entry.contents)[0])
elif entry.st_nlink == 1:
self.filesystem.change_disk_usage(
-entry.size, pathname_name, entry.st_dev)
self.st_nlink -= 1
entry.st_nlink -= 1
assert entry.st_nlink >= 0
del self.contents[pathname_name] | def remove_entry(self, pathname_name, recursive=True) | Removes the specified child file or directory.
Args:
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. | 3.110166 | 3.165787 | 0.982431 |
obj = self
while obj:
if obj == dir_object:
return True
obj = obj.parent_dir
return False | def has_parent_object(self, dir_object) | Return `True` if dir_object is a direct or indirect parent
directory, or if both are the same object. | 3.035205 | 2.713013 | 1.118758 |
if not self.contents_read:
self.contents_read = True
base = self.path
for entry in os.listdir(self.source_path):
source_path = os.path.join(self.source_path, entry)
target_path = os.path.join(base, entry)
if os.path.isdir(source_path):
self.filesystem.add_real_directory(
source_path, self.read_only, target_path=target_path)
else:
self.filesystem.add_real_file(
source_path, self.read_only, target_path=target_path)
return self.byte_contents | def contents(self) | Return the list of contained directory entries, loading them
if not already loaded. | 2.568265 | 2.401602 | 1.069397 |
self.root = FakeDirectory(self.path_separator, filesystem=self)
self.cwd = self.root.name
self.open_files = []
self._free_fd_heap = []
self._last_ino = 0
self._last_dev = 0
self.mount_points = {}
self.add_mount_point(self.root.name, total_size)
self._add_standard_streams() | def reset(self, total_size=None) | Remove all file system contents and reset the root. | 5.965101 | 5.339505 | 1.117164 |
message = self._error_message(errno)
if (winerror is not None and sys.platform == 'win32' and
self.is_windows_fs):
if IS_PY2:
raise WindowsError(winerror, message, filename)
raise OSError(errno, message, filename, winerror)
raise OSError(errno, message, filename) | def raise_os_error(self, errno, filename=None, winerror=None) | Raises OSError.
The error message is constructed from the given error code and shall
start with the error string issued in the real system.
Note: this is not true under Windows if winerror is given - in this
case a localized message specific to winerror will be shown in the
real file system.
Args:
errno: A numeric error code from the C variable errno.
filename: The name of the affected file, if any.
winerror: Windows only - the specific Windows error code. | 3.89685 | 4.505946 | 0.864824 |
raise IOError(errno, self._error_message(errno), filename) | def raise_io_error(self, errno, filename=None) | Raises IOError.
The error message is constructed from the given error code and shall
start with the error in the real system.
Args:
errno: A numeric error code from the C variable errno.
filename: The name of the affected file, if any. | 5.299739 | 8.415839 | 0.629734 |
if string is None:
return string
if IS_PY2:
# pylint: disable=undefined-variable
if isinstance(matched, text_type):
return text_type(string)
else:
if isinstance(matched, bytes) and isinstance(string, str):
return string.encode(locale.getpreferredencoding(False))
return string | def _matching_string(matched, string) | Return the string as byte or unicode depending
on the type of matched, assuming string is an ASCII string. | 3.148082 | 2.952441 | 1.066264 |
path = self.absnormpath(path)
if path in self.mount_points:
self.raise_os_error(errno.EEXIST, path)
self._last_dev += 1
self.mount_points[path] = {
'idev': self._last_dev, 'total_size': total_size, 'used_size': 0
}
# special handling for root path: has been created before
root_dir = (self.root if path == self.root.name
else self.create_dir(path))
root_dir.st_dev = self._last_dev
return self.mount_points[path] | def add_mount_point(self, path, total_size=None) | Add a new mount point for a filesystem device.
The mount point gets a new unique device number.
Args:
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. | 4.399224 | 4.730593 | 0.929952 |
DiskUsage = namedtuple('usage', 'total, used, free')
if path is None:
mount_point = self.mount_points[self.root.name]
else:
mount_point = self._mount_point_for_path(path)
if mount_point and mount_point['total_size'] is not None:
return DiskUsage(mount_point['total_size'],
mount_point['used_size'],
mount_point['total_size'] -
mount_point['used_size'])
return DiskUsage(
1024 * 1024 * 1024 * 1024, 0, 1024 * 1024 * 1024 * 1024) | def get_disk_usage(self, 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().
Args:
path: The disk space is returned for the file system device where
`path` resides.
Defaults to the root path (e.g. '/' on Unix systems). | 2.185263 | 2.28569 | 0.956063 |
if path is None:
path = self.root.name
mount_point = self._mount_point_for_path(path)
if (mount_point['total_size'] is not None and
mount_point['used_size'] > total_size):
self.raise_io_error(errno.ENOSPC, path)
mount_point['total_size'] = total_size | def set_disk_usage(self, 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.
Args:
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. | 3.384455 | 3.449833 | 0.981049 |
mount_point = self._mount_point_for_device(st_dev)
if mount_point:
total_size = mount_point['total_size']
if total_size is not None:
if total_size - mount_point['used_size'] < usage_change:
self.raise_io_error(errno.ENOSPC, file_path)
mount_point['used_size'] += usage_change | def change_disk_usage(self, usage_change, file_path, st_dev) | Change the used disk space by the given amount.
Args:
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 | 3.042359 | 3.429556 | 0.8871 |
# stat should return the tuple representing return value of os.stat
try:
file_object = self.resolve(
entry_path, follow_symlinks, allow_fd=True)
self.raise_for_filepath_ending_with_separator(
entry_path, file_object, follow_symlinks)
return file_object.stat_result.copy()
except IOError as io_error:
winerror = (io_error.winerror if hasattr(io_error, 'winerror')
else io_error.errno)
self.raise_os_error(io_error.errno, entry_path, winerror=winerror) | def stat(self, entry_path, follow_symlinks=True) | Return the os.stat-like tuple for the FakeFile object of entry_path.
Args:
entry_path: Path to filesystem object to retrieve.
follow_symlinks: If False and entry_path points to a symlink,
the link itself is inspected instead of the linked object.
Returns:
The FakeStatResult object corresponding to entry_path.
Raises:
OSError: if the filesystem object doesn't exist. | 4.598177 | 4.896217 | 0.939129 |
try:
file_object = self.resolve(path, follow_symlinks, allow_fd=True)
except IOError as io_error:
if io_error.errno == errno.ENOENT:
self.raise_os_error(errno.ENOENT, path)
raise
if self.is_windows_fs:
if mode & PERM_WRITE:
file_object.st_mode = file_object.st_mode | 0o222
else:
file_object.st_mode = file_object.st_mode & 0o777555
else:
file_object.st_mode = ((file_object.st_mode & ~PERM_ALL) |
(mode & PERM_ALL))
file_object.st_ctime = time.time() | def chmod(self, path, mode, follow_symlinks=True) | Change the permissions of a file as encoded in integer mode.
Args:
path: (str) Path to the file.
mode: (int) Permissions.
follow_symlinks: If `False` and `path` points to a symlink,
the link itself is affected instead of the linked object. | 2.582397 | 2.737522 | 0.943334 |
self._handle_utime_arg_errors(ns, times)
try:
file_object = self.resolve(path, follow_symlinks, allow_fd=True)
except IOError as io_error:
if io_error.errno == errno.ENOENT:
self.raise_os_error(errno.ENOENT, path)
raise
if times is not None:
for file_time in times:
if not isinstance(file_time, (int, float)):
raise TypeError('atime and mtime must be numbers')
file_object.st_atime = times[0]
file_object.st_mtime = times[1]
elif ns is not None:
for file_time in ns:
if not isinstance(file_time, int):
raise TypeError('atime and mtime must be ints')
file_object.st_atime_ns = ns[0]
file_object.st_mtime_ns = ns[1]
else:
current_time = time.time()
file_object.st_atime = current_time
file_object.st_mtime = current_time | def utime(self, path, times=None, ns=None, follow_symlinks=True) | Change the access and modified times of a file.
Args:
path: (str) Path to the file.
times: 2-tuple of int or float numbers, of the form (atime, mtime)
which is used to set the access and modified times in seconds.
If None, both times are set to the current time.
ns: 2-tuple of int numbers, of the form (atime, mtime) which is
used to set the access and modified times in nanoseconds.
If `None`, both times are set to the current time.
New in Python 3.3.
follow_symlinks: If `False` and entry_path points to a symlink,
the link itself is queried instead of the linked object.
New in Python 3.3.
Raises:
TypeError: If anything other than the expected types is
specified in the passed `times` or `ns` tuple,
or if the tuple length is not equal to 2.
ValueError: If both times and ns are specified. | 2.129893 | 2.123772 | 1.002882 |
if self._free_fd_heap:
open_fd = heapq.heappop(self._free_fd_heap)
self.open_files[open_fd] = [file_obj]
return open_fd
self.open_files.append([file_obj])
return len(self.open_files) - 1 | def _add_open_file(self, file_obj) | Add file_obj to the list of open files on the filesystem.
Used internally to manage open files.
The position in the open_files array is the file descriptor number.
Args:
file_obj: File object to be added to open files list.
Returns:
File descriptor number for the file object. | 2.981802 | 3.010026 | 0.990623 |
self.open_files[file_des] = None
heapq.heappush(self._free_fd_heap, file_des) | def _close_open_file(self, file_des) | Remove file object with given descriptor from the list
of open files.
Sets the entry in open_files to None.
Args:
file_des: Descriptor of file object to be removed from
open files list. | 4.601688 | 5.027507 | 0.915302 |
if not is_int_type(file_des):
raise TypeError('an integer is required')
if (file_des >= len(self.open_files) or
self.open_files[file_des] is None):
self.raise_os_error(errno.EBADF, str(file_des))
return self.open_files[file_des][0] | def get_open_file(self, file_des) | Return an open file.
Args:
file_des: File descriptor of the open file.
Raises:
OSError: an invalid file descriptor.
TypeError: filedes is not an integer.
Returns:
Open file object. | 3.389194 | 3.332501 | 1.017012 |
return (file_object in [wrappers[0].get_object()
for wrappers in self.open_files if wrappers]) | def has_open_file(self, file_object) | Return True if the given file object is in the list of open files.
Args:
file_object: The FakeFile object to be checked.
Returns:
`True` if the file is open. | 13.541162 | 18.636913 | 0.726578 |
path = self.normcase(path)
drive, path = self.splitdrive(path)
sep = self._path_separator(path)
is_absolute_path = path.startswith(sep)
path_components = path.split(sep)
collapsed_path_components = []
dot = self._matching_string(path, '.')
dotdot = self._matching_string(path, '..')
for component in path_components:
if (not component) or (component == dot):
continue
if component == dotdot:
if collapsed_path_components and (
collapsed_path_components[-1] != dotdot):
# Remove an up-reference: directory/..
collapsed_path_components.pop()
continue
elif is_absolute_path:
# Ignore leading .. components if starting from the
# root directory.
continue
collapsed_path_components.append(component)
collapsed_path = sep.join(collapsed_path_components)
if is_absolute_path:
collapsed_path = sep + collapsed_path
return drive + collapsed_path or dot | def normpath(self, path) | Mimic os.path.normpath using the specified path_separator.
Mimics os.path.normpath using the path_separator that was specified
for this FakeFilesystem. Normalizes the path, but unlike the method
absnormpath, does not make it absolute. Eliminates dot components
(. and ..) and combines repeated path separators (//). Initial ..
components are left in place for relative paths.
If the result is an empty path, '.' is returned instead.
This also replaces alternative path separator with path separator.
That is, it behaves like the real os.path.normpath on Windows if
initialized with '\\' as path separator and '/' as alternative
separator.
Args:
path: (str) The path to normalize.
Returns:
(str) A copy of path with empty components and dot components
removed. | 3.100442 | 3.237347 | 0.957711 |
def components_to_path():
if len(path_components) > len(normalized_components):
normalized_components.extend(
path_components[len(normalized_components):])
sep = self._path_separator(path)
normalized_path = sep.join(normalized_components)
if path.startswith(sep) and not normalized_path.startswith(sep):
normalized_path = sep + normalized_path
return normalized_path
if self.is_case_sensitive or not path:
return path
path_components = self._path_components(path)
normalized_components = []
current_dir = self.root
for component in path_components:
if not isinstance(current_dir, FakeDirectory):
return components_to_path()
dir_name, current_dir = self._directory_content(
current_dir, component)
if current_dir is None or (
isinstance(current_dir, FakeDirectory) and
current_dir._byte_contents is None and
current_dir.st_size == 0):
return components_to_path()
normalized_components.append(dir_name)
return components_to_path() | def _original_path(self, path) | Return a normalized case version of the given path for
case-insensitive file systems. For case-sensitive file systems,
return path unchanged.
Args:
path: the file path to be transformed
Returns:
A version of path matching the case of existing path elements. | 2.928386 | 2.954915 | 0.991022 |
path = self.normcase(path)
cwd = self._matching_string(path, self.cwd)
if not path:
path = self.path_separator
elif not self._starts_with_root_path(path):
# Prefix relative paths with cwd, if cwd is not root.
root_name = self._matching_string(path, self.root.name)
empty = self._matching_string(path, '')
path = self._path_separator(path).join(
(cwd != root_name and cwd or empty, path))
if path == self._matching_string(path, '.'):
path = cwd
return self.normpath(path) | def absnormpath(self, path) | Absolutize and minimalize the given path.
Forces all relative paths to be absolute, and normalizes the path to
eliminate dot and empty components.
Args:
path: Path to normalize.
Returns:
The normalized path relative to the current working directory,
or the root directory if path is empty. | 4.842148 | 5.200397 | 0.931111 |
path = self.normcase(path)
sep = self._path_separator(path)
path_components = path.split(sep)
if not path_components:
return ('', '')
starts_with_drive = self._starts_with_drive_letter(path)
basename = path_components.pop()
colon = self._matching_string(path, ':')
if not path_components:
if starts_with_drive:
components = basename.split(colon)
return (components[0] + colon, components[1])
return ('', basename)
for component in path_components:
if component:
# The path is not the root; it contains a non-separator
# component. Strip all trailing separators.
while not path_components[-1]:
path_components.pop()
if starts_with_drive:
if not path_components:
components = basename.split(colon)
return (components[0] + colon, components[1])
if (len(path_components) == 1 and
path_components[0].endswith(colon)):
return (path_components[0] + sep, basename)
return (sep.join(path_components), basename)
# Root path. Collapse all leading separators.
return (sep, basename) | def splitpath(self, path) | Mimic os.path.splitpath using the specified path_separator.
Mimics os.path.splitpath using the path_separator that was specified
for this FakeFilesystem.
Args:
path: (str) The path to split.
Returns:
(str) A duple (pathname, basename) for which pathname does not
end with a slash, and basename does not contain a slash. | 3.286455 | 3.256694 | 1.009138 |
path = make_string_path(path)
if self.is_windows_fs:
if len(path) >= 2:
path = self.normcase(path)
sep = self._path_separator(path)
# UNC path handling is here since Python 2.7.8,
# back-ported from Python 3
if sys.version_info >= (2, 7, 8):
if (path[0:2] == sep * 2) and (
path[2:3] != sep):
# UNC path handling - splits off the mount point
# instead of the drive
sep_index = path.find(sep, 2)
if sep_index == -1:
return path[:0], path
sep_index2 = path.find(sep, sep_index + 1)
if sep_index2 == sep_index + 1:
return path[:0], path
if sep_index2 == -1:
sep_index2 = len(path)
return path[:sep_index2], path[sep_index2:]
if path[1:2] == self._matching_string(path, ':'):
return path[:2], path[2:]
return path[:0], path | def splitdrive(self, path) | Splits the path into the drive part and the rest of the path.
Taken from Windows specific implementation in Python 3.5
and slightly adapted.
Args:
path: the full path to be splitpath.
Returns:
A tuple of the drive part and the rest of the path, or of
an empty string and the full path if drive letters are
not supported or no drive is present. | 3.579839 | 3.629419 | 0.986339 |
base_path = all_paths[0]
paths_to_add = all_paths[1:]
sep = self._path_separator(base_path)
seps = [sep, self._alternative_path_separator(base_path)]
result_drive, result_path = self.splitdrive(base_path)
for path in paths_to_add:
drive_part, path_part = self.splitdrive(path)
if path_part and path_part[:1] in seps:
# Second path is absolute
if drive_part or not result_drive:
result_drive = drive_part
result_path = path_part
continue
elif drive_part and drive_part != result_drive:
if (self.is_case_sensitive or
drive_part.lower() != result_drive.lower()):
# Different drives => ignore the first path entirely
result_drive = drive_part
result_path = path_part
continue
# Same drive in different case
result_drive = drive_part
# Second path is relative to the first
if result_path and result_path[-1:] not in seps:
result_path = result_path + sep
result_path = result_path + path_part
# add separator between UNC and non-absolute path
colon = self._matching_string(base_path, ':')
if (result_path and result_path[:1] not in seps and
result_drive and result_drive[-1:] != colon):
return result_drive + sep + result_path
return result_drive + result_path | def _join_paths_with_drive_support(self, *all_paths) | Taken from Python 3.5 os.path.join() code in ntpath.py
and slightly adapted | 2.996002 | 2.913392 | 1.028355 |
if sys.version_info >= (3, 6):
paths = [os.fspath(path) for path in paths]
if len(paths) == 1:
return paths[0]
if self.is_windows_fs:
return self._join_paths_with_drive_support(*paths)
joined_path_segments = []
sep = self._path_separator(paths[0])
for path_segment in paths:
if self._starts_with_root_path(path_segment):
# An absolute path
joined_path_segments = [path_segment]
else:
if (joined_path_segments and
not joined_path_segments[-1].endswith(sep)):
joined_path_segments.append(sep)
if path_segment:
joined_path_segments.append(path_segment)
return self._matching_string(paths[0], '').join(joined_path_segments) | def joinpaths(self, *paths) | Mimic os.path.join using the specified path_separator.
Args:
*paths: (str) Zero or more paths to join.
Returns:
(str) The paths joined by the path separator, starting with
the last absolute path in paths. | 3.006624 | 3.037786 | 0.989742 |
if not path or path == self._path_separator(path):
return []
drive, path = self.splitdrive(path)
path_components = path.split(self._path_separator(path))
assert drive or path_components
if not path_components[0]:
if len(path_components) > 1 and not path_components[1]:
path_components = []
else:
# This is an absolute path.
path_components = path_components[1:]
if drive:
path_components.insert(0, drive)
return path_components | def _path_components(self, path) | Breaks the path into a list of component names.
Does not include the root directory as a component, as all paths
are considered relative to the root directory for the FakeFilesystem.
Callers should basically follow this pattern:
.. code:: python
file_path = self.absnormpath(file_path)
path_components = self._path_components(file_path)
current_dir = self.root
for component in path_components:
if component not in current_dir.contents:
raise IOError
_do_stuff_with_component(current_dir, component)
current_dir = current_dir.get_entry(component)
Args:
path: Path to tokenize.
Returns:
The list of names split from path. | 2.732765 | 2.818337 | 0.969638 |
colon = self._matching_string(file_path, ':')
return (self.is_windows_fs and len(file_path) >= 2 and
file_path[:1].isalpha and (file_path[1:2]) == colon) | def _starts_with_drive_letter(self, file_path) | Return True if file_path starts with a drive letter.
Args:
file_path: the full path to be examined.
Returns:
`True` if drive letter support is enabled in the filesystem and
the path starts with a drive letter. | 7.307717 | 8.570239 | 0.852685 |
if is_int_type(file_path):
return False
file_path = make_string_path(file_path)
return (file_path and
file_path not in (self.path_separator,
self.alternative_path_separator) and
(file_path.endswith(self._path_separator(file_path)) or
self.alternative_path_separator is not None and
file_path.endswith(
self._alternative_path_separator(file_path)))) | def ends_with_path_separator(self, file_path) | Return True if ``file_path`` ends with a valid path separator. | 3.411391 | 3.247788 | 1.050374 |
if check_link and self.islink(file_path):
return True
file_path = make_string_path(file_path)
if file_path is None:
raise TypeError
if not file_path:
return False
if file_path == self.dev_null.name:
return not self.is_windows_fs
try:
if self.is_filepath_ending_with_separator(file_path):
return False
file_path = self.resolve_path(file_path)
except (IOError, OSError):
return False
if file_path == self.root.name:
return True
path_components = self._path_components(file_path)
current_dir = self.root
for component in path_components:
current_dir = self._directory_content(current_dir, component)[1]
if not current_dir:
return False
return True | def exists(self, file_path, check_link=False) | Return true if a path points to an existing file system object.
Args:
file_path: The path to examine.
Returns:
(bool) True if the corresponding object exists.
Raises:
TypeError: if file_path is None. | 3.009733 | 3.020421 | 0.996461 |
if (allow_fd and sys.version_info >= (3, 3) and
isinstance(file_path, int)):
return self.get_open_file(file_path).get_object().path
file_path = make_string_path(file_path)
if file_path is None:
# file.open(None) raises TypeError, so mimic that.
raise TypeError('Expected file system path string, received None')
file_path = self._to_string(file_path)
if not file_path or not self._valid_relative_path(file_path):
# file.open('') raises IOError, so mimic that, and validate that
# all parts of a relative path exist.
self.raise_io_error(errno.ENOENT, file_path)
file_path = self.absnormpath(self._original_path(file_path))
if self._is_root_path(file_path):
return file_path
if file_path == self.dev_null.name:
return file_path
path_components = self._path_components(file_path)
resolved_components = self._resolve_components(path_components, raw_io)
return self._components_to_path(resolved_components) | def resolve_path(self, file_path, allow_fd=False, raw_io=True) | Follow a path, resolving symlinks.
ResolvePath traverses the filesystem along the specified file path,
resolving file names and symbolic links until all elements of the path
are exhausted, or we reach a file which does not exist.
If all the elements are not consumed, they just get appended to the
path resolved so far.
This gives us the path which is as resolved as it can be, even if the
file does not exist.
This behavior mimics Unix semantics, and is best shown by example.
Given a file system that looks like this:
/a/b/
/a/b/c -> /a/b2 c is a symlink to /a/b2
/a/b2/x
/a/c -> ../d
/a/x -> y
Then:
/a/b/x => /a/b/x
/a/c => /a/d
/a/x => /a/y
/a/b/c/d/e => /a/b2/d/e
Args:
file_path: The path to examine.
allow_fd: If `True`, `file_path` may be open file descriptor.
raw_io: `True` if called from low-level I/O functions.
Returns:
The resolved_path (string) or None.
Raises:
TypeError: if `file_path` is `None`.
IOError: if `file_path` is '' or a part of the path doesn't exist. | 3.906885 | 3.819273 | 1.02294 |
link_path = link.contents
sep = self._path_separator(link_path)
# For links to absolute paths, we want to throw out everything
# in the path built so far and replace with the link. For relative
# links, we have to append the link to what we have so far,
if not self._starts_with_root_path(link_path):
# Relative path. Append remainder of path to what we have
# processed so far, excluding the name of the link itself.
# /a/b => ../c should yield /a/../c
# (which will normalize to /c)
# /a/b => d should yield a/d
components = link_path_components[:-1]
components.append(link_path)
link_path = sep.join(components)
# Don't call self.NormalizePath(), as we don't want to prepend
# self.cwd.
return self.normpath(link_path) | def _follow_link(self, link_path_components, link) | Follow a link w.r.t. a path resolved so far.
The component is either a real file, which is a no-op, or a
symlink. In the case of a symlink, we have to modify the path
as built up so far
/a/b => ../c should yield /a/../c (which will normalize to /a/c)
/a/b => x should yield /a/x
/a/b => /x/y/z should yield /x/y/z
The modified path may land us in a new spot which is itself a
link, so we may repeat the process.
Args:
link_path_components: The resolved path built up to the link
so far.
link: The link object itself.
Returns:
(string) The updated path resolved after following the link.
Raises:
IOError: if there are too many levels of symbolic link | 7.127042 | 6.126386 | 1.163335 |
file_path = make_string_path(file_path)
if file_path == self.root.name:
return self.root
if file_path == self.dev_null.name:
return self.dev_null
file_path = self._original_path(file_path)
path_components = self._path_components(file_path)
target_object = self.root
try:
for component in path_components:
if S_ISLNK(target_object.st_mode):
target_object = self.resolve(target_object.contents)
if not S_ISDIR(target_object.st_mode):
if not self.is_windows_fs:
self.raise_io_error(errno.ENOTDIR, file_path)
self.raise_io_error(errno.ENOENT, file_path)
target_object = target_object.get_entry(component)
except KeyError:
self.raise_io_error(errno.ENOENT, file_path)
return target_object | def get_object_from_normpath(self, file_path) | Search for the specified filesystem object within the fake
filesystem.
Args:
file_path: Specifies target FakeFile object to retrieve, with a
path that has already been normalized/resolved.
Returns:
The FakeFile object corresponding to file_path.
Raises:
IOError: if the object is not found. | 2.566631 | 2.587279 | 0.99202 |
file_path = make_string_path(file_path)
file_path = self.absnormpath(self._original_path(file_path))
return self.get_object_from_normpath(file_path) | def get_object(self, file_path) | Search for the specified filesystem object within the fake
filesystem.
Args:
file_path: Specifies the target FakeFile object to retrieve.
Returns:
The FakeFile object corresponding to `file_path`.
Raises:
IOError: if the object is not found. | 5.783728 | 8.071951 | 0.716522 |
if isinstance(file_path, int):
if allow_fd and sys.version_info >= (3, 3):
return self.get_open_file(file_path).get_object()
raise TypeError('path should be string, bytes or '
'os.PathLike (if supported), not int')
if follow_symlinks:
file_path = make_string_path(file_path)
return self.get_object_from_normpath(self.resolve_path(file_path))
return self.lresolve(file_path) | def resolve(self, file_path, follow_symlinks=True, allow_fd=False) | Search for the specified filesystem object, resolving all links.
Args:
file_path: Specifies the target FakeFile object to retrieve.
follow_symlinks: If `False`, the link itself is resolved,
otherwise the object linked to.
allow_fd: If `True`, `file_path` may be an open file descriptor
Returns:
The FakeFile object corresponding to `file_path`.
Raises:
IOError: if the object is not found. | 4.282808 | 4.503484 | 0.950999 |
path = make_string_path(path)
if path == self.root.name:
# The root directory will never be a link
return self.root
# remove trailing separator
path = self._path_without_trailing_separators(path)
path = self._original_path(path)
parent_directory, child_name = self.splitpath(path)
if not parent_directory:
parent_directory = self.cwd
try:
parent_obj = self.resolve(parent_directory)
assert parent_obj
if not isinstance(parent_obj, FakeDirectory):
if not self.is_windows_fs and isinstance(parent_obj, FakeFile):
self.raise_io_error(errno.ENOTDIR, path)
self.raise_io_error(errno.ENOENT, path)
return parent_obj.get_entry(child_name)
except KeyError:
self.raise_io_error(errno.ENOENT, path) | def lresolve(self, path) | Search for the specified object, resolving only parent links.
This is analogous to the stat/lstat difference. This resolves links
*to* the object but not of the final object itself.
Args:
path: Specifies target FakeFile object to retrieve.
Returns:
The FakeFile object corresponding to path.
Raises:
IOError: if the object is not found. | 3.420427 | 3.515641 | 0.972917 |
error_fct = error_fct or self.raise_os_error
if not file_path:
target_directory = self.root
else:
target_directory = self.resolve(file_path)
if not S_ISDIR(target_directory.st_mode):
error = errno.ENOENT if self.is_windows_fs else errno.ENOTDIR
error_fct(error, file_path)
target_directory.add_entry(file_object) | def add_object(self, file_path, file_object, error_fct=None) | Add a fake file or directory into the filesystem at file_path.
Args:
file_path: The path to the file to be added relative to self.
file_object: File or directory to add.
error_class: The error class to be thrown if file_path does
not correspond to a directory (used internally(
Raises:
IOError or OSError: if file_path does not correspond to a
directory. | 3.50458 | 3.830026 | 0.915028 |
ends_with_sep = self.ends_with_path_separator(old_file_path)
old_file_path = self.absnormpath(old_file_path)
new_file_path = self.absnormpath(new_file_path)
if not self.exists(old_file_path, check_link=True):
self.raise_os_error(errno.ENOENT, old_file_path, 2)
if ends_with_sep:
self._handle_broken_link_with_trailing_sep(old_file_path)
old_object = self.lresolve(old_file_path)
if not self.is_windows_fs:
self._handle_posix_dir_link_errors(
new_file_path, old_file_path, ends_with_sep)
if self.exists(new_file_path, check_link=True):
new_file_path = self._rename_to_existing_path(
force_replace, new_file_path, old_file_path,
old_object, ends_with_sep)
if not new_file_path:
return
old_dir, old_name = self.splitpath(old_file_path)
new_dir, new_name = self.splitpath(new_file_path)
if not self.exists(new_dir):
self.raise_os_error(errno.ENOENT, new_dir)
old_dir_object = self.resolve(old_dir)
new_dir_object = self.resolve(new_dir)
if old_dir_object.st_dev != new_dir_object.st_dev:
self.raise_os_error(errno.EXDEV, old_file_path)
if not S_ISDIR(new_dir_object.st_mode):
self.raise_os_error(
errno.EACCES if self.is_windows_fs else errno.ENOTDIR,
new_file_path)
if new_dir_object.has_parent_object(old_object):
self.raise_os_error(errno.EINVAL, new_file_path)
object_to_rename = old_dir_object.get_entry(old_name)
old_dir_object.remove_entry(old_name, recursive=False)
object_to_rename.name = new_name
new_name = new_dir_object._normalized_entryname(new_name)
if new_name in new_dir_object.contents:
# in case of overwriting remove the old entry first
new_dir_object.remove_entry(new_name)
new_dir_object.add_entry(object_to_rename) | def rename(self, old_file_path, new_file_path, force_replace=False) | Renames a FakeFile object at old_file_path to new_file_path,
preserving all properties.
Args:
old_file_path: Path to filesystem object to rename.
new_file_path: Path to where the filesystem object will live
after this call.
force_replace: If set and destination is an existing file, it
will be replaced even under Windows if the user has
permissions, otherwise replacement happens under Unix only.
Raises:
OSError: if old_file_path does not exist.
OSError: if new_file_path is an existing directory
(Windows, or Posix if old_file_path points to a regular file)
OSError: if old_file_path is a directory and new_file_path a file
OSError: if new_file_path is an existing file and force_replace
not set (Windows only).
OSError: if new_file_path is an existing file and could not be
removed (Posix, or Windows with force_replace set).
OSError: if dirname(new_file_path) does not exist.
OSError: if the file would be moved to another filesystem
(e.g. mount point). | 2.347044 | 2.357952 | 0.995374 |
file_path = self.absnormpath(self._original_path(file_path))
if self._is_root_path(file_path):
self.raise_os_error(errno.EBUSY, file_path)
try:
dirname, basename = self.splitpath(file_path)
target_directory = self.resolve(dirname)
target_directory.remove_entry(basename)
except KeyError:
self.raise_io_error(errno.ENOENT, file_path)
except AttributeError:
self.raise_io_error(errno.ENOTDIR, file_path) | def remove_object(self, file_path) | Remove an existing file or directory.
Args:
file_path: The path to the file relative to self.
Raises:
IOError: if file_path does not correspond to an existing file, or
if part of the path refers to something other than a directory.
OSError: if the directory is in use (eg, if it is '/'). | 3.038493 | 3.113019 | 0.97606 |
directory_path = self.make_string_path(directory_path)
directory_path = self.absnormpath(directory_path)
self._auto_mount_drive_if_needed(directory_path)
if self.exists(directory_path, check_link=True):
self.raise_os_error(errno.EEXIST, directory_path)
path_components = self._path_components(directory_path)
current_dir = self.root
new_dirs = []
for component in path_components:
directory = self._directory_content(current_dir, component)[1]
if not directory:
new_dir = FakeDirectory(component, filesystem=self)
new_dirs.append(new_dir)
current_dir.add_entry(new_dir)
current_dir = new_dir
else:
if S_ISLNK(directory.st_mode):
directory = self.resolve(directory.contents)
current_dir = directory
if directory.st_mode & S_IFDIR != S_IFDIR:
self.raise_os_error(errno.ENOTDIR, current_dir.path)
# set the permission after creating the directories
# to allow directory creation inside a read-only directory
for new_dir in new_dirs:
new_dir.st_mode = S_IFDIR | perm_bits
self._last_ino += 1
current_dir.st_ino = self._last_ino
return current_dir | def create_dir(self, directory_path, perm_bits=PERM_DEF) | Create `directory_path`, and all the parent directories.
Helper method to set up your test faster.
Args:
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. | 3.129259 | 3.215786 | 0.973093 |
return self.create_file_internally(
file_path, st_mode, contents, st_size, create_missing_dirs,
apply_umask, encoding, errors, side_effect=side_effect) | def create_file(self, file_path, st_mode=S_IFREG | PERM_DEF_FILE,
contents='', st_size=None, create_missing_dirs=True,
apply_umask=False, encoding=None, errors=None,
side_effect=None) | Create `file_path`, including all the parent directories along
the way.
This helper method can be used to set up tests more easily.
Args:
file_path: The path to the file to create.
st_mode: The stat constant representing the file type.
contents: the contents of the file. If not given and st_size is
None, an empty file is assumed.
st_size: file size; only valid if contents not given. If given,
the file is considered to be in "large file mode" and trying
to read from or write to the file will result in an exception.
create_missing_dirs: If `True`, auto create missing directories.
apply_umask: `True` if the current umask must be applied
on `st_mode`.
encoding: If `contents` is a unicode string, the encoding used
for serialization.
errors: The error mode used for encoding/decoding errors.
side_effect: function handle that is executed when file is written,
must accept the file object as an argument.
Returns:
The newly created FakeFile object.
Raises:
IOError: if the file already exists.
IOError: if the containing directory is required and missing. | 2.16239 | 3.182322 | 0.679501 |
target_path = target_path or source_path
source_path = make_string_path(source_path)
target_path = self.make_string_path(target_path)
real_stat = os.stat(source_path)
fake_file = self.create_file_internally(target_path,
read_from_real_fs=True)
# for read-only mode, remove the write/executable permission bits
fake_file.stat_result.set_from_stat_result(real_stat)
if read_only:
fake_file.st_mode &= 0o777444
fake_file.file_path = source_path
self.change_disk_usage(fake_file.size, fake_file.name,
fake_file.st_dev)
return fake_file | def add_real_file(self, source_path, read_only=True, target_path=None) | 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.
Args:
source_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.
target_path: If given, the path of the target direction,
otherwise it is equal to `source_path`.
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 most systems, accessing the fake file's contents may
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. | 4.077146 | 4.032969 | 1.010954 |
source_path = self._path_without_trailing_separators(source_path)
if not os.path.exists(source_path):
self.raise_io_error(errno.ENOENT, source_path)
target_path = target_path or source_path
if lazy_read:
parent_path = os.path.split(target_path)[0]
if self.exists(parent_path):
parent_dir = self.get_object(parent_path)
else:
parent_dir = self.create_dir(parent_path)
new_dir = FakeDirectoryFromRealDirectory(
source_path, self, read_only, target_path)
parent_dir.add_entry(new_dir)
self._last_ino += 1
new_dir.st_ino = self._last_ino
else:
new_dir = self.create_dir(target_path)
for base, _, files in os.walk(source_path):
new_base = os.path.join(new_dir.path,
os.path.relpath(base, source_path))
for fileEntry in files:
self.add_real_file(os.path.join(base, fileEntry),
read_only,
os.path.join(new_base, fileEntry))
return new_dir | def add_real_directory(self, source_path, read_only=True, lazy_read=True,
target_path=None) | 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.
Args:
source_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
target_path: If given, the target directory, otherwise,
the target directory is the same as `source_path`.
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. | 2.341354 | 2.410004 | 0.971515 |
for path in path_list:
if os.path.isdir(path):
self.add_real_directory(path, read_only, lazy_dir_read)
else:
self.add_real_file(path, read_only) | def add_real_paths(self, 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()`.
Args:
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. | 1.814133 | 1.961726 | 0.924764 |
error_fct = self.raise_os_error if raw_io else self.raise_io_error
file_path = self.make_string_path(file_path)
file_path = self.absnormpath(file_path)
if not is_int_type(st_mode):
raise TypeError(
'st_mode must be of int type - did you mean to set contents?')
if self.exists(file_path, check_link=True):
self.raise_os_error(errno.EEXIST, file_path)
parent_directory, new_file = self.splitpath(file_path)
if not parent_directory:
parent_directory = self.cwd
self._auto_mount_drive_if_needed(parent_directory)
if not self.exists(parent_directory):
if not create_missing_dirs:
error_fct(errno.ENOENT, parent_directory)
self.create_dir(parent_directory)
else:
parent_directory = self._original_path(parent_directory)
if apply_umask:
st_mode &= ~self.umask
if read_from_real_fs:
file_object = FakeFileFromRealFile(file_path, filesystem=self,
side_effect=side_effect)
else:
file_object = FakeFile(new_file, st_mode, filesystem=self,
encoding=encoding, errors=errors,
side_effect=side_effect)
self._last_ino += 1
file_object.st_ino = self._last_ino
self.add_object(parent_directory, file_object, error_fct)
if st_size is None and contents is None:
contents = ''
if (not read_from_real_fs and
(contents is not None or st_size is not None)):
try:
if st_size is not None:
file_object.set_large_file_size(st_size)
else:
file_object._set_initial_contents(contents)
except IOError:
self.remove_object(file_path)
raise
return file_object | def create_file_internally(self, file_path,
st_mode=S_IFREG | PERM_DEF_FILE,
contents='', st_size=None,
create_missing_dirs=True,
apply_umask=False, encoding=None, errors=None,
read_from_real_fs=False, raw_io=False,
side_effect=None) | Internal fake file creator that supports both normal fake files
and fake files based on real files.
Args:
file_path: path to the file to create.
st_mode: the stat.S_IF constant representing the file type.
contents: the contents of the file. If not given and st_size is
None, an empty file is assumed.
st_size: file size; only valid if contents not given. If given,
the file is considered to be in "large file mode" and trying
to read from or write to the file will result in an exception.
create_missing_dirs: if True, auto create missing directories.
apply_umask: whether or not the current umask must be applied
on st_mode.
encoding: if contents is a unicode string, the encoding used for
serialization.
errors: the error mode used for encoding/decoding errors
read_from_real_fs: if True, the contents are read from the real
file system on demand.
raw_io: `True` if called from low-level API (`os.open`)
side_effect: function handle that is executed when file is written,
must accept the file object as an argument. | 2.874638 | 2.86289 | 1.004104 |
if not self._is_link_supported():
raise OSError("Symbolic links are not supported "
"on Windows before Python 3.2")
# the link path cannot end with a path separator
file_path = self.make_string_path(file_path)
link_target = self.make_string_path(link_target)
file_path = self.normcase(file_path)
if self.ends_with_path_separator(file_path):
if self.exists(file_path):
self.raise_os_error(errno.EEXIST, file_path)
if self.exists(link_target):
if not self.is_windows_fs:
self.raise_os_error(errno.ENOENT, file_path)
else:
if self.is_windows_fs:
self.raise_os_error(errno.EINVAL, link_target)
if not self.exists(
self._path_without_trailing_separators(file_path),
check_link=True):
self.raise_os_error(errno.ENOENT, link_target)
if self.is_macos:
# to avoid EEXIST exception, remove the link
# if it already exists
if self.exists(file_path, check_link=True):
self.remove_object(file_path)
else:
self.raise_os_error(errno.EEXIST, link_target)
# resolve the link path only if it is not a link itself
if not self.islink(file_path):
file_path = self.resolve_path(file_path)
link_target = make_string_path(link_target)
return self.create_file_internally(
file_path, st_mode=S_IFLNK | PERM_DEF,
contents=link_target,
create_missing_dirs=create_missing_dirs,
raw_io=True) | def create_symlink(self, file_path, link_target, create_missing_dirs=True) | Create the specified symlink, pointed at the specified link target.
Args:
file_path: path to the symlink to create
link_target: the target of the symlink
create_missing_dirs: If `True`, any missing parent directories of
file_path will be created
Returns:
The newly created FakeFile object.
Raises:
OSError: if the symlink could not be created
(see :py:meth:`create_file`).
OSError: if on Windows before Python 3.2. | 2.990037 | 2.930587 | 1.020286 |
if not self._is_link_supported():
raise OSError(
"Links are not supported on Windows before Python 3.2")
new_path_normalized = self.absnormpath(new_path)
if self.exists(new_path_normalized, check_link=True):
self.raise_os_error(errno.EEXIST, new_path)
new_parent_directory, new_basename = self.splitpath(
new_path_normalized)
if not new_parent_directory:
new_parent_directory = self.cwd
if not self.exists(new_parent_directory):
self.raise_os_error(errno.ENOENT, new_parent_directory)
if self.ends_with_path_separator(old_path):
error = errno.EINVAL if self.is_windows_fs else errno.ENOTDIR
self.raise_os_error(error, old_path)
if not self.is_windows_fs and self.ends_with_path_separator(new_path):
self.raise_os_error(errno.ENOENT, old_path)
# Retrieve the target file
try:
old_file = self.resolve(old_path)
except IOError:
self.raise_os_error(errno.ENOENT, old_path)
if old_file.st_mode & S_IFDIR:
self.raise_os_error(
errno.EACCES if self.is_windows_fs else errno.EPERM, old_path)
# abuse the name field to control the filename of the
# newly created link
old_file.name = new_basename
self.add_object(new_parent_directory, old_file)
return old_file | def link(self, old_path, new_path) | Create a hard link at new_path, pointing at old_path.
Args:
old_path: An existing link to the target file.
new_path: The destination path to create a new link at.
Returns:
The FakeFile object referred to by old_path.
Raises:
OSError: if something already exists at new_path.
OSError: if old_path is a directory.
OSError: if the parent directory doesn't exist.
OSError: if on Windows before Python 3.2. | 2.822024 | 2.668858 | 1.05739 |
if path is None:
raise TypeError
try:
link_obj = self.lresolve(path)
except IOError as exc:
self.raise_os_error(exc.errno, path)
if S_IFMT(link_obj.st_mode) != S_IFLNK:
self.raise_os_error(errno.EINVAL, path)
if self.ends_with_path_separator(path):
if not self.is_windows_fs and self.exists(path):
self.raise_os_error(errno.EINVAL, path)
if not self.exists(link_obj.path):
if self.is_windows_fs:
error = errno.EINVAL
elif self._is_circular_link(link_obj):
if self.is_macos:
return link_obj.path
error = errno.ELOOP
else:
error = errno.ENOENT
self.raise_os_error(error, link_obj.path)
return link_obj.contents | def readlink(self, path) | Read the target of a symlink.
Args:
path: symlink to read the target of.
Returns:
the string representing the path to which the symbolic link points.
Raises:
TypeError: if path is None
OSError: (with errno=ENOENT) if path is not a valid path, or
(with errno=EINVAL) if path is valid, but is not a symlink,
or if the path ends with a path separator (Posix only) | 2.935302 | 2.97643 | 0.986182 |
dir_name = make_string_path(dir_name)
ends_with_sep = self.ends_with_path_separator(dir_name)
dir_name = self._path_without_trailing_separators(dir_name)
if not dir_name:
self.raise_os_error(errno.ENOENT, '')
if self.is_windows_fs:
dir_name = self.absnormpath(dir_name)
parent_dir, _ = self.splitpath(dir_name)
if parent_dir:
base_dir = self.normpath(parent_dir)
ellipsis = self._matching_string(
parent_dir, self.path_separator + '..')
if parent_dir.endswith(ellipsis) and not self.is_windows_fs:
base_dir, dummy_dotdot, _ = parent_dir.partition(ellipsis)
if not self.exists(base_dir):
self.raise_os_error(errno.ENOENT, base_dir)
dir_name = self.absnormpath(dir_name)
if self.exists(dir_name, check_link=True):
if self.is_windows_fs and dir_name == self.path_separator:
error_nr = errno.EACCES
else:
error_nr = errno.EEXIST
if ends_with_sep and self.is_macos and not self.exists(dir_name):
# to avoid EEXIST exception, remove the link
self.remove_object(dir_name)
else:
self.raise_os_error(error_nr, dir_name)
head, tail = self.splitpath(dir_name)
self.add_object(
head, FakeDirectory(tail, mode & ~self.umask, filesystem=self)) | def makedir(self, dir_name, mode=PERM_DEF) | Create a leaf Fake directory.
Args:
dir_name: (str) Name of directory to create.
Relative paths are assumed to be relative to '/'.
mode: (int) Mode to create directory with. This argument defaults
to 0o777. The umask is applied to this mode.
Raises:
OSError: if the directory name is invalid or parent directory is
read only or as per :py:meth:`add_object`. | 3.542042 | 3.458168 | 1.024254 |
ends_with_sep = self.ends_with_path_separator(dir_name)
dir_name = self.absnormpath(dir_name)
if (ends_with_sep and self.is_macos and
self.exists(dir_name, check_link=True) and
not self.exists(dir_name)):
# to avoid EEXIST exception, remove the link
self.remove_object(dir_name)
path_components = self._path_components(dir_name)
# Raise a permission denied error if the first existing directory
# is not writeable.
current_dir = self.root
for component in path_components:
if (component not in current_dir.contents
or not isinstance(current_dir.contents, dict)):
break
else:
current_dir = current_dir.contents[component]
try:
self.create_dir(dir_name, mode & ~self.umask)
except (IOError, OSError) as e:
if (not exist_ok or
not isinstance(self.resolve(dir_name), FakeDirectory)):
if self.is_windows_fs and e.errno == errno.ENOTDIR:
e.errno = errno.ENOENT
self.raise_os_error(e.errno, e.filename) | def makedirs(self, dir_name, mode=PERM_DEF, exist_ok=False) | Create a leaf Fake directory and create any non-existent
parent dirs.
Args:
dir_name: (str) Name of directory to create.
mode: (int) Mode to create directory (and any necessary parent
directories) with. This argument defaults to 0o777.
The umask is applied to this mode.
exist_ok: (boolean) If exist_ok is False (the default), an OSError is
raised if the target directory already exists.
New in Python 3.2.
Raises:
OSError: if the directory already exists and exist_ok=False,
or as per :py:meth:`create_dir`. | 3.939149 | 3.808972 | 1.034176 |
path = make_string_path(path)
if path is None:
raise TypeError
try:
obj = self.resolve(path, follow_symlinks)
if obj:
self.raise_for_filepath_ending_with_separator(
path, obj, macos_handling=not follow_symlinks)
return S_IFMT(obj.st_mode) == st_flag
except (IOError, OSError):
return False
return False | def _is_of_type(self, path, st_flag, follow_symlinks=True) | Helper function to implement isdir(), islink(), etc.
See the stat(2) man page for valid stat.S_I* flag values
Args:
path: Path to file to stat and test
st_flag: The stat.S_I* flag checked for the file's st_mode
Returns:
(boolean) `True` if the st_flag is set in path's st_mode.
Raises:
TypeError: if path is None | 5.016561 | 6.261273 | 0.801205 |
return self._is_of_type(path, S_IFDIR, follow_symlinks) | def isdir(self, path, follow_symlinks=True) | Determine if path identifies a directory.
Args:
path: Path to filesystem object.
Returns:
`True` if path points to a directory (following symlinks).
Raises:
TypeError: if path is None. | 5.604362 | 9.912016 | 0.565411 |
return self._is_of_type(path, S_IFREG, follow_symlinks) | def isfile(self, path, follow_symlinks=True) | Determine if path identifies a regular file.
Args:
path: Path to filesystem object.
Returns:
`True` if path points to a regular file (following symlinks).
Raises:
TypeError: if path is None. | 5.501225 | 9.558235 | 0.575548 |
try:
directory = self.resolve(target_directory)
except IOError as exc:
self.raise_os_error(exc.errno, target_directory)
if not directory.st_mode & S_IFDIR:
if self.is_windows_fs and IS_PY2:
error_nr = errno.EINVAL
else:
error_nr = errno.ENOTDIR
self.raise_os_error(error_nr, target_directory, 267)
return directory | def confirmdir(self, target_directory) | Test that the target is actually a directory, raising OSError
if not.
Args:
target_directory: Path to the target directory within the fake
filesystem.
Returns:
The FakeDirectory object corresponding to target_directory.
Raises:
OSError: if the target is not a directory. | 4.096989 | 4.243064 | 0.965573 |
norm_path = self.absnormpath(path)
if self.ends_with_path_separator(path):
self._handle_broken_link_with_trailing_sep(norm_path)
if self.exists(norm_path):
obj = self.resolve(norm_path)
if S_IFMT(obj.st_mode) == S_IFDIR:
link_obj = self.lresolve(norm_path)
if S_IFMT(link_obj.st_mode) != S_IFLNK:
if self.is_windows_fs:
error = errno.EACCES
elif self.is_macos:
error = errno.EPERM
else:
error = errno.EISDIR
self.raise_os_error(error, norm_path)
norm_path = make_string_path(norm_path)
if path.endswith(self.path_separator):
if self.is_windows_fs:
error = errno.EACCES
elif self.is_macos:
error = errno.EPERM
else:
error = errno.ENOTDIR
self.raise_os_error(error, norm_path)
else:
self.raise_for_filepath_ending_with_separator(path, obj)
try:
self.remove_object(norm_path)
except IOError as exc:
self.raise_os_error(exc.errno, exc.filename) | def remove(self, path) | Remove the FakeFile object at the specified file path.
Args:
path: Path to file to be removed.
Raises:
OSError: if path points to a directory.
OSError: if path does not exist.
OSError: if removal failed. | 2.909721 | 3.037276 | 0.958003 |
if target_directory in (b'.', u'.'):
error_nr = errno.EACCES if self.is_windows_fs else errno.EINVAL
self.raise_os_error(error_nr, target_directory)
ends_with_sep = self.ends_with_path_separator(target_directory)
target_directory = self.absnormpath(target_directory)
if self.confirmdir(target_directory):
if not self.is_windows_fs and self.islink(target_directory):
if allow_symlink:
return
if not ends_with_sep or not self.is_macos:
self.raise_os_error(errno.ENOTDIR, target_directory)
dir_object = self.resolve(target_directory)
if dir_object.contents:
self.raise_os_error(errno.ENOTEMPTY, target_directory)
try:
self.remove_object(target_directory)
except IOError as exc:
self.raise_os_error(exc.errno, exc.filename) | def rmdir(self, target_directory, allow_symlink=False) | Remove a leaf Fake directory.
Args:
target_directory: (str) Name of directory to remove.
allow_symlink: (bool) if `target_directory` is a symlink,
the function just returns, otherwise it raises (Posix only)
Raises:
OSError: if target_directory does not exist.
OSError: if target_directory does not point to a directory.
OSError: if removal failed per FakeFilesystem.RemoveObject.
Cannot remove '.'. | 3.113236 | 3.158872 | 0.985553 |
target_directory = self.resolve_path(target_directory, allow_fd=True)
directory = self.confirmdir(target_directory)
directory_contents = directory.contents
return list(directory_contents.keys()) | def listdir(self, target_directory) | Return a list of file names in target_directory.
Args:
target_directory: Path to the target directory within the
fake filesystem.
Returns:
A list of file names within the target directory in arbitrary
order.
Raises:
OSError: if the target is not a directory. | 5.52775 | 8.204695 | 0.67373 |
dir = [
'abspath', 'dirname', 'exists', 'expanduser', 'getatime',
'getctime', 'getmtime', 'getsize', 'isabs', 'isdir', 'isfile',
'islink', 'ismount', 'join', 'lexists', 'normcase', 'normpath',
'realpath', 'relpath', 'split', 'splitdrive'
]
if IS_PY2:
dir.append('walk')
if sys.platform != 'win32' or not IS_PY2:
dir.append('samefile')
return dir | def dir() | Return the list of patched function names. Used for patching
functions imported from the module. | 2.676979 | 2.632078 | 1.017059 |
try:
file_obj = self.filesystem.resolve(path)
if (self.filesystem.ends_with_path_separator(path) and
S_IFMT(file_obj.st_mode) != S_IFDIR):
error_nr = (errno.EINVAL if self.filesystem.is_windows_fs
else errno.ENOTDIR)
self.filesystem.raise_os_error(error_nr, path)
return file_obj.st_size
except IOError as exc:
raise os.error(exc.errno, exc.strerror) | def getsize(self, path) | Return the file object size in bytes.
Args:
path: path to the file object.
Returns:
file size in bytes. | 3.600447 | 3.767091 | 0.955763 |
if self.filesystem.is_windows_fs:
path = self.splitdrive(path)[1]
path = make_string_path(path)
sep = self.filesystem._path_separator(path)
altsep = self.filesystem._alternative_path_separator(path)
if self.filesystem.is_windows_fs:
return len(path) > 0 and path[:1] in (sep, altsep)
else:
return (path.startswith(sep) or
altsep is not None and path.startswith(altsep)) | def isabs(self, path) | Return True if path is an absolute pathname. | 3.357527 | 3.294059 | 1.019267 |
try:
file_obj = self.filesystem.resolve(path)
return file_obj.st_mtime
except IOError:
self.filesystem.raise_os_error(errno.ENOENT, winerror=3) | def getmtime(self, path) | Returns the modification time of the fake file.
Args:
path: the path to fake file.
Returns:
(int, float) the modification time of the fake file
in number of seconds since the epoch.
Raises:
OSError: if the file does not exist. | 5.190369 | 6.058887 | 0.856654 |
try:
file_obj = self.filesystem.resolve(path)
except IOError:
self.filesystem.raise_os_error(errno.ENOENT)
return file_obj.st_atime | def getatime(self, path) | Returns the last access time of the fake file.
Note: Access time is not set automatically in fake filesystem
on access.
Args:
path: the path to fake file.
Returns:
(int, float) the access time of the fake file in number of seconds
since the epoch.
Raises:
OSError: if the file does not exist. | 4.127321 | 4.902571 | 0.841869 |
try:
file_obj = self.filesystem.resolve(path)
except IOError:
self.filesystem.raise_os_error(errno.ENOENT)
return file_obj.st_ctime | def getctime(self, path) | Returns the creation time of the fake file.
Args:
path: the path to fake file.
Returns:
(int, float) the creation time of the fake file in number of
seconds since the epoch.
Raises:
OSError: if the file does not exist. | 4.207653 | 5.158571 | 0.815662 |
def getcwd():
# pylint: disable=undefined-variable
if IS_PY2 and isinstance(path, text_type):
return self.os.getcwdu()
elif not IS_PY2 and isinstance(path, bytes):
return self.os.getcwdb()
else:
return self.os.getcwd()
path = make_string_path(path)
sep = self.filesystem._path_separator(path)
altsep = self.filesystem._alternative_path_separator(path)
if not self.isabs(path):
path = self.join(getcwd(), path)
elif (self.filesystem.is_windows_fs and
path.startswith(sep) or altsep is not None and
path.startswith(altsep)):
cwd = getcwd()
if self.filesystem._starts_with_drive_letter(cwd):
path = self.join(cwd[:2], path)
return self.normpath(path) | def abspath(self, path) | Return the absolute version of a path. | 3.18971 | 3.146443 | 1.013751 |
path = self.filesystem.normcase(path)
if self.filesystem.is_windows_fs:
path = path.lower()
return path | def normcase(self, path) | Convert to lower case under windows, replaces additional path
separator. | 4.20464 | 3.960205 | 1.061723 |
if not path:
raise ValueError("no path specified")
path = make_string_path(path)
if start is not None:
start = make_string_path(start)
else:
start = self.filesystem.cwd
if self.filesystem.alternative_path_separator is not None:
path = path.replace(self.filesystem.alternative_path_separator,
self._os_path.sep)
start = start.replace(self.filesystem.alternative_path_separator,
self._os_path.sep)
path = path.replace(self.filesystem.path_separator, self._os_path.sep)
start = start.replace(
self.filesystem.path_separator, self._os_path.sep)
path = self._os_path.relpath(path, start)
return path.replace(self._os_path.sep, self.filesystem.path_separator) | def relpath(self, path, start=None) | We mostly rely on the native implementation and adapt the
path separator. | 1.991519 | 1.971085 | 1.010367 |
if self.filesystem.is_windows_fs:
return self.abspath(filename)
filename = make_string_path(filename)
path, ok = self._joinrealpath(filename[:0], filename, {})
return self.abspath(path) | def realpath(self, filename) | Return the canonical path of the specified filename, eliminating any
symbolic links encountered in the path. | 8.884166 | 8.749492 | 1.015392 |
curdir = self.filesystem._matching_string(path, '.')
pardir = self.filesystem._matching_string(path, '..')
sep = self.filesystem._path_separator(path)
if self.isabs(rest):
rest = rest[1:]
path = sep
while rest:
name, _, rest = rest.partition(sep)
if not name or name == curdir:
# current dir
continue
if name == pardir:
# parent dir
if path:
path, name = self.filesystem.splitpath(path)
if name == pardir:
path = self.filesystem.joinpaths(path, pardir, pardir)
else:
path = pardir
continue
newpath = self.filesystem.joinpaths(path, name)
if not self.filesystem.islink(newpath):
path = newpath
continue
# Resolve the symbolic link
if newpath in seen:
# Already seen this path
path = seen[newpath]
if path is not None:
# use cached value
continue
# The symlink is not resolved, so we must have a symlink loop.
# Return already resolved part + rest of the path unchanged.
return self.filesystem.joinpaths(newpath, rest), False
seen[newpath] = None # not resolved symlink
path, ok = self._joinrealpath(
path, self.filesystem.readlink(newpath), seen)
if not ok:
return self.filesystem.joinpaths(path, rest), False
seen[newpath] = path # resolved symlink
return path, True | def _joinrealpath(self, path, rest, seen) | Join two paths, normalizing and eliminating any symbolic links
encountered in the second path.
Taken from Python source and adapted. | 3.42254 | 3.291976 | 1.039661 |
return self._os_path.expanduser(path).replace(
self._os_path.sep, self.sep) | def expanduser(self, path) | Return the argument with an initial component of ~ or ~user
replaced by that user's home directory. | 4.794312 | 5.764659 | 0.831673 |
path = make_string_path(path)
if not path:
return False
normed_path = self.filesystem.absnormpath(path)
sep = self.filesystem._path_separator(path)
if self.filesystem.is_windows_fs:
if self.filesystem.alternative_path_separator is not None:
path_seps = (
sep, self.filesystem._alternative_path_separator(path)
)
else:
path_seps = (sep, )
drive, rest = self.filesystem.splitdrive(normed_path)
if drive and drive[:1] in path_seps:
return (not rest) or (rest in path_seps)
if rest in path_seps:
return True
for mount_point in self.filesystem.mount_points:
if normed_path.rstrip(sep) == mount_point.rstrip(sep):
return True
return False | def ismount(self, path) | Return true if the given path is a mount point.
Args:
path: Path to filesystem object to be checked
Returns:
`True` if path is a mount point added to the fake file system.
Under Windows also returns True for drive and UNC roots
(independent of their existence). | 3.358984 | 3.404227 | 0.98671 |
dir = [
'access', 'chdir', 'chmod', 'chown', 'close', 'fstat', 'fsync',
'getcwd', 'lchmod', 'link', 'listdir', 'lstat', 'makedirs',
'mkdir', 'mknod', 'open', 'read', 'readlink', 'remove',
'removedirs', 'rename', 'rmdir', 'stat', 'symlink', 'umask',
'unlink', 'utime', 'walk', 'write'
]
if IS_PY2:
dir += ['getcwdu']
else:
dir += ['getcwdb', 'replace']
if sys.platform.startswith('linux'):
dir += [
'fdatasync', 'getxattr', 'listxattr',
'removexattr', 'setxattr'
]
if use_scandir:
dir += ['scandir']
return dir | def dir() | Return the list of patched function names. Used for patching
functions imported from the module. | 2.858774 | 2.814232 | 1.015827 |
if not is_int_type(args[0]):
raise TypeError('an integer is required')
return FakeFileOpen(self.filesystem)(*args, **kwargs) | def _fdopen(self, *args, **kwargs) | Redirector to open() builtin function.
Args:
*args: Pass through args.
**kwargs: Pass through kwargs.
Returns:
File object corresponding to file_des.
Raises:
TypeError: if file descriptor is not an integer. | 8.370149 | 10.921403 | 0.766399 |
raise TypeError('an integer is required')
try:
return FakeFileOpen(self.filesystem).call(file_des, mode=mode)
except IOError as exc:
self.filesystem.raise_os_error(exc.errno, exc.filename) | def _fdopen_ver2(self, file_des, mode='r',
bufsize=None): # pylint: disable=unused-argument
if not is_int_type(file_des) | Returns an open file object connected to the file descriptor
file_des.
Args:
file_des: An integer file descriptor for the file object requested.
mode: Additional file flags. Currently checks to see if the mode
matches the mode of the requested file object.
bufsize: ignored. (Used for signature compliance with
__builtin__.fdopen)
Returns:
File object corresponding to file_des.
Raises:
OSError: if bad file descriptor or incompatible mode is given.
TypeError: if file descriptor is not an integer. | 7.026113 | 7.591384 | 0.925538 |
if self.filesystem.is_windows_fs:
# windows always returns 0 - it has no real notion of umask
return 0
if sys.platform == 'win32':
# if we are testing Unix under Windows we assume a default mask
return 0o002
else:
# under Unix, we return the real umask;
# as there is no pure getter for umask, so we have to first
# set a mode to get the previous one and then re-set that
mask = os.umask(0)
os.umask(mask)
return mask | def _umask(self) | Return the current umask. | 7.737578 | 7.535858 | 1.026768 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.