Skip to content

Commit fe215bd

Browse files
authored
Merge pull request #8446 from bluetech/unnecessary-py-path-2
More py.path removal work
2 parents f7efb9a + f0c7043 commit fe215bd

File tree

22 files changed

+111
-98
lines changed

22 files changed

+111
-98
lines changed

changelog/7259.feature.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Added :meth:`cache.mkdir() <pytest.Cache.mkdir>`, which is similar to the existing :meth:`cache.makedir() <pytest.Cache.makedir>`,
2+
but returns a :class:`pathlib.Path` instead of a legacy ``py.path.local``.

doc/en/example/nonpython/conftest.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,17 @@
22
import pytest
33

44

5-
def pytest_collect_file(parent, path):
6-
if path.ext == ".yaml" and path.basename.startswith("test"):
7-
return YamlFile.from_parent(parent, fspath=path)
5+
def pytest_collect_file(parent, fspath):
6+
if fspath.suffix == ".yaml" and fspath.name.startswith("test"):
7+
return YamlFile.from_parent(parent, path=fspath)
88

99

1010
class YamlFile(pytest.File):
1111
def collect(self):
1212
# We need a yaml parser, e.g. PyYAML.
1313
import yaml
1414

15-
raw = yaml.safe_load(self.fspath.open())
15+
raw = yaml.safe_load(self.path.open())
1616
for name, spec in sorted(raw.items()):
1717
yield YamlItem.from_parent(self, name=name, spec=spec)
1818

doc/en/reference/reference.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -936,7 +936,7 @@ pytest treats some global variables in a special manner when defined in a test m
936936
**Tutorial**: :ref:`customizing-test-collection`
937937

938938
Can be declared in *conftest.py files* to exclude test directories or modules.
939-
Needs to be ``list[str]``.
939+
Needs to be a list of paths (``str``, :class:`pathlib.Path` or any :class:`os.PathLike`).
940940

941941
.. code-block:: python
942942

src/_pytest/cacheprovider.py

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -60,10 +60,10 @@ class Cache:
6060
_cachedir = attr.ib(type=Path, repr=False)
6161
_config = attr.ib(type=Config, repr=False)
6262

63-
# sub-directory under cache-dir for directories created by "makedir"
63+
# Sub-directory under cache-dir for directories created by `mkdir()`.
6464
_CACHE_PREFIX_DIRS = "d"
6565

66-
# sub-directory under cache-dir for values created by "set"
66+
# Sub-directory under cache-dir for values created by `set()`.
6767
_CACHE_PREFIX_VALUES = "v"
6868

6969
def __init__(
@@ -121,13 +121,15 @@ def warn(self, fmt: str, *, _ispytest: bool = False, **args: object) -> None:
121121
stacklevel=3,
122122
)
123123

124-
def makedir(self, name: str) -> LEGACY_PATH:
124+
def mkdir(self, name: str) -> Path:
125125
"""Return a directory path object with the given name.
126126
127127
If the directory does not yet exist, it will be created. You can use
128128
it to manage files to e.g. store/retrieve database dumps across test
129129
sessions.
130130
131+
.. versionadded:: 6.3
132+
131133
:param name:
132134
Must be a string not containing a ``/`` separator.
133135
Make sure the name contains your plugin or application
@@ -138,7 +140,14 @@ def makedir(self, name: str) -> LEGACY_PATH:
138140
raise ValueError("name is not allowed to contain path separators")
139141
res = self._cachedir.joinpath(self._CACHE_PREFIX_DIRS, path)
140142
res.mkdir(exist_ok=True, parents=True)
141-
return legacy_path(res)
143+
return res
144+
145+
def makedir(self, name: str) -> LEGACY_PATH:
146+
"""Return a directory path object with the given name.
147+
148+
Same as :func:`mkdir`, but returns a legacy py path instance.
149+
"""
150+
return legacy_path(self.mkdir(name))
142151

143152
def _getvaluepath(self, key: str) -> Path:
144153
return self._cachedir.joinpath(self._CACHE_PREFIX_VALUES, Path(key))
@@ -572,8 +581,8 @@ def cacheshow(config: Config, session: Session) -> int:
572581
contents = sorted(ddir.rglob(glob))
573582
tw.sep("-", "cache directories for %r" % glob)
574583
for p in contents:
575-
# if p.check(dir=1):
576-
# print("%s/" % p.relto(basedir))
584+
# if p.is_dir():
585+
# print("%s/" % p.relative_to(basedir))
577586
if p.is_file():
578587
key = str(p.relative_to(basedir))
579588
tw.line(f"{key} is a file of length {p.stat().st_size:d}")

src/_pytest/config/__init__.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1445,9 +1445,7 @@ def _getconftest_pathlist(self, name: str, path: Path) -> Optional[List[Path]]:
14451445
modpath = Path(mod.__file__).parent
14461446
values: List[Path] = []
14471447
for relroot in relroots:
1448-
if isinstance(relroot, Path):
1449-
pass
1450-
elif isinstance(relroot, LEGACY_PATH):
1448+
if isinstance(relroot, os.PathLike):
14511449
relroot = Path(relroot)
14521450
else:
14531451
relroot = relroot.replace("/", os.sep)

src/_pytest/doctest.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@
2828
from _pytest._code.code import ReprFileLocation
2929
from _pytest._code.code import TerminalRepr
3030
from _pytest._io import TerminalWriter
31-
from _pytest.compat import LEGACY_PATH
3231
from _pytest.compat import legacy_path
3332
from _pytest.compat import safe_getattr
3433
from _pytest.config import Config
@@ -122,7 +121,6 @@ def pytest_unconfigure() -> None:
122121

123122
def pytest_collect_file(
124123
fspath: Path,
125-
path: LEGACY_PATH,
126124
parent: Collector,
127125
) -> Optional[Union["DoctestModule", "DoctestTextfile"]]:
128126
config = parent.config

src/_pytest/main.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -465,7 +465,7 @@ class Session(nodes.FSCollector):
465465
def __init__(self, config: Config) -> None:
466466
super().__init__(
467467
path=config.rootpath,
468-
fspath=config.rootdir,
468+
fspath=None,
469469
parent=None,
470470
config=config,
471471
session=self,

src/_pytest/pytester.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -912,7 +912,7 @@ def copy_example(self, name: Optional[str] = None) -> Path:
912912
example_dir = self._request.config.getini("pytester_example_dir")
913913
if example_dir is None:
914914
raise ValueError("pytester_example_dir is unset, can't copy examples")
915-
example_dir = Path(str(self._request.config.rootdir)) / example_dir
915+
example_dir = self._request.config.rootpath / example_dir
916916

917917
for extra_element in self._request.node.iter_markers("pytester_example_path"):
918918
assert extra_element.args

src/_pytest/python.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -210,11 +210,11 @@ def path_matches_patterns(path: Path, patterns: Iterable[str]) -> bool:
210210
return any(fnmatch_ex(pattern, path) for pattern in patterns)
211211

212212

213-
def pytest_pycollect_makemodule(fspath: Path, path: LEGACY_PATH, parent) -> "Module":
213+
def pytest_pycollect_makemodule(fspath: Path, parent) -> "Module":
214214
if fspath.name == "__init__.py":
215-
pkg: Package = Package.from_parent(parent, fspath=path)
215+
pkg: Package = Package.from_parent(parent, path=fspath)
216216
return pkg
217-
mod: Module = Module.from_parent(parent, fspath=path)
217+
mod: Module = Module.from_parent(parent, path=fspath)
218218
return mod
219219

220220

@@ -691,7 +691,7 @@ def _collectfile(
691691
assert (
692692
fspath.is_file()
693693
), "{!r} is not a file (isdir={!r}, exists={!r}, islink={!r})".format(
694-
path, fspath.is_dir(), fspath.exists(), fspath.is_symlink()
694+
fspath, fspath.is_dir(), fspath.exists(), fspath.is_symlink()
695695
)
696696
ihook = self.session.gethookproxy(fspath)
697697
if not self.session.isinitpath(fspath):

testing/acceptance_test.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -304,9 +304,9 @@ def runtest(self):
304304
class MyCollector(pytest.File):
305305
def collect(self):
306306
return [MyItem.from_parent(name="xyz", parent=self)]
307-
def pytest_collect_file(path, parent):
308-
if path.basename.startswith("conftest"):
309-
return MyCollector.from_parent(fspath=path, parent=parent)
307+
def pytest_collect_file(fspath, parent):
308+
if fspath.name.startswith("conftest"):
309+
return MyCollector.from_parent(path=fspath, parent=parent)
310310
"""
311311
)
312312
result = pytester.runpytest(c.name + "::" + "xyz")

0 commit comments

Comments
 (0)