diff --git a/src/_pytest/_py/error.py b/src/_pytest/_py/error.py index e1e3ccd28af..c427ee5f599 100644 --- a/src/_pytest/_py/error.py +++ b/src/_pytest/_py/error.py @@ -2,41 +2,49 @@ create errno-specific classes for IO or os calls. """ +import errno +import os +import sys from types import ModuleType -import sys, os, errno + class Error(EnvironmentError): def __repr__(self): - return "%s.%s %r: %s " %(self.__class__.__module__, - self.__class__.__name__, - self.__class__.__doc__, - " ".join(map(str, self.args)), - #repr(self.args) - ) + return "{}.{} {!r}: {} ".format( + self.__class__.__module__, + self.__class__.__name__, + self.__class__.__doc__, + " ".join(map(str, self.args)), + # repr(self.args) + ) def __str__(self): - s = "[%s]: %s" %(self.__class__.__doc__, - " ".join(map(str, self.args)), - ) + s = "[{}]: {}".format( + self.__class__.__doc__, + " ".join(map(str, self.args)), + ) return s + _winerrnomap = { 2: errno.ENOENT, 3: errno.ENOENT, 17: errno.EEXIST, 18: errno.EXDEV, - 13: errno.EBUSY, # empty cd drive, but ENOMEDIUM seems unavailiable + 13: errno.EBUSY, # empty cd drive, but ENOMEDIUM seems unavailiable 22: errno.ENOTDIR, 20: errno.ENOTDIR, 267: errno.ENOTDIR, 5: errno.EACCES, # anything better? } + class ErrorMaker(ModuleType): - """ lazily provides Exception classes for each possible POSIX errno - (as defined per the 'errno' module). All such instances - subclass EnvironmentError. + """lazily provides Exception classes for each possible POSIX errno + (as defined per the 'errno' module). All such instances + subclass EnvironmentError. """ + Error = Error _errno2class = {} @@ -52,23 +60,25 @@ def _geterrnoclass(self, eno): try: return self._errno2class[eno] except KeyError: - clsname = errno.errorcode.get(eno, "UnknownErrno%d" %(eno,)) - errorcls = type(Error)(clsname, (Error,), - {'__module__':'py.error', - '__doc__': os.strerror(eno)}) + clsname = errno.errorcode.get(eno, "UnknownErrno%d" % (eno,)) + errorcls = type(Error)( + clsname, + (Error,), + {"__module__": "py.error", "__doc__": os.strerror(eno)}, + ) self._errno2class[eno] = errorcls return errorcls def checked_call(self, func, *args, **kwargs): - """ call a function and raise an errno-exception if applicable. """ + """call a function and raise an errno-exception if applicable.""" __tracebackhide__ = True try: return func(*args, **kwargs) except self.Error: raise - except (OSError, EnvironmentError): + except OSError: cls, value, tb = sys.exc_info() - if not hasattr(value, 'errno'): + if not hasattr(value, "errno"): raise __tracebackhide__ = False errno = value.errno @@ -83,9 +93,9 @@ def checked_call(self, func, *args, **kwargs): cls = self._geterrnoclass(_winerrnomap[errno]) except KeyError: raise value - raise cls("%s%r" % (func.__name__, args)) + raise cls(f"{func.__name__}{args!r}") __tracebackhide__ = True -error = ErrorMaker('_pytest._py.error') +error = ErrorMaker("_pytest._py.error") sys.modules[error.__name__] = error diff --git a/src/_pytest/_py/path.py b/src/_pytest/_py/path.py index e8adbf27a79..0bf27bcfaf4 100644 --- a/src/_pytest/_py/path.py +++ b/src/_pytest/_py/path.py @@ -1,24 +1,31 @@ """ local path implementation. """ -from __future__ import with_statement - -from contextlib import contextmanager -import sys, os, atexit, io, uuid -from stat import S_ISLNK, S_ISDIR, S_ISREG - -from os.path import abspath, normpath, isabs, exists, isdir, isfile, islink, dirname - -import warnings +import atexit +import fnmatch +import io import os -import sys import posixpath -import fnmatch +import sys +import uuid +import warnings +from contextlib import contextmanager +from os.path import abspath +from os.path import dirname +from os.path import exists +from os.path import isabs +from os.path import isdir +from os.path import isfile +from os.path import islink +from os.path import normpath +from stat import S_ISDIR +from stat import S_ISLNK +from stat import S_ISREG from . import error # Moved from local.py. -iswin32 = sys.platform == "win32" or (getattr(os, '_name', False) == 'nt') +iswin32 = sys.platform == "win32" or (getattr(os, "_name", False) == "nt") try: # FileNotFoundError might happen in py34, and is not available with py27. @@ -29,6 +36,7 @@ try: from os import fspath except ImportError: + def fspath(path): """ Return the string representation of the path. @@ -47,7 +55,7 @@ def fspath(path): try: return path_type.__fspath__(path) except AttributeError: - if hasattr(path_type, '__fspath__'): + if hasattr(path_type, "__fspath__"): raise try: import pathlib @@ -57,11 +65,13 @@ def fspath(path): if isinstance(path, pathlib.PurePath): return str(path) - raise TypeError("expected str, bytes or os.PathLike object, not " - + path_type.__name__) + raise TypeError( + "expected str, bytes or os.PathLike object, not " + path_type.__name__ + ) + class Checkers: - _depend_on_existence = 'exists', 'link', 'dir', 'file' + _depend_on_existence = "exists", "link", "dir", "file" def __init__(self, path): self.path = path @@ -73,11 +83,11 @@ def file(self): raise NotImplementedError def dotfile(self): - return self.path.basename.startswith('.') + return self.path.basename.startswith(".") def ext(self, arg): - if not arg.startswith('.'): - arg = '.' + arg + if not arg.startswith("."): + arg = "." + arg return self.path.ext == arg def exists(self): @@ -105,15 +115,14 @@ def _evaluate(self, kw): try: meth = getattr(self, name) except AttributeError: - if name[:3] == 'not': + if name[:3] == "not": invert = True try: meth = getattr(self, name[3:]) except AttributeError: pass if meth is None: - raise TypeError( - "no %r checker available for %r" % (name, self.path)) + raise TypeError(f"no {name!r} checker available for {self.path!r}") try: if py.code.getrawcode(meth).co_argcount > 1: if (not meth(value)) ^ invert: @@ -129,74 +138,78 @@ def _evaluate(self, kw): if name in kw: if kw.get(name): return False - name = 'not' + name + name = "not" + name if name in kw: if not kw.get(name): return False return True + class NeverRaised(Exception): pass -class PathBase(object): - """ shared implementation for filesystem path objects.""" + +class PathBase: + """shared implementation for filesystem path objects.""" + Checkers = Checkers def __div__(self, other): return self.join(fspath(other)) - __truediv__ = __div__ # py3k + + __truediv__ = __div__ # py3k def basename(self): - """ basename part of path. """ - return self._getbyspec('basename')[0] + """basename part of path.""" + return self._getbyspec("basename")[0] + basename = property(basename, None, None, basename.__doc__) def dirname(self): - """ dirname part of path. """ - return self._getbyspec('dirname')[0] + """dirname part of path.""" + return self._getbyspec("dirname")[0] + dirname = property(dirname, None, None, dirname.__doc__) def purebasename(self): - """ pure base name of the path.""" - return self._getbyspec('purebasename')[0] + """pure base name of the path.""" + return self._getbyspec("purebasename")[0] + purebasename = property(purebasename, None, None, purebasename.__doc__) def ext(self): - """ extension of the path (including the '.').""" - return self._getbyspec('ext')[0] + """extension of the path (including the '.').""" + return self._getbyspec("ext")[0] + ext = property(ext, None, None, ext.__doc__) def dirpath(self, *args, **kwargs): - """ return the directory path joined with any given path arguments. """ - return self.new(basename='').join(*args, **kwargs) + """return the directory path joined with any given path arguments.""" + return self.new(basename="").join(*args, **kwargs) def read_binary(self): - """ read and return a bytestring from reading the path. """ - with self.open('rb') as f: + """read and return a bytestring from reading the path.""" + with self.open("rb") as f: return f.read() def read_text(self, encoding): - """ read and return a Unicode string from reading the path. """ + """read and return a Unicode string from reading the path.""" with self.open("r", encoding=encoding) as f: return f.read() - - def read(self, mode='r'): - """ read and return a bytestring from reading the path. """ + def read(self, mode="r"): + """read and return a bytestring from reading the path.""" with self.open(mode) as f: return f.read() def readlines(self, cr=1): - """ read and return a list of lines from the path. if cr is False, the -newline will be removed from the end of each line. """ - if sys.version_info < (3, ): - mode = 'rU' - else: # python 3 deprecates mode "U" in favor of "newline" option - mode = 'r' + """read and return a list of lines from the path. if cr is False, the + newline will be removed from the end of each line.""" + mode = "r" if not cr: content = self.read(mode) - return content.split('\n') + return content.split("\n") else: f = self.open(mode) try: @@ -205,20 +218,19 @@ def readlines(self, cr=1): f.close() def load(self): - """ (deprecated) return object unpickled from self.read() """ - f = self.open('rb') + """(deprecated) return object unpickled from self.read()""" + f = self.open("rb") try: import pickle + return error.checked_call(pickle.load, f) finally: f.close() def move(self, target): - """ move this path to target. """ + """move this path to target.""" if target.relto(self): - raise error.EINVAL( - target, - "cannot move path into a subdirectory of itself") + raise error.EINVAL(target, "cannot move path into a subdirectory of itself") try: self.rename(target) except error.EXDEV: # invalid cross-device link @@ -226,28 +238,28 @@ def move(self, target): self.remove() def __repr__(self): - """ return a string representation of this path. """ + """return a string representation of this path.""" return repr(str(self)) def check(self, **kw): - """ check a path for existence and properties. + """check a path for existence and properties. - Without arguments, return True if the path exists, otherwise False. + Without arguments, return True if the path exists, otherwise False. - valid checkers:: + valid checkers:: - file=1 # is a file - file=0 # is not a file (may not even exist) - dir=1 # is a dir - link=1 # is a link - exists=1 # exists + file=1 # is a file + file=0 # is not a file (may not even exist) + dir=1 # is a dir + link=1 # is a link + exists=1 # exists - You can specify multiple checker definitions, for example:: + You can specify multiple checker definitions, for example:: - path.check(file=1, link=1) # a link pointing to a file + path.check(file=1, link=1) # a link pointing to a file """ if not kw: - kw = {'exists': 1} + kw = {"exists": 1} return self.Checkers(self)._evaluate(kw) def fnmatch(self, pattern): @@ -270,34 +282,33 @@ def fnmatch(self, pattern): return FNMatcher(pattern)(self) def relto(self, relpath): - """ return a string which is the relative part of the path + """return a string which is the relative part of the path to the given 'relpath'. """ if not isinstance(relpath, (str, PathBase)): - raise TypeError("%r: not a string or path object" %(relpath,)) + raise TypeError(f"{relpath!r}: not a string or path object") strrelpath = str(relpath) if strrelpath and strrelpath[-1] != self.sep: strrelpath += self.sep - #assert strrelpath[-1] == self.sep - #assert strrelpath[-2] != self.sep + # assert strrelpath[-1] == self.sep + # assert strrelpath[-2] != self.sep strself = self.strpath - if sys.platform == "win32" or getattr(os, '_name', None) == 'nt': - if os.path.normcase(strself).startswith( - os.path.normcase(strrelpath)): - return strself[len(strrelpath):] + if sys.platform == "win32" or getattr(os, "_name", None) == "nt": + if os.path.normcase(strself).startswith(os.path.normcase(strrelpath)): + return strself[len(strrelpath) :] elif strself.startswith(strrelpath): - return strself[len(strrelpath):] + return strself[len(strrelpath) :] return "" def ensure_dir(self, *args): - """ ensure the path joined with args is a directory. """ + """ensure the path joined with args is a directory.""" return self.ensure(*args, **{"dir": True}) def bestrelpath(self, dest): - """ return a string which is a relative path from self - (assumed to be a directory) to dest such that - self.join(bestrelpath) == dest and if not such - path can be determined return dest. + """return a string which is a relative path from self + (assumed to be a directory) to dest such that + self.join(bestrelpath) == dest and if not such + path can be determined return dest. """ try: if self == dest: @@ -329,8 +340,8 @@ def isfile(self): return self.check(file=1) def parts(self, reverse=False): - """ return a root-first list of all ancestor directories - plus the path itself. + """return a root-first list of all ancestor directories + plus the path itself. """ current = self l = [self] @@ -345,8 +356,8 @@ def parts(self, reverse=False): return l def common(self, other): - """ return the common part shared with the other path - or None if there is no common part. + """return the common part shared with the other path + or None if there is no common part. """ last = None for x, y in zip(self.parts(), other.parts()): @@ -356,15 +367,15 @@ def common(self, other): return last def __add__(self, other): - """ return new path object with 'other' added to the basename""" - return self.new(basename=self.basename+str(other)) + """return new path object with 'other' added to the basename""" + return self.new(basename=self.basename + str(other)) def __cmp__(self, other): - """ return sort value (-1, 0, +1). """ + """return sort value (-1, 0, +1).""" try: return cmp(self.strpath, other.strpath) except AttributeError: - return cmp(str(self), str(other)) # self.path, other.path) + return cmp(str(self), str(other)) # self.path, other.path) def __lt__(self, other): try: @@ -373,50 +384,53 @@ def __lt__(self, other): return str(self) < str(other) def visit(self, fil=None, rec=None, ignore=NeverRaised, bf=False, sort=False): - """ yields all paths below the current one + """yields all paths below the current one - fil is a filter (glob pattern or callable), if not matching the - path will not be yielded, defaulting to None (everything is - returned) + fil is a filter (glob pattern or callable), if not matching the + path will not be yielded, defaulting to None (everything is + returned) - rec is a filter (glob pattern or callable) that controls whether - a node is descended, defaulting to None + rec is a filter (glob pattern or callable) that controls whether + a node is descended, defaulting to None - ignore is an Exception class that is ignoredwhen calling dirlist() - on any of the paths (by default, all exceptions are reported) + ignore is an Exception class that is ignoredwhen calling dirlist() + on any of the paths (by default, all exceptions are reported) - bf if True will cause a breadthfirst search instead of the - default depthfirst. Default: False + bf if True will cause a breadthfirst search instead of the + default depthfirst. Default: False - sort if True will sort entries within each directory level. + sort if True will sort entries within each directory level. """ - for x in Visitor(fil, rec, ignore, bf, sort).gen(self): - yield x + yield from Visitor(fil, rec, ignore, bf, sort).gen(self) def _sortlist(self, res, sort): if sort: - if hasattr(sort, '__call__'): - warnings.warn(DeprecationWarning( - "listdir(sort=callable) is deprecated and breaks on python3" - ), stacklevel=3) + if hasattr(sort, "__call__"): + warnings.warn( + DeprecationWarning( + "listdir(sort=callable) is deprecated and breaks on python3" + ), + stacklevel=3, + ) res.sort(sort) else: res.sort() def samefile(self, other): - """ return True if other refers to the same stat object as self. """ + """return True if other refers to the same stat object as self.""" return self.strpath == str(other) def __fspath__(self): return self.strpath + class Visitor: def __init__(self, fil, rec, ignore, bf, sort): if isinstance(fil, py.builtin._basestring): fil = FNMatcher(fil) if isinstance(rec, py.builtin._basestring): self.rec = FNMatcher(rec) - elif not hasattr(rec, '__call__') and rec: + elif not hasattr(rec, "__call__") and rec: self.rec = lambda path: True else: self.rec = rec @@ -431,8 +445,9 @@ def gen(self, path): except self.ignore: return rec = self.rec - dirs = self.optsort([p for p in entries - if p.check(dir=1) and (rec is None or rec(p))]) + dirs = self.optsort( + [p for p in entries if p.check(dir=1) and (rec is None or rec(p))] + ) if not self.breadthfirst: for subdir in dirs: for p in self.gen(subdir): @@ -445,6 +460,7 @@ def gen(self, path): for p in self.gen(subdir): yield p + class FNMatcher: def __init__(self, pattern): self.pattern = pattern @@ -452,9 +468,11 @@ def __init__(self, pattern): def __call__(self, path): pattern = self.pattern - if (pattern.find(path.sep) == -1 and - iswin32 and - pattern.find(posixpath.sep) != -1): + if ( + pattern.find(path.sep) == -1 + and iswin32 + and pattern.find(posixpath.sep) != -1 + ): # Running on Windows, the pattern has no Windows path separators, # and the pattern has one or more Posix path separators. Replace # the Posix path separators with the Windows path separator. @@ -463,24 +481,22 @@ def __call__(self, path): if pattern.find(path.sep) == -1: name = path.basename else: - name = str(path) # path.strpath # XXX svn? + name = str(path) # path.strpath # XXX svn? if not os.path.isabs(pattern): - pattern = '*' + path.sep + pattern + pattern = "*" + path.sep + pattern return fnmatch.fnmatch(name, pattern) -if sys.version_info > (3,0): - def map_as_list(func, iter): - return list(map(func, iter)) -else: - map_as_list = map +def map_as_list(func, iter): + return list(map(func, iter)) -ALLOW_IMPORTLIB_MODE = sys.version_info > (3,5) + +ALLOW_IMPORTLIB_MODE = sys.version_info > (3, 5) if ALLOW_IMPORTLIB_MODE: import importlib -class Stat(object): +class Stat: def __getattr__(self, name): return getattr(self._osstatresult, "st_" + name) @@ -493,15 +509,17 @@ def owner(self): if iswin32: raise NotImplementedError("XXX win32") import pwd + entry = error.checked_call(pwd.getpwuid, self.uid) return entry[0] @property def group(self): - """ return group name of file. """ + """return group name of file.""" if iswin32: raise NotImplementedError("XXX win32") import grp + entry = error.checked_call(grp.getgrgid, self.gid) return entry[0] @@ -512,15 +530,16 @@ def isfile(self): return S_ISREG(self._osstatresult.st_mode) def islink(self): - st = self.path.lstat() + self.path.lstat() return S_ISLNK(self._osstatresult.st_mode) + class PosixPath(PathBase): def chown(self, user, group, rec=0): - """ change ownership to the given user and group. - user and group may be specified by a number or - by a name. if rec is True change ownership - recursively. + """change ownership to the given user and group. + user and group may be specified by a number or + by a name. if rec is True change ownership + recursively. """ uid = getuserid(user) gid = getgroupid(group) @@ -531,15 +550,15 @@ def chown(self, user, group, rec=0): error.checked_call(os.chown, str(self), uid, gid) def readlink(self): - """ return value of a symbolic link. """ + """return value of a symbolic link.""" return error.checked_call(os.readlink, self.strpath) def mklinkto(self, oldname): - """ posix style hard link to another name. """ + """posix style hard link to another name.""" error.checked_call(os.link, str(oldname), str(self)) def mksymlinkto(self, value, absolute=1): - """ create a symbolic link with the given value (pointing to another name). """ + """create a symbolic link with the given value (pointing to another name).""" if absolute: error.checked_call(os.symlink, str(value), self.strpath) else: @@ -548,31 +567,39 @@ def mksymlinkto(self, value, absolute=1): relsource = self.__class__(value).relto(base) reldest = self.relto(base) n = reldest.count(self.sep) - target = self.sep.join(('..', )*n + (relsource, )) + target = self.sep.join(("..",) * n + (relsource,)) error.checked_call(os.symlink, target, self.strpath) + def getuserid(user): import pwd + if not isinstance(user, int): user = pwd.getpwnam(user)[2] return user + def getgroupid(group): import grp + if not isinstance(group, int): group = grp.getgrnam(group)[2] return group + FSBase = not iswin32 and PosixPath or PathBase + class LocalPath(FSBase): - """ object oriented interface to os.path and other local filesystem - related information. + """object oriented interface to os.path and other local filesystem + related information. """ + class ImportMismatchError(ImportError): - """ raised on pyimport() if there is a mismatch of __file__'s""" + """raised on pyimport() if there is a mismatch of __file__'s""" sep = os.sep + class Checkers(Checkers): def _stat(self): try: @@ -598,7 +625,7 @@ def link(self): return S_ISLNK(st.mode) def __init__(self, path=None, expanduser=False): - """ Initialize and return a local Path instance. + """Initialize and return a local Path instance. Path can be relative to the current directory. If path is None it defaults to the current working directory. @@ -613,8 +640,10 @@ def __init__(self, path=None, expanduser=False): try: path = fspath(path) except TypeError: - raise ValueError("can only pass None, Path instances " - "or non-empty strings to LocalPath") + raise ValueError( + "can only pass None, Path instances " + "or non-empty strings to LocalPath" + ) if expanduser: path = os.path.expanduser(path) self.strpath = abspath(path) @@ -649,8 +678,7 @@ def __gt__(self, other): return fspath(self) > fspath(other) def samefile(self, other): - """ return True if 'other' references the same file as 'self'. - """ + """return True if 'other' references the same file as 'self'.""" other = fspath(other) if not isabs(other): other = abspath(other) @@ -658,11 +686,10 @@ def samefile(self, other): return True if not hasattr(os.path, "samefile"): return False - return error.checked_call( - os.path.samefile, self.strpath, other) + return error.checked_call(os.path.samefile, self.strpath, other) def remove(self, rec=1, ignore_errors=False): - """ remove a file or directory (or a directory tree if rec=1). + """remove a file or directory (or a directory tree if rec=1). if ignore_errors is True, errors while removing directories will be ignored. """ @@ -672,9 +699,10 @@ def remove(self, rec=1, ignore_errors=False): if iswin32: self.chmod(0o700, rec=1) import shutil + error.checked_call( - shutil.rmtree, self.strpath, - ignore_errors=ignore_errors) + shutil.rmtree, self.strpath, ignore_errors=ignore_errors + ) else: error.checked_call(os.rmdir, self.strpath) else: @@ -683,7 +711,7 @@ def remove(self, rec=1, ignore_errors=False): error.checked_call(os.remove, self.strpath) def computehash(self, hashtype="md5", chunksize=524288): - """ return hexdigest of hashvalue for this file. """ + """return hexdigest of hashvalue for this file.""" try: try: import hashlib as mod @@ -693,8 +721,8 @@ def computehash(self, hashtype="md5", chunksize=524288): mod = __import__(hashtype) hash = getattr(mod, hashtype)() except (AttributeError, ImportError): - raise ValueError("Don't know how to compute %r hash" %(hashtype,)) - f = self.open('rb') + raise ValueError(f"Don't know how to compute {hashtype!r} hash") + f = self.open("rb") try: while 1: buf = f.read(chunksize) @@ -705,94 +733,94 @@ def computehash(self, hashtype="md5", chunksize=524288): f.close() def new(self, **kw): - """ create a modified version of this path. - the following keyword arguments modify various path parts:: - - a:/some/path/to/a/file.ext - xx drive - xxxxxxxxxxxxxxxxx dirname - xxxxxxxx basename - xxxx purebasename - xxx ext + """create a modified version of this path. + the following keyword arguments modify various path parts:: + + a:/some/path/to/a/file.ext + xx drive + xxxxxxxxxxxxxxxxx dirname + xxxxxxxx basename + xxxx purebasename + xxx ext """ obj = object.__new__(self.__class__) if not kw: obj.strpath = self.strpath return obj - drive, dirname, basename, purebasename,ext = self._getbyspec( - "drive,dirname,basename,purebasename,ext") - if 'basename' in kw: - if 'purebasename' in kw or 'ext' in kw: + drive, dirname, basename, purebasename, ext = self._getbyspec( + "drive,dirname,basename,purebasename,ext" + ) + if "basename" in kw: + if "purebasename" in kw or "ext" in kw: raise ValueError("invalid specification %r" % kw) else: - pb = kw.setdefault('purebasename', purebasename) + pb = kw.setdefault("purebasename", purebasename) try: - ext = kw['ext'] + ext = kw["ext"] except KeyError: pass else: - if ext and not ext.startswith('.'): - ext = '.' + ext - kw['basename'] = pb + ext + if ext and not ext.startswith("."): + ext = "." + ext + kw["basename"] = pb + ext - if ('dirname' in kw and not kw['dirname']): - kw['dirname'] = drive + if "dirname" in kw and not kw["dirname"]: + kw["dirname"] = drive else: - kw.setdefault('dirname', dirname) - kw.setdefault('sep', self.sep) - obj.strpath = normpath( - "%(dirname)s%(sep)s%(basename)s" % kw) + kw.setdefault("dirname", dirname) + kw.setdefault("sep", self.sep) + obj.strpath = normpath("%(dirname)s%(sep)s%(basename)s" % kw) return obj def _getbyspec(self, spec): - """ see new for what 'spec' can be. """ + """see new for what 'spec' can be.""" res = [] parts = self.strpath.split(self.sep) - args = filter(None, spec.split(',') ) + args = filter(None, spec.split(",")) append = res.append for name in args: - if name == 'drive': + if name == "drive": append(parts[0]) - elif name == 'dirname': + elif name == "dirname": append(self.sep.join(parts[:-1])) else: basename = parts[-1] - if name == 'basename': + if name == "basename": append(basename) else: - i = basename.rfind('.') + i = basename.rfind(".") if i == -1: - purebasename, ext = basename, '' + purebasename, ext = basename, "" else: purebasename, ext = basename[:i], basename[i:] - if name == 'purebasename': + if name == "purebasename": append(purebasename) - elif name == 'ext': + elif name == "ext": append(ext) else: raise ValueError("invalid part specification %r" % name) return res def dirpath(self, *args, **kwargs): - """ return the directory path joined with any given path arguments. """ + """return the directory path joined with any given path arguments.""" if not kwargs: path = object.__new__(self.__class__) path.strpath = dirname(self.strpath) if args: path = path.join(*args) return path - return super(LocalPath, self).dirpath(*args, **kwargs) + return super().dirpath(*args, **kwargs) def join(self, *args, **kwargs): - """ return a new path by appending all 'args' as path + """return a new path by appending all 'args' as path components. if abs=1 is used restart from root if any of the args is an absolute path. """ sep = self.sep strargs = [fspath(arg) for arg in args] strpath = self.strpath - if kwargs.get('abs'): + if kwargs.get("abs"): newargs = [] for arg in reversed(strargs): if isabs(arg): @@ -806,16 +834,16 @@ def join(self, *args, **kwargs): arg = arg.strip(sep) if iswin32: # allow unix style paths even on windows. - arg = arg.strip('/') - arg = arg.replace('/', sep) + arg = arg.strip("/") + arg = arg.replace("/", sep) strpath = strpath + actual_sep + arg actual_sep = sep obj = object.__new__(self.__class__) obj.strpath = normpath(strpath) return obj - def open(self, mode='r', ensure=False, encoding=None): - """ return an opened file with the given mode. + def open(self, mode="r", ensure=False, encoding=None): + """return an opened file with the given mode. If ensure is True, create parent directories if needed. """ @@ -841,12 +869,13 @@ def check(self, **kw): return not kw["dir"] ^ isdir(self.strpath) if "file" in kw: return not kw["file"] ^ isfile(self.strpath) - return super(LocalPath, self).check(**kw) + return super().check(**kw) _patternchars = set("*?[" + os.path.sep) + def listdir(self, fil=None, sort=None): - """ list directory contents, possibly filter by the given fil func - and possibly sorted. + """list directory contents, possibly filter by the given fil func + and possibly sorted. """ if fil is None and sort is None: names = error.checked_call(os.listdir, self.strpath) @@ -868,32 +897,34 @@ def listdir(self, fil=None, sort=None): return res def size(self): - """ return size of the underlying file object """ + """return size of the underlying file object""" return self.stat().size def mtime(self): - """ return last modification time of the path. """ + """return last modification time of the path.""" return self.stat().mtime def copy(self, target, mode=False, stat=False): - """ copy path to target. + """copy path to target. - If mode is True, will copy copy permission from path to target. - If stat is True, copy permission, last modification - time, last access time, and flags from path to target. + If mode is True, will copy copy permission from path to target. + If stat is True, copy permission, last modification + time, last access time, and flags from path to target. """ if self.check(file=1): if target.check(dir=1): target = target.join(self.basename) - assert self!=target + assert self != target copychunked(self, target) if mode: copymode(self.strpath, target.strpath) if stat: copystat(self, target) else: + def rec(p): return p.check(link=0) + for x in self.visit(rec=rec): relpath = x.relto(self) newx = target.join(relpath) @@ -911,50 +942,51 @@ def rec(p): copystat(x, newx) def rename(self, target): - """ rename this path to target. """ + """rename this path to target.""" target = fspath(target) return error.checked_call(os.rename, self.strpath, target) def dump(self, obj, bin=1): - """ pickle object into path location""" - f = self.open('wb') + """pickle object into path location""" + f = self.open("wb") import pickle + try: error.checked_call(pickle.dump, obj, f, bin) finally: f.close() def mkdir(self, *args): - """ create & return the directory joined with args. """ + """create & return the directory joined with args.""" p = self.join(*args) error.checked_call(os.mkdir, fspath(p)) return p def write_binary(self, data, ensure=False): - """ write binary data into path. If ensure is True create + """write binary data into path. If ensure is True create missing parent directories. """ if ensure: self.dirpath().ensure(dir=1) - with self.open('wb') as f: + with self.open("wb") as f: f.write(data) def write_text(self, data, encoding, ensure=False): - """ write text data into path using the specified encoding. + """write text data into path using the specified encoding. If ensure is True create missing parent directories. """ if ensure: self.dirpath().ensure(dir=1) - with self.open('w', encoding=encoding) as f: + with self.open("w", encoding=encoding) as f: f.write(data) - def write(self, data, mode='w', ensure=False): - """ write data into path. If ensure is True create + def write(self, data, mode="w", ensure=False): + """write data into path. If ensure is True create missing parent directories. """ if ensure: self.dirpath().ensure(dir=1) - if 'b' in mode: + if "b" in mode: if not py.builtin._isbytes(data): raise ValueError("can only process bytes") else: @@ -986,21 +1018,21 @@ def _ensuredirs(self): return self def ensure(self, *args, **kwargs): - """ ensure that an args-joined path exists (by default as - a file). if you specify a keyword argument 'dir=True' - then the path is forced to be a directory path. + """ensure that an args-joined path exists (by default as + a file). if you specify a keyword argument 'dir=True' + then the path is forced to be a directory path. """ p = self.join(*args) - if kwargs.get('dir', 0): + if kwargs.get("dir", 0): return p._ensuredirs() else: p.dirpath()._ensuredirs() if not p.check(file=1): - p.open('w').close() + p.open("w").close() return p def stat(self, raising=True): - """ Return an os.stat() tuple. """ + """Return an os.stat() tuple.""" if raising == True: return Stat(self, error.checked_call(os.stat, self.strpath)) try: @@ -1011,11 +1043,11 @@ def stat(self, raising=True): return None def lstat(self): - """ Return an os.lstat() tuple. """ + """Return an os.lstat() tuple.""" return Stat(self, error.checked_call(os.lstat, self.strpath)) def setmtime(self, mtime=None): - """ set modification time for the given path. if 'mtime' is None + """set modification time for the given path. if 'mtime' is None (the default) then the file's mtime is set to current time. Note that the resolution for 'mtime' is platform dependent. @@ -1028,7 +1060,7 @@ def setmtime(self, mtime=None): return error.checked_call(os.utime, self.strpath, (self.atime(), mtime)) def chdir(self): - """ change directory to self and return old current directory """ + """change directory to self and return old current directory""" try: old = self.__class__() except error.ENOENT: @@ -1036,7 +1068,6 @@ def chdir(self): error.checked_call(os.chdir, self.strpath) return old - @contextmanager def as_cwd(self): """ @@ -1052,41 +1083,41 @@ def as_cwd(self): old.chdir() def realpath(self): - """ return a new path which contains no symbolic links.""" + """return a new path which contains no symbolic links.""" return self.__class__(os.path.realpath(self.strpath)) def atime(self): - """ return last access time of the path. """ + """return last access time of the path.""" return self.stat().atime def __repr__(self): - return 'local(%r)' % self.strpath + return "local(%r)" % self.strpath def __str__(self): - """ return string representation of the Path. """ + """return string representation of the Path.""" return self.strpath def chmod(self, mode, rec=0): - """ change permissions to the given mode. If mode is an - integer it directly encodes the os-specific modes. - if rec is True perform recursively. + """change permissions to the given mode. If mode is an + integer it directly encodes the os-specific modes. + if rec is True perform recursively. """ if not isinstance(mode, int): - raise TypeError("mode %r must be an integer" % (mode,)) + raise TypeError(f"mode {mode!r} must be an integer") if rec: for x in self.visit(rec=rec): error.checked_call(os.chmod, str(x), mode) error.checked_call(os.chmod, self.strpath, mode) def pypkgpath(self): - """ return the Python package path by looking for the last + """return the Python package path by looking for the last directory upwards which still contains an __init__.py. Return None if a pkgpath can not be determined. """ pkgpath = None for parent in self.parts(reverse=True): if parent.isdir(): - if not parent.join('__init__.py').exists(): + if not parent.join("__init__.py").exists(): break if not isimportable(parent.basename): break @@ -1104,7 +1135,7 @@ def _ensuresyspath(self, ensuremode, path): sys.path.insert(0, s) def pyimport(self, modname=None, ensuresyspath=True): - """ return path as an imported python module. + """return path as an imported python module. If modname is None, look for the containing package and construct an according module name. @@ -1127,18 +1158,15 @@ def pyimport(self, modname=None, ensuresyspath=True): if not self.check(): raise error.ENOENT(self) - if ensuresyspath == 'importlib': + if ensuresyspath == "importlib": if modname is None: modname = self.purebasename if not ALLOW_IMPORTLIB_MODE: - raise ImportError( - "Can't use importlib due to old version of Python") - spec = importlib.util.spec_from_file_location( - modname, str(self)) + raise ImportError("Can't use importlib due to old version of Python") + spec = importlib.util.spec_from_file_location(modname, str(self)) if spec is None: raise ImportError( - "Can't find module %s at location %s" % - (modname, str(self)) + f"Can't find module {modname} at location {str(self)}" ) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) @@ -1161,13 +1189,13 @@ def pyimport(self, modname=None, ensuresyspath=True): __import__(modname) mod = sys.modules[modname] if self.basename == "__init__.py": - return mod # we don't check anything as we might - # be in a namespace package ... too icky to check + return mod # we don't check anything as we might + # be in a namespace package ... too icky to check modfile = mod.__file__ - if modfile[-4:] in ('.pyc', '.pyo'): + if modfile[-4:] in (".pyc", ".pyo"): modfile = modfile[:-1] - elif modfile.endswith('$py.class'): - modfile = modfile[:-9] + '.py' + elif modfile.endswith("$py.class"): + modfile = modfile[:-9] + ".py" if modfile.endswith(os.path.sep + "__init__.py"): if self.basename != "__init__.py": modfile = modfile[:-12] @@ -1176,8 +1204,8 @@ def pyimport(self, modname=None, ensuresyspath=True): except error.ENOENT: issame = False if not issame: - ignore = os.getenv('PY_IGNORE_IMPORTMISMATCH') - if ignore != '1': + ignore = os.getenv("PY_IGNORE_IMPORTMISMATCH") + if ignore != "1": raise self.ImportMismatchError(modname, modfile, self) return mod else: @@ -1186,6 +1214,7 @@ def pyimport(self, modname=None, ensuresyspath=True): except KeyError: # we have a custom modname, do a pseudo-import import types + mod = types.ModuleType(modname) mod.__file__ = str(self) sys.modules[modname] = mod @@ -1197,13 +1226,14 @@ def pyimport(self, modname=None, ensuresyspath=True): return mod def sysexec(self, *argv, **popen_opts): - """ return stdout text from executing a system child process, - where the 'self' path points to executable. - The process is directly invoked and not through a system shell. + """return stdout text from executing a system child process, + where the 'self' path points to executable. + The process is directly invoked and not through a system shell. """ from subprocess import Popen, PIPE + argv = map_as_list(str, argv) - popen_opts['stdout'] = popen_opts['stderr'] = PIPE + popen_opts["stdout"] = popen_opts["stderr"] = PIPE proc = Popen([str(self)] + argv, **popen_opts) stdout, stderr = proc.communicate() ret = proc.wait() @@ -1212,17 +1242,22 @@ def sysexec(self, *argv, **popen_opts): if ret != 0: if py.builtin._isbytes(stderr): stderr = py.builtin._totext(stderr, sys.getdefaultencoding()) - raise py.process.cmdexec.Error(ret, ret, str(self), - stdout, stderr,) + raise py.process.cmdexec.Error( + ret, + ret, + str(self), + stdout, + stderr, + ) return stdout def sysfind(cls, name, checker=None, paths=None): - """ return a path object found by looking at the systems - underlying PATH specification. If the checker is not None - it will be invoked to filter matching paths. If a binary - cannot be found, None is returned - Note: This is probably not working on plain win32 systems - but may work on cygwin. + """return a path object found by looking at the systems + underlying PATH specification. If the checker is not None + it will be invoked to filter matching paths. If a binary + cannot be found, None is returned + Note: This is probably not working on plain win32 systems + but may work on cygwin. """ if isabs(name): p = py.path.local(name) @@ -1231,21 +1266,22 @@ def sysfind(cls, name, checker=None, paths=None): else: if paths is None: if iswin32: - paths = os.environ['Path'].split(';') - if '' not in paths and '.' not in paths: - paths.append('.') + paths = os.environ["Path"].split(";") + if "" not in paths and "." not in paths: + paths.append(".") try: - systemroot = os.environ['SYSTEMROOT'] + systemroot = os.environ["SYSTEMROOT"] except KeyError: pass else: - paths = [path.replace('%SystemRoot%', systemroot) - for path in paths] + paths = [ + path.replace("%SystemRoot%", systemroot) for path in paths + ] else: - paths = os.environ['PATH'].split(':') + paths = os.environ["PATH"].split(":") tryadd = [] if iswin32: - tryadd += os.environ['PATHEXT'].split(os.pathsep) + tryadd += os.environ["PATHEXT"].split(os.pathsep) tryadd.append("") for x in paths: @@ -1260,17 +1296,19 @@ def sysfind(cls, name, checker=None, paths=None): except error.EACCES: pass return None + sysfind = classmethod(sysfind) def _gethomedir(cls): try: - x = os.environ['HOME'] + x = os.environ["HOME"] except KeyError: try: - x = os.environ["HOMEDRIVE"] + os.environ['HOMEPATH'] + x = os.environ["HOMEDRIVE"] + os.environ["HOMEPATH"] except KeyError: return None return cls(x) + _gethomedir = classmethod(_gethomedir) # """ @@ -1278,58 +1316,65 @@ def _gethomedir(cls): # """ @classmethod def get_temproot(cls): - """ return the system's temporary directory - (where tempfiles are usually created in) + """return the system's temporary directory + (where tempfiles are usually created in) """ import tempfile + return py.path.local(tempfile.gettempdir()) @classmethod def mkdtemp(cls, rootdir=None): - """ return a Path object pointing to a fresh new temporary directory - (which we created ourself). + """return a Path object pointing to a fresh new temporary directory + (which we created ourself). """ import tempfile + if rootdir is None: rootdir = cls.get_temproot() return cls(error.checked_call(tempfile.mkdtemp, dir=str(rootdir))) - def make_numbered_dir(cls, prefix='session-', rootdir=None, keep=3, - lock_timeout=172800): # two days - """ return unique directory with a number greater than the current - maximum one. The number is assumed to start directly after prefix. - if keep is true directories with a number less than (maxnum-keep) - will be removed. If .lock files are used (lock_timeout non-zero), - algorithm is multi-process safe. + def make_numbered_dir( + cls, prefix="session-", rootdir=None, keep=3, lock_timeout=172800 + ): # two days + """return unique directory with a number greater than the current + maximum one. The number is assumed to start directly after prefix. + if keep is true directories with a number less than (maxnum-keep) + will be removed. If .lock files are used (lock_timeout non-zero), + algorithm is multi-process safe. """ if rootdir is None: rootdir = cls.get_temproot() nprefix = prefix.lower() + def parse_num(path): - """ parse the number out of a path (if it matches the prefix) """ + """parse the number out of a path (if it matches the prefix)""" nbasename = path.basename.lower() if nbasename.startswith(nprefix): try: - return int(nbasename[len(nprefix):]) + return int(nbasename[len(nprefix) :]) except ValueError: pass def create_lockfile(path): - """ exclusively create lockfile. Throws when failed """ + """exclusively create lockfile. Throws when failed""" mypid = os.getpid() - lockfile = path.join('.lock') - if hasattr(lockfile, 'mksymlinkto'): + lockfile = path.join(".lock") + if hasattr(lockfile, "mksymlinkto"): lockfile.mksymlinkto(str(mypid)) else: - fd = error.checked_call(os.open, str(lockfile), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644) - with os.fdopen(fd, 'w') as f: + fd = error.checked_call( + os.open, str(lockfile), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644 + ) + with os.fdopen(fd, "w") as f: f.write(str(mypid)) return lockfile def atexit_remove_lockfile(lockfile): - """ ensure lockfile is removed at process exit """ + """ensure lockfile is removed at process exit""" mypid = os.getpid() + def try_remove_lockfile(): # in a fork() situation, only the last process should # remove the .lock, otherwise the other processes run the @@ -1342,6 +1387,7 @@ def try_remove_lockfile(): lockfile.remove() except error.Error: pass + atexit.register(try_remove_lockfile) # compute the maximum number currently in use with the prefix @@ -1355,7 +1401,7 @@ def try_remove_lockfile(): # make the new directory try: - udir = rootdir.mkdir(prefix + str(maxnum+1)) + udir = rootdir.mkdir(prefix + str(maxnum + 1)) if lock_timeout: lockfile = create_lockfile(udir) atexit_remove_lockfile(lockfile) @@ -1375,16 +1421,16 @@ def try_remove_lockfile(): break def get_mtime(path): - """ read file modification time """ + """read file modification time""" try: return path.lstat().mtime except error.Error: pass - garbage_prefix = prefix + 'garbage-' + garbage_prefix = prefix + "garbage-" def is_garbage(path): - """ check if path denotes directory scheduled for removal """ + """check if path denotes directory scheduled for removal""" bn = path.basename return bn.startswith(garbage_prefix) @@ -1417,27 +1463,27 @@ def is_garbage(path): garbage_path.remove(rec=1) except KeyboardInterrupt: raise - except: # this might be error.Error, WindowsError ... + except: # this might be error.Error, WindowsError ... pass if is_garbage(path): try: path.remove(rec=1) except KeyboardInterrupt: raise - except: # this might be error.Error, WindowsError ... + except: # this might be error.Error, WindowsError ... pass # make link... try: - username = os.environ['USER'] #linux, et al + username = os.environ["USER"] # linux, et al except KeyError: try: - username = os.environ['USERNAME'] #windows + username = os.environ["USERNAME"] # windows except KeyError: - username = 'current' + username = "current" - src = str(udir) - dest = src[:src.rfind('-')] + '-' + username + src = str(udir) + dest = src[: src.rfind("-")] + "-" + username try: os.unlink(dest) except OSError: @@ -1448,27 +1494,30 @@ def is_garbage(path): pass return udir + make_numbered_dir = classmethod(make_numbered_dir) def copymode(src, dest): - """ copy permission from src to dst. """ + """copy permission from src to dst.""" import shutil + shutil.copymode(src, dest) def copystat(src, dest): - """ copy permission, last modification time, + """copy permission, last modification time, last access time, and flags from src to dst.""" import shutil + shutil.copystat(str(src), str(dest)) def copychunked(src, dest): chunksize = 524288 # half a meg of bytes - fsrc = src.open('rb') + fsrc = src.open("rb") try: - fdest = dest.open('wb') + fdest = dest.open("wb") try: while 1: buf = fsrc.read(chunksize) @@ -1482,8 +1531,9 @@ def copychunked(src, dest): def isimportable(name): - if name and (name[0].isalpha() or name[0] == '_'): - name = name.replace("_", '') + if name and (name[0].isalpha() or name[0] == "_"): + name = name.replace("_", "") return not name or name.isalnum() + local = LocalPath diff --git a/src/_pytest/compat.py b/src/_pytest/compat.py index fab4c31107f..211407b2374 100644 --- a/src/_pytest/compat.py +++ b/src/_pytest/compat.py @@ -18,6 +18,7 @@ from typing import Union import attr + import py # fmt: off diff --git a/src/py.py b/src/py.py index c4f049e360f..7813c9b93cd 100644 --- a/src/py.py +++ b/src/py.py @@ -6,5 +6,5 @@ import _pytest._py.error as error import _pytest._py.path as path -sys.modules['py.error'] = error -sys.modules['py.path'] = path +sys.modules["py.error"] = error +sys.modules["py.path"] = path