Skip to content

Commit

Permalink
Some py.path.local -> pathlib.Path
Browse files Browse the repository at this point in the history
  • Loading branch information
bluetech committed Dec 14, 2020
1 parent cb8142b commit 1620b3d
Show file tree
Hide file tree
Showing 9 changed files with 81 additions and 87 deletions.
4 changes: 1 addition & 3 deletions src/_pytest/assertion/rewrite.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,6 @@
from typing import TYPE_CHECKING
from typing import Union

import py

from _pytest._io.saferepr import saferepr
from _pytest._version import version
from _pytest.assertion import util
Expand Down Expand Up @@ -215,7 +213,7 @@ def _should_rewrite(self, name: str, fn: str, state: "AssertionState") -> bool:
return True

if self.session is not None:
if self.session.isinitpath(py.path.local(fn)):
if self.session.isinitpath(fn):
state.trace(f"matched test file (was specified on cmdline): {fn!r}")
return True

Expand Down
15 changes: 7 additions & 8 deletions src/_pytest/config/argparsing.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import argparse
import os
import sys
import warnings
from gettext import gettext
Expand All @@ -14,8 +15,6 @@
from typing import TYPE_CHECKING
from typing import Union

import py

import _pytest._io
from _pytest.compat import final
from _pytest.config.exceptions import UsageError
Expand Down Expand Up @@ -97,14 +96,14 @@ def addoption(self, *opts: str, **attrs: Any) -> None:

def parse(
self,
args: Sequence[Union[str, py.path.local]],
args: Sequence[Union[str, "os.PathLike[str]"]],
namespace: Optional[argparse.Namespace] = None,
) -> argparse.Namespace:
from _pytest._argcomplete import try_argcomplete

self.optparser = self._getparser()
try_argcomplete(self.optparser)
strargs = [str(x) if isinstance(x, py.path.local) else x for x in args]
strargs = [os.fspath(x) for x in args]
return self.optparser.parse_args(strargs, namespace=namespace)

def _getparser(self) -> "MyOptionParser":
Expand All @@ -128,7 +127,7 @@ def _getparser(self) -> "MyOptionParser":

def parse_setoption(
self,
args: Sequence[Union[str, py.path.local]],
args: Sequence[Union[str, "os.PathLike[str]"]],
option: argparse.Namespace,
namespace: Optional[argparse.Namespace] = None,
) -> List[str]:
Expand All @@ -139,21 +138,21 @@ def parse_setoption(

def parse_known_args(
self,
args: Sequence[Union[str, py.path.local]],
args: Sequence[Union[str, "os.PathLike[str]"]],
namespace: Optional[argparse.Namespace] = None,
) -> argparse.Namespace:
"""Parse and return a namespace object with known arguments at this point."""
return self.parse_known_and_unknown_args(args, namespace=namespace)[0]

def parse_known_and_unknown_args(
self,
args: Sequence[Union[str, py.path.local]],
args: Sequence[Union[str, "os.PathLike[str]"]],
namespace: Optional[argparse.Namespace] = None,
) -> Tuple[argparse.Namespace, List[str]]:
"""Parse and return a namespace object with known arguments, and
the remaining arguments unknown at this point."""
optparser = self._getparser()
strargs = [str(x) if isinstance(x, py.path.local) else x for x in args]
strargs = [os.fspath(x) for x in args]
return optparser.parse_known_args(strargs, namespace=namespace)

def addini(
Expand Down
15 changes: 8 additions & 7 deletions src/_pytest/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -648,12 +648,13 @@ def _compute_fixture_value(self, fixturedef: "FixtureDef[object]") -> None:
if has_params:
frame = inspect.stack()[3]
frameinfo = inspect.getframeinfo(frame[0])
source_path = py.path.local(frameinfo.filename)
source_path = absolutepath(frameinfo.filename)
source_lineno = frameinfo.lineno
rel_source_path = source_path.relto(funcitem.config.rootdir)
if rel_source_path:
source_path_str = rel_source_path
else:
try:
source_path_str = str(
source_path.relative_to(funcitem.config.rootpath)
)
except ValueError:
source_path_str = str(source_path)
msg = (
"The requested fixture has no parameter defined for test:\n"
Expand Down Expand Up @@ -876,7 +877,7 @@ def formatrepr(self) -> "FixtureLookupErrorRepr":
class FixtureLookupErrorRepr(TerminalRepr):
def __init__(
self,
filename: Union[str, py.path.local],
filename: Union[str, "os.PathLike[str]"],
firstlineno: int,
tblines: Sequence[str],
errorstring: str,
Expand All @@ -903,7 +904,7 @@ def toterminal(self, tw: TerminalWriter) -> None:
f"{FormattedExcinfo.flow_marker} {line.strip()}", red=True,
)
tw.line()
tw.line("%s:%d" % (self.filename, self.firstlineno + 1))
tw.line("%s:%d" % (os.fspath(self.filename), self.firstlineno + 1))


def fail_fixturefunc(fixturefunc, msg: str) -> "NoReturn":
Expand Down
43 changes: 21 additions & 22 deletions src/_pytest/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,7 @@ def __init__(self, config: Config) -> None:
self.shouldfail: Union[bool, str] = False
self.trace = config.trace.root.get("collection")
self.startdir = config.invocation_dir
self._initialpaths: FrozenSet[py.path.local] = frozenset()
self._initialpaths: FrozenSet[Path] = frozenset()

self._bestrelpathcache: Dict[Path, str] = _bestrelpath_cache(config.rootpath)

Expand Down Expand Up @@ -510,8 +510,8 @@ def pytest_runtest_logreport(

pytest_collectreport = pytest_runtest_logreport

def isinitpath(self, path: py.path.local) -> bool:
return path in self._initialpaths
def isinitpath(self, path: Union[str, "os.PathLike[str]"]) -> bool:
return Path(path) in self._initialpaths

def gethookproxy(self, fspath: "os.PathLike[str]"):
# Check if we have the common case of running
Expand Down Expand Up @@ -601,14 +601,14 @@ def perform_collect(
self.trace.root.indent += 1

self._notfound: List[Tuple[str, Sequence[nodes.Collector]]] = []
self._initial_parts: List[Tuple[py.path.local, List[str]]] = []
self._initial_parts: List[Tuple[Path, List[str]]] = []
self.items: List[nodes.Item] = []

hook = self.config.hook

items: Sequence[Union[nodes.Item, nodes.Collector]] = self.items
try:
initialpaths: List[py.path.local] = []
initialpaths: List[Path] = []
for arg in args:
fspath, parts = resolve_collection_argument(
self.config.invocation_params.dir,
Expand Down Expand Up @@ -669,13 +669,13 @@ def collect(self) -> Iterator[Union[nodes.Item, nodes.Collector]]:
# No point in finding packages when collecting doctests.
if not self.config.getoption("doctestmodules", False):
pm = self.config.pluginmanager
confcutdir = py.path.local(pm._confcutdir) if pm._confcutdir else None
for parent in reversed(argpath.parts()):
if confcutdir and confcutdir.relto(parent):
confcutdir = pm._confcutdir
for parent in (argpath, *argpath.parents):
if confcutdir and parent in confcutdir.parents:
break

if parent.isdir():
pkginit = parent.join("__init__.py")
if parent.is_dir():
pkginit = py.path.local(parent / "__init__.py")
if pkginit.isfile() and pkginit not in node_cache1:
col = self._collectfile(pkginit, handle_dupes=False)
if col:
Expand All @@ -685,7 +685,7 @@ def collect(self) -> Iterator[Union[nodes.Item, nodes.Collector]]:

# If it's a directory argument, recurse and look for any Subpackages.
# Let the Package collector deal with subnodes, don't collect here.
if argpath.check(dir=1):
if argpath.is_dir():
assert not names, "invalid arg {!r}".format((argpath, names))

seen_dirs: Set[py.path.local] = set()
Expand Down Expand Up @@ -717,15 +717,16 @@ def collect(self) -> Iterator[Union[nodes.Item, nodes.Collector]]:
node_cache2[key] = x
yield x
else:
assert argpath.check(file=1)
assert argpath.is_file()

if argpath in node_cache1:
col = node_cache1[argpath]
argpath_ = py.path.local(argpath)
if argpath_ in node_cache1:
col = node_cache1[argpath_]
else:
collect_root = pkg_roots.get(argpath.dirname, self)
col = collect_root._collectfile(argpath, handle_dupes=False)
collect_root = pkg_roots.get(argpath_.dirname, self)
col = collect_root._collectfile(argpath_, handle_dupes=False)
if col:
node_cache1[argpath] = col
node_cache1[argpath_] = col

matching = []
work: List[
Expand Down Expand Up @@ -782,9 +783,7 @@ def collect(self) -> Iterator[Union[nodes.Item, nodes.Collector]]:
# first yielded item will be the __init__ Module itself, so
# just use that. If this special case isn't taken, then all the
# files in the package will be yielded.
if argpath.basename == "__init__.py" and isinstance(
matching[0], Package
):
if argpath.name == "__init__.py" and isinstance(matching[0], Package):
try:
yield next(iter(matching[0].collect()))
except StopIteration:
Expand Down Expand Up @@ -833,7 +832,7 @@ def search_pypath(module_name: str) -> str:

def resolve_collection_argument(
invocation_path: Path, arg: str, *, as_pypath: bool = False
) -> Tuple[py.path.local, List[str]]:
) -> Tuple[Path, List[str]]:
"""Parse path arguments optionally containing selection parts and return (fspath, names).
Command-line arguments can point to files and/or directories, and optionally contain
Expand Down Expand Up @@ -875,4 +874,4 @@ def resolve_collection_argument(
else "directory argument cannot contain :: selection parts: {arg}"
)
raise UsageError(msg.format(arg=arg))
return py.path.local(str(fspath)), parts
return fspath, parts
10 changes: 3 additions & 7 deletions src/_pytest/monkeypatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import sys
import warnings
from contextlib import contextmanager
from pathlib import Path
from typing import Any
from typing import Generator
from typing import List
Expand Down Expand Up @@ -325,18 +324,15 @@ def syspath_prepend(self, path) -> None:

invalidate_caches()

def chdir(self, path) -> None:
def chdir(self, path: Union[str, "os.PathLike[str]"]) -> None:
"""Change the current working directory to the specified path.
Path can be a string or a py.path.local object.
Path can be a string or a path object.
"""
if self._cwd is None:
self._cwd = os.getcwd()
if hasattr(path, "chdir"):
path.chdir()
elif isinstance(path, Path):
# Modern python uses the fspath protocol here LEGACY
os.chdir(str(path))
path.chdir() # type: ignore[union-attr]
else:
os.chdir(path)

Expand Down
10 changes: 7 additions & 3 deletions src/_pytest/nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -480,10 +480,14 @@ def _prunetraceback(self, excinfo: ExceptionInfo[BaseException]) -> None:
excinfo.traceback = ntraceback.filter()


def _check_initialpaths_for_relpath(session, fspath):
def _check_initialpaths_for_relpath(
session: "Session", fspath: py.path.local
) -> Optional[str]:
for initial_path in session._initialpaths:
if fspath.common(initial_path) == initial_path:
return fspath.relto(initial_path)
initial_path_ = py.path.local(initial_path)
if fspath.common(initial_path_) == initial_path_:
return fspath.relto(initial_path_)
return None


class FSCollector(Collector):
Expand Down
6 changes: 2 additions & 4 deletions src/_pytest/pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@
from typing import TypeVar
from typing import Union

import py

from _pytest.compat import assert_never
from _pytest.outcomes import skip
from _pytest.warning_types import PytestWarning
Expand Down Expand Up @@ -456,7 +454,7 @@ class ImportPathMismatchError(ImportError):


def import_path(
p: Union[str, py.path.local, Path],
p: Union[str, "os.PathLike[str]"],
*,
mode: Union[str, ImportMode] = ImportMode.prepend,
) -> ModuleType:
Expand All @@ -482,7 +480,7 @@ def import_path(
"""
mode = ImportMode(mode)

path = Path(str(p))
path = Path(p)

if not path.exists():
raise ImportError(path)
Expand Down

0 comments on commit 1620b3d

Please sign in to comment.