Skip to content

Commit 62e249a

Browse files
committed
Replace some usages of config.{rootdir,inifile} with config.{rootpath,inipath}
1 parent a346028 commit 62e249a

File tree

10 files changed

+117
-99
lines changed

10 files changed

+117
-99
lines changed

src/_pytest/cacheprovider.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def clear_cache(cls, cachedir: Path) -> None:
7878

7979
@staticmethod
8080
def cache_dir_from_config(config: Config) -> Path:
81-
return resolve_from_str(config.getini("cache_dir"), config.rootdir)
81+
return resolve_from_str(config.getini("cache_dir"), config.rootpath)
8282

8383
def warn(self, fmt: str, **args: object) -> None:
8484
import warnings
@@ -264,7 +264,7 @@ def __init__(self, config: Config) -> None:
264264

265265
def get_last_failed_paths(self) -> Set[Path]:
266266
"""Return a set with all Paths()s of the previously failed nodeids."""
267-
rootpath = Path(str(self.config.rootdir))
267+
rootpath = self.config.rootpath
268268
result = {rootpath / nodeid.split("::")[0] for nodeid in self.lastfailed}
269269
return {x for x in result if x.exists()}
270270

@@ -495,7 +495,7 @@ def pytest_report_header(config: Config) -> Optional[str]:
495495
# starting with .., ../.. if sensible
496496

497497
try:
498-
displaypath = cachedir.relative_to(str(config.rootdir))
498+
displaypath = cachedir.relative_to(config.rootpath)
499499
except ValueError:
500500
displaypath = cachedir
501501
return "cachedir: {}".format(displaypath)

src/_pytest/config/__init__.py

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
from _pytest.compat import TYPE_CHECKING
4848
from _pytest.outcomes import fail
4949
from _pytest.outcomes import Skipped
50+
from _pytest.pathlib import bestrelpath
5051
from _pytest.pathlib import import_path
5152
from _pytest.pathlib import ImportMode
5253
from _pytest.pathlib import Path
@@ -520,7 +521,7 @@ def _getconftestmodules(
520521
else:
521522
directory = path
522523

523-
# XXX these days we may rather want to use config.rootdir
524+
# XXX these days we may rather want to use config.rootpath
524525
# and allow users to opt into looking into the rootdir parent
525526
# directories instead of requiring to specify confcutdir.
526527
clist = []
@@ -1036,9 +1037,9 @@ def notify_exception(
10361037

10371038
def cwd_relative_nodeid(self, nodeid: str) -> str:
10381039
# nodeid's are relative to the rootpath, compute relative to cwd.
1039-
if self.invocation_dir != self.rootdir:
1040-
fullpath = self.rootdir.join(nodeid)
1041-
nodeid = self.invocation_dir.bestrelpath(fullpath)
1040+
if self.invocation_params.dir != self.rootpath:
1041+
fullpath = self.rootpath / nodeid
1042+
nodeid = bestrelpath(self.invocation_params.dir, fullpath)
10421043
return nodeid
10431044

10441045
@classmethod
@@ -1076,8 +1077,8 @@ def _initini(self, args: Sequence[str]) -> None:
10761077
self._rootpath = rootpath
10771078
self._inipath = inipath
10781079
self.inicfg = inicfg
1079-
self._parser.extra_info["rootdir"] = self.rootdir
1080-
self._parser.extra_info["inifile"] = self.inifile
1080+
self._parser.extra_info["rootdir"] = str(self.rootpath)
1081+
self._parser.extra_info["inifile"] = str(self.inipath)
10811082
self._parser.addini("addopts", "extra command line options", "args")
10821083
self._parser.addini("minversion", "minimally required pytest version")
10831084
self._parser.addini(
@@ -1169,8 +1170,8 @@ def _preparse(self, args: List[str], addopts: bool = True) -> None:
11691170
self._validate_plugins()
11701171
self._warn_about_skipped_plugins()
11711172

1172-
if self.known_args_namespace.confcutdir is None and self.inifile:
1173-
confcutdir = py.path.local(self.inifile).dirname
1173+
if self.known_args_namespace.confcutdir is None and self.inipath is not None:
1174+
confcutdir = str(self.inipath.parent)
11741175
self.known_args_namespace.confcutdir = confcutdir
11751176
try:
11761177
self.hook.pytest_load_initial_conftests(
@@ -1206,13 +1207,13 @@ def _checkversion(self) -> None:
12061207

12071208
if not isinstance(minver, str):
12081209
raise pytest.UsageError(
1209-
"%s: 'minversion' must be a single value" % self.inifile
1210+
"%s: 'minversion' must be a single value" % self.inipath
12101211
)
12111212

12121213
if Version(minver) > Version(pytest.__version__):
12131214
raise pytest.UsageError(
12141215
"%s: 'minversion' requires pytest-%s, actual pytest-%s'"
1215-
% (self.inifile, minver, pytest.__version__,)
1216+
% (self.inipath, minver, pytest.__version__,)
12161217
)
12171218

12181219
def _validate_config_options(self) -> None:
@@ -1277,10 +1278,10 @@ def parse(self, args: List[str], addopts: bool = True) -> None:
12771278
args, self.option, namespace=self.option
12781279
)
12791280
if not args:
1280-
if self.invocation_dir == self.rootdir:
1281+
if self.invocation_params.dir == self.rootpath:
12811282
args = self.getini("testpaths")
12821283
if not args:
1283-
args = [str(self.invocation_dir)]
1284+
args = [str(self.invocation_params.dir)]
12841285
self.args = args
12851286
except PrintHelp:
12861287
pass
@@ -1383,10 +1384,10 @@ def _getini(self, name: str):
13831384
#
13841385
if type == "pathlist":
13851386
# TODO: This assert is probably not valid in all cases.
1386-
assert self.inifile is not None
1387-
dp = py.path.local(self.inifile).dirpath()
1387+
assert self.inipath is not None
1388+
dp = self.inipath.parent
13881389
input_values = shlex.split(value) if isinstance(value, str) else value
1389-
return [dp.join(x, abs=True) for x in input_values]
1390+
return [py.path.local(str(dp / x)) for x in input_values]
13901391
elif type == "args":
13911392
return shlex.split(value) if isinstance(value, str) else value
13921393
elif type == "linelist":

src/_pytest/fixtures.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
from _pytest.mark import ParameterSet
5151
from _pytest.outcomes import fail
5252
from _pytest.outcomes import TEST_OUTCOME
53+
from _pytest.pathlib import absolutepath
5354

5455
if TYPE_CHECKING:
5556
from typing import Deque
@@ -1443,7 +1444,7 @@ def getfixtureinfo(
14431444
def pytest_plugin_registered(self, plugin: _PluggyPlugin) -> None:
14441445
nodeid = None
14451446
try:
1446-
p = py.path.local(plugin.__file__) # type: ignore[attr-defined]
1447+
p = absolutepath(plugin.__file__) # type: ignore[attr-defined]
14471448
except AttributeError:
14481449
pass
14491450
else:
@@ -1452,8 +1453,13 @@ def pytest_plugin_registered(self, plugin: _PluggyPlugin) -> None:
14521453
# Construct the base nodeid which is later used to check
14531454
# what fixtures are visible for particular tests (as denoted
14541455
# by their test id).
1455-
if p.basename.startswith("conftest.py"):
1456-
nodeid = p.dirpath().relto(self.config.rootdir)
1456+
if p.name.startswith("conftest.py"):
1457+
try:
1458+
nodeid = str(p.parent.relative_to(self.config.rootpath))
1459+
except ValueError:
1460+
nodeid = ""
1461+
if nodeid == ".":
1462+
nodeid = ""
14571463
if os.sep != nodes.SEP:
14581464
nodeid = nodeid.replace(os.sep, nodes.SEP)
14591465

src/_pytest/logging.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -603,7 +603,7 @@ def set_log_path(self, fname: str) -> None:
603603
fpath = Path(fname)
604604

605605
if not fpath.is_absolute():
606-
fpath = Path(str(self._config.rootdir), fpath)
606+
fpath = self._config.rootpath / fpath
607607

608608
if not fpath.parent.exists():
609609
fpath.parent.mkdir(exist_ok=True, parents=True)

src/_pytest/main.py

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
from _pytest.fixtures import FixtureManager
3434
from _pytest.outcomes import exit
3535
from _pytest.pathlib import absolutepath
36+
from _pytest.pathlib import bestrelpath
3637
from _pytest.pathlib import Path
3738
from _pytest.pathlib import visit
3839
from _pytest.reports import CollectReport
@@ -425,11 +426,11 @@ class Failed(Exception):
425426

426427

427428
@attr.s
428-
class _bestrelpath_cache(Dict[py.path.local, str]):
429-
path = attr.ib(type=py.path.local)
429+
class _bestrelpath_cache(Dict[Path, str]):
430+
path = attr.ib(type=Path)
430431

431-
def __missing__(self, path: py.path.local) -> str:
432-
r = self.path.bestrelpath(path) # type: str
432+
def __missing__(self, path: Path) -> str:
433+
r = bestrelpath(self.path, path)
433434
self[path] = r
434435
return r
435436

@@ -444,8 +445,8 @@ class Session(nodes.FSCollector):
444445
exitstatus = None # type: Union[int, ExitCode]
445446

446447
def __init__(self, config: Config) -> None:
447-
nodes.FSCollector.__init__(
448-
self, config.rootdir, parent=None, config=config, session=self, nodeid=""
448+
super().__init__(
449+
config.rootdir, parent=None, config=config, session=self, nodeid=""
449450
)
450451
self.testsfailed = 0
451452
self.testscollected = 0
@@ -456,8 +457,8 @@ def __init__(self, config: Config) -> None:
456457
self._initialpaths = frozenset() # type: FrozenSet[py.path.local]
457458

458459
self._bestrelpathcache = _bestrelpath_cache(
459-
config.rootdir
460-
) # type: Dict[py.path.local, str]
460+
config.rootpath
461+
) # type: Dict[Path, str]
461462

462463
self.config.pluginmanager.register(self, name="session")
463464

@@ -475,7 +476,7 @@ def __repr__(self) -> str:
475476
self.testscollected,
476477
)
477478

478-
def _node_location_to_relpath(self, node_path: py.path.local) -> str:
479+
def _node_location_to_relpath(self, node_path: Path) -> str:
479480
# bestrelpath is a quite slow function.
480481
return self._bestrelpathcache[node_path]
481482

@@ -599,7 +600,9 @@ def perform_collect( # noqa: F811
599600
initialpaths = [] # type: List[py.path.local]
600601
for arg in args:
601602
fspath, parts = resolve_collection_argument(
602-
self.config.invocation_dir, arg, as_pypath=self.config.option.pyargs
603+
self.config.invocation_params.dir,
604+
arg,
605+
as_pypath=self.config.option.pyargs,
603606
)
604607
self._initial_parts.append((fspath, parts))
605608
initialpaths.append(fspath)
@@ -817,7 +820,7 @@ def search_pypath(module_name: str) -> str:
817820

818821

819822
def resolve_collection_argument(
820-
invocation_dir: py.path.local, arg: str, *, as_pypath: bool = False
823+
invocation_path: Path, arg: str, *, as_pypath: bool = False
821824
) -> Tuple[py.path.local, List[str]]:
822825
"""Parse path arguments optionally containing selection parts and return (fspath, names).
823826
@@ -844,7 +847,7 @@ def resolve_collection_argument(
844847
strpath, *parts = str(arg).split("::")
845848
if as_pypath:
846849
strpath = search_pypath(strpath)
847-
fspath = Path(str(invocation_dir), strpath)
850+
fspath = invocation_path / strpath
848851
fspath = absolutepath(fspath)
849852
if not fspath.exists():
850853
msg = (

src/_pytest/nodes.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
from _pytest.mark.structures import MarkDecorator
3232
from _pytest.mark.structures import NodeKeywords
3333
from _pytest.outcomes import fail
34+
from _pytest.pathlib import absolutepath
3435
from _pytest.pathlib import Path
3536
from _pytest.store import Store
3637

@@ -401,7 +402,7 @@ def _repr_failure_py(
401402
# It will be better to just always display paths relative to invocation_dir, but
402403
# this requires a lot of plumbing (#6428).
403404
try:
404-
abspath = Path(os.getcwd()) != Path(str(self.config.invocation_dir))
405+
abspath = Path(os.getcwd()) != self.config.invocation_params.dir
405406
except OSError:
406407
abspath = True
407408

@@ -597,10 +598,7 @@ def reportinfo(self) -> Tuple[Union[py.path.local, str], Optional[int], str]:
597598
@cached_property
598599
def location(self) -> Tuple[str, Optional[int], str]:
599600
location = self.reportinfo()
600-
if isinstance(location[0], py.path.local):
601-
fspath = location[0]
602-
else:
603-
fspath = py.path.local(location[0])
601+
fspath = absolutepath(str(location[0]))
604602
relfspath = self.session._node_location_to_relpath(fspath)
605603
assert type(location[2]) is str
606604
return (relfspath, location[1], location[2])

src/_pytest/pathlib.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -366,8 +366,7 @@ def make_numbered_dir_with_cleanup(
366366
raise e
367367

368368

369-
def resolve_from_str(input: str, root: py.path.local) -> Path:
370-
rootpath = Path(root)
369+
def resolve_from_str(input: str, rootpath: Path) -> Path:
371370
input = expanduser(input)
372371
input = expandvars(input)
373372
if isabs(input):

0 commit comments

Comments
 (0)