summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorRan Benita <ran@unusedvar.com>2020-12-19 14:11:00 +0200
committerRan Benita <ran@unusedvar.com>2020-12-22 21:08:25 +0200
commit92ba96b0612e6b06bb8f4ab05bd75481d2504806 (patch)
treef88a7320cab5bb9ca516ffb33c20757317c720f7 /src
parent7aa224083205adb650a7b1132e6b9e861361426e (diff)
downloadpytest-92ba96b0612e6b06bb8f4ab05bd75481d2504806.tar.gz
code: convert from py.path to pathlib
Diffstat (limited to 'src')
-rw-r--r--src/_pytest/_code/code.py55
-rw-r--r--src/_pytest/fixtures.py8
-rw-r--r--src/_pytest/nodes.py8
-rw-r--r--src/_pytest/python.py6
4 files changed, 45 insertions, 32 deletions
diff --git a/src/_pytest/_code/code.py b/src/_pytest/_code/code.py
index 423069330..043a23a79 100644
--- a/src/_pytest/_code/code.py
+++ b/src/_pytest/_code/code.py
@@ -43,6 +43,8 @@ from _pytest._io.saferepr import safeformat
from _pytest._io.saferepr import saferepr
from _pytest.compat import final
from _pytest.compat import get_real_func
+from _pytest.pathlib import absolutepath
+from _pytest.pathlib import bestrelpath
if TYPE_CHECKING:
from typing_extensions import Literal
@@ -78,16 +80,16 @@ class Code:
return self.raw.co_name
@property
- def path(self) -> Union[py.path.local, str]:
+ def path(self) -> Union[Path, str]:
"""Return a path object pointing to source code, or an ``str`` in
case of ``OSError`` / non-existing file."""
if not self.raw.co_filename:
return ""
try:
- p = py.path.local(self.raw.co_filename)
+ p = absolutepath(self.raw.co_filename)
# maybe don't try this checking
- if not p.check():
- raise OSError("py.path check failed.")
+ if not p.exists():
+ raise OSError("path check failed.")
return p
except OSError:
# XXX maybe try harder like the weird logic
@@ -223,7 +225,7 @@ class TracebackEntry:
return source.getstatement(self.lineno)
@property
- def path(self) -> Union[py.path.local, str]:
+ def path(self) -> Union[Path, str]:
"""Path to the source code."""
return self.frame.code.path
@@ -336,10 +338,10 @@ class Traceback(List[TracebackEntry]):
def cut(
self,
- path=None,
+ path: Optional[Union[Path, str]] = None,
lineno: Optional[int] = None,
firstlineno: Optional[int] = None,
- excludepath: Optional[py.path.local] = None,
+ excludepath: Optional[Path] = None,
) -> "Traceback":
"""Return a Traceback instance wrapping part of this Traceback.
@@ -353,17 +355,19 @@ class Traceback(List[TracebackEntry]):
for x in self:
code = x.frame.code
codepath = code.path
+ if path is not None and codepath != path:
+ continue
if (
- (path is None or codepath == path)
- and (
- excludepath is None
- or not isinstance(codepath, py.path.local)
- or not codepath.relto(excludepath)
- )
- and (lineno is None or x.lineno == lineno)
- and (firstlineno is None or x.frame.code.firstlineno == firstlineno)
+ excludepath is not None
+ and isinstance(codepath, Path)
+ and excludepath in codepath.parents
):
- return Traceback(x._rawentry, self._excinfo)
+ continue
+ if lineno is not None and x.lineno != lineno:
+ continue
+ if firstlineno is not None and x.frame.code.firstlineno != firstlineno:
+ continue
+ return Traceback(x._rawentry, self._excinfo)
return self
@overload
@@ -801,7 +805,8 @@ class FormattedExcinfo:
message = "in %s" % (entry.name)
else:
message = excinfo and excinfo.typename or ""
- path = self._makepath(entry.path)
+ entry_path = entry.path
+ path = self._makepath(entry_path)
reprfileloc = ReprFileLocation(path, entry.lineno + 1, message)
localsrepr = self.repr_locals(entry.locals)
return ReprEntry(lines, reprargs, localsrepr, reprfileloc, style)
@@ -814,15 +819,15 @@ class FormattedExcinfo:
lines.extend(self.get_exconly(excinfo, indent=4))
return ReprEntry(lines, None, None, None, style)
- def _makepath(self, path):
- if not self.abspath:
+ def _makepath(self, path: Union[Path, str]) -> str:
+ if not self.abspath and isinstance(path, Path):
try:
- np = py.path.local().bestrelpath(path)
+ np = bestrelpath(Path.cwd(), path)
except OSError:
- return path
+ return str(path)
if len(np) < len(str(path)):
- path = np
- return path
+ return np
+ return str(path)
def repr_traceback(self, excinfo: ExceptionInfo[BaseException]) -> "ReprTraceback":
traceback = excinfo.traceback
@@ -1181,7 +1186,7 @@ class ReprFuncArgs(TerminalRepr):
tw.line("")
-def getfslineno(obj: object) -> Tuple[Union[str, py.path.local], int]:
+def getfslineno(obj: object) -> Tuple[Union[str, Path], int]:
"""Return source location (path, lineno) for the given object.
If the source cannot be determined return ("", -1).
@@ -1203,7 +1208,7 @@ def getfslineno(obj: object) -> Tuple[Union[str, py.path.local], int]:
except TypeError:
return "", -1
- fspath = fn and py.path.local(fn) or ""
+ fspath = fn and absolutepath(fn) or ""
lineno = -1
if fspath:
try:
diff --git a/src/_pytest/fixtures.py b/src/_pytest/fixtures.py
index c24ab7069..6db1c5906 100644
--- a/src/_pytest/fixtures.py
+++ b/src/_pytest/fixtures.py
@@ -5,6 +5,7 @@ import sys
import warnings
from collections import defaultdict
from collections import deque
+from pathlib import Path
from types import TracebackType
from typing import Any
from typing import Callable
@@ -58,6 +59,7 @@ from _pytest.mark.structures import MarkDecorator
from _pytest.outcomes import fail
from _pytest.outcomes import TEST_OUTCOME
from _pytest.pathlib import absolutepath
+from _pytest.pathlib import bestrelpath
from _pytest.store import StoreKey
if TYPE_CHECKING:
@@ -718,7 +720,11 @@ class FixtureRequest:
for fixturedef in self._get_fixturestack():
factory = fixturedef.func
fs, lineno = getfslineno(factory)
- p = self._pyfuncitem.session.fspath.bestrelpath(fs)
+ if isinstance(fs, Path):
+ session: Session = self._pyfuncitem.session
+ p = bestrelpath(Path(session.fspath), fs)
+ else:
+ p = fs
args = _format_args(factory)
lines.append("%s:%d: def %s%s" % (p, lineno + 1, factory.__name__, args))
return lines
diff --git a/src/_pytest/nodes.py b/src/_pytest/nodes.py
index 1b3ec5571..da2a0a7ea 100644
--- a/src/_pytest/nodes.py
+++ b/src/_pytest/nodes.py
@@ -39,7 +39,7 @@ if TYPE_CHECKING:
SEP = "/"
-tracebackcutdir = py.path.local(_pytest.__file__).dirpath()
+tracebackcutdir = Path(_pytest.__file__).parent
def iterparentnodeids(nodeid: str) -> Iterator[str]:
@@ -416,9 +416,7 @@ class Node(metaclass=NodeMeta):
return self._repr_failure_py(excinfo, style)
-def get_fslocation_from_item(
- node: "Node",
-) -> Tuple[Union[str, py.path.local], Optional[int]]:
+def get_fslocation_from_item(node: "Node") -> Tuple[Union[str, Path], Optional[int]]:
"""Try to extract the actual location from a node, depending on available attributes:
* "location": a pair (path, lineno)
@@ -474,7 +472,7 @@ class Collector(Node):
def _prunetraceback(self, excinfo: ExceptionInfo[BaseException]) -> None:
if hasattr(self, "fspath"):
traceback = excinfo.traceback
- ntraceback = traceback.cut(path=self.fspath)
+ ntraceback = traceback.cut(path=Path(self.fspath))
if ntraceback == traceback:
ntraceback = ntraceback.cut(excludepath=tracebackcutdir)
excinfo.traceback = ntraceback.filter()
diff --git a/src/_pytest/python.py b/src/_pytest/python.py
index 3ff04455f..27bbb24fe 100644
--- a/src/_pytest/python.py
+++ b/src/_pytest/python.py
@@ -340,7 +340,11 @@ class PyobjMixin:
fspath: Union[py.path.local, str] = file_path
lineno = compat_co_firstlineno
else:
- fspath, lineno = getfslineno(obj)
+ path, lineno = getfslineno(obj)
+ if isinstance(path, Path):
+ fspath = py.path.local(path)
+ else:
+ fspath = path
modpath = self.getmodpath()
assert isinstance(lineno, int)
return fspath, lineno, modpath