Skip to content

Commit 1cf9405

Browse files
committed
Fix some type errors around py.path.local
These errors are found using a typed version of py.path.local.
1 parent 0256cb3 commit 1cf9405

File tree

11 files changed

+36
-29
lines changed

11 files changed

+36
-29
lines changed

src/_pytest/assertion/rewrite.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@
2323
from typing import Tuple
2424
from typing import Union
2525

26+
import py
27+
2628
from _pytest._io.saferepr import saferepr
2729
from _pytest._version import version
2830
from _pytest.assertion import util
@@ -177,10 +179,10 @@ def _early_rewrite_bailout(self, name: str, state: "AssertionState") -> bool:
177179
"""
178180
if self.session is not None and not self._session_paths_checked:
179181
self._session_paths_checked = True
180-
for path in self.session._initialpaths:
182+
for initial_path in self.session._initialpaths:
181183
# Make something as c:/projects/my_project/path.py ->
182184
# ['c:', 'projects', 'my_project', 'path.py']
183-
parts = str(path).split(os.path.sep)
185+
parts = str(initial_path).split(os.path.sep)
184186
# add 'path' to basenames to be checked.
185187
self._basenames_to_check_rewrite.add(os.path.splitext(parts[-1])[0])
186188

@@ -213,7 +215,7 @@ def _should_rewrite(self, name: str, fn: str, state: "AssertionState") -> bool:
213215
return True
214216

215217
if self.session is not None:
216-
if self.session.isinitpath(fn):
218+
if self.session.isinitpath(py.path.local(fn)):
217219
state.trace(
218220
"matched test file (was specified on cmdline): {!r}".format(fn)
219221
)

src/_pytest/cacheprovider.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -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(config.rootdir)
498+
displaypath = cachedir.relative_to(str(config.rootdir))
499499
except ValueError:
500500
displaypath = cachedir
501501
return "cachedir: {}".format(displaypath)

src/_pytest/config/__init__.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -308,10 +308,9 @@ def __init__(self) -> None:
308308
self._dirpath2confmods = {} # type: Dict[Any, List[object]]
309309
# Maps a py.path.local to a module object.
310310
self._conftestpath2mod = {} # type: Dict[Any, object]
311-
self._confcutdir = None
311+
self._confcutdir = None # type: Optional[py.path.local]
312312
self._noconftest = False
313-
# Set of py.path.local's.
314-
self._duplicatepaths = set() # type: Set[Any]
313+
self._duplicatepaths = set() # type: Set[py.path.local]
315314

316315
self.add_hookspecs(_pytest.hookspec)
317316
self.register(self)
@@ -945,13 +944,12 @@ def _initini(self, args: Sequence[str]) -> None:
945944
ns, unknown_args = self._parser.parse_known_and_unknown_args(
946945
args, namespace=copy.copy(self.option)
947946
)
948-
r = determine_setup(
947+
self.rootdir, self.inifile, self.inicfg = determine_setup(
949948
ns.inifilename,
950949
ns.file_or_dir + unknown_args,
951950
rootdir_cmd_arg=ns.rootdir or None,
952951
config=self,
953952
)
954-
self.rootdir, self.inifile, self.inicfg = r
955953
self._parser.extra_info["rootdir"] = self.rootdir
956954
self._parser.extra_info["inifile"] = self.inifile
957955
self._parser.addini("addopts", "extra command line options", "args")
@@ -1162,6 +1160,8 @@ def _getini(self, name: str) -> Any:
11621160
# in this case, we already have a list ready to use
11631161
#
11641162
if type == "pathlist":
1163+
# TODO: This assert is probably not valid in all cases.
1164+
assert self.inifile is not None
11651165
dp = py.path.local(self.inifile).dirpath()
11661166
input_values = shlex.split(value) if isinstance(value, str) else value
11671167
return [dp.join(x, abs=True) for x in input_values]

src/_pytest/config/findpaths.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ def load_config_dict_from_file(
6363
elif filepath.ext == ".toml":
6464
import toml
6565

66-
config = toml.load(filepath)
66+
config = toml.load(str(filepath))
6767

6868
result = config.get("tool", {}).get("pytest", {}).get("ini_options", None)
6969
if result is not None:
@@ -161,24 +161,26 @@ def determine_setup(
161161
args: List[str],
162162
rootdir_cmd_arg: Optional[str] = None,
163163
config: Optional["Config"] = None,
164-
) -> Tuple[py.path.local, Optional[str], Dict[str, Union[str, List[str]]]]:
164+
) -> Tuple[py.path.local, Optional[py.path.local], Dict[str, Union[str, List[str]]]]:
165165
rootdir = None
166166
dirs = get_dirs_from_args(args)
167167
if inifile:
168-
inicfg = load_config_dict_from_file(py.path.local(inifile)) or {}
168+
inipath_ = py.path.local(inifile)
169+
inipath = inipath_ # type: Optional[py.path.local]
170+
inicfg = load_config_dict_from_file(inipath_) or {}
169171
if rootdir_cmd_arg is None:
170172
rootdir = get_common_ancestor(dirs)
171173
else:
172174
ancestor = get_common_ancestor(dirs)
173-
rootdir, inifile, inicfg = locate_config([ancestor])
175+
rootdir, inipath, inicfg = locate_config([ancestor])
174176
if rootdir is None and rootdir_cmd_arg is None:
175177
for possible_rootdir in ancestor.parts(reverse=True):
176178
if possible_rootdir.join("setup.py").exists():
177179
rootdir = possible_rootdir
178180
break
179181
else:
180182
if dirs != [ancestor]:
181-
rootdir, inifile, inicfg = locate_config(dirs)
183+
rootdir, inipath, inicfg = locate_config(dirs)
182184
if rootdir is None:
183185
if config is not None:
184186
cwd = config.invocation_dir
@@ -196,4 +198,5 @@ def determine_setup(
196198
rootdir
197199
)
198200
)
199-
return rootdir, inifile, inicfg or {}
201+
assert rootdir is not None
202+
return rootdir, inipath, inicfg or {}

src/_pytest/logging.py

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

588588
if not fpath.is_absolute():
589-
fpath = Path(self._config.rootdir, fpath)
589+
fpath = Path(str(self._config.rootdir), fpath)
590590

591591
if not fpath.parent.exists():
592592
fpath.parent.mkdir(exist_ok=True, parents=True)

src/_pytest/main.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -439,7 +439,7 @@ def __init__(self, config: Config) -> None:
439439
) # type: Dict[Tuple[Type[nodes.Collector], str], CollectReport]
440440

441441
# Dirnames of pkgs with dunder-init files.
442-
self._collection_pkg_roots = {} # type: Dict[py.path.local, Package]
442+
self._collection_pkg_roots = {} # type: Dict[str, Package]
443443

444444
self._bestrelpathcache = _bestrelpath_cache(
445445
config.rootdir
@@ -601,7 +601,7 @@ def _collect(
601601
col = self._collectfile(pkginit, handle_dupes=False)
602602
if col:
603603
if isinstance(col[0], Package):
604-
self._collection_pkg_roots[parent] = col[0]
604+
self._collection_pkg_roots[str(parent)] = col[0]
605605
# always store a list in the cache, matchnodes expects it
606606
self._collection_node_cache1[col[0].fspath] = [col[0]]
607607

@@ -623,8 +623,8 @@ def _collect(
623623
for x in self._collectfile(pkginit):
624624
yield x
625625
if isinstance(x, Package):
626-
self._collection_pkg_roots[dirpath] = x
627-
if dirpath in self._collection_pkg_roots:
626+
self._collection_pkg_roots[str(dirpath)] = x
627+
if str(dirpath) in self._collection_pkg_roots:
628628
# Do not collect packages here.
629629
continue
630630

src/_pytest/nodes.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -393,7 +393,7 @@ def _repr_failure_py(
393393
# It will be better to just always display paths relative to invocation_dir, but
394394
# this requires a lot of plumbing (#6428).
395395
try:
396-
abspath = Path(os.getcwd()) != Path(self.config.invocation_dir)
396+
abspath = Path(os.getcwd()) != Path(str(self.config.invocation_dir))
397397
except OSError:
398398
abspath = True
399399

src/_pytest/python.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -656,7 +656,7 @@ def collect(self) -> Iterable[Union[nodes.Item, nodes.Collector]]:
656656

657657
parts_ = parts(path.strpath)
658658
if any(
659-
pkg_prefix in parts_ and pkg_prefix.join("__init__.py") != path
659+
str(pkg_prefix) in parts_ and pkg_prefix.join("__init__.py") != path
660660
for pkg_prefix in pkg_prefixes
661661
):
662662
continue
@@ -1332,7 +1332,7 @@ def _show_fixtures_per_test(config, session):
13321332

13331333
def get_best_relpath(func):
13341334
loc = getlocation(func, curdir)
1335-
return curdir.bestrelpath(loc)
1335+
return curdir.bestrelpath(py.path.local(loc))
13361336

13371337
def write_fixture(fixture_def):
13381338
argname = fixture_def.argname
@@ -1406,7 +1406,7 @@ def _showfixtures_main(config: Config, session: Session) -> None:
14061406
(
14071407
len(fixturedef.baseid),
14081408
fixturedef.func.__module__,
1409-
curdir.bestrelpath(loc),
1409+
curdir.bestrelpath(py.path.local(loc)),
14101410
fixturedef.argname,
14111411
fixturedef,
14121412
)

src/_pytest/terminal.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -380,9 +380,9 @@ def write_fspath_result(self, nodeid: str, res, **markup: bool) -> None:
380380
if self.currentfspath is not None and self._show_progress_info:
381381
self._write_progress_information_filling_space()
382382
self.currentfspath = fspath
383-
fspath = self.startdir.bestrelpath(fspath)
383+
relfspath = self.startdir.bestrelpath(fspath)
384384
self._tw.line()
385-
self._tw.write(fspath + " ")
385+
self._tw.write(relfspath + " ")
386386
self._tw.write(res, flush=True, **markup)
387387

388388
def write_ensure_prefix(self, prefix, extra: str = "", **kwargs) -> None:

testing/acceptance_test.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -580,8 +580,9 @@ def test_python_pytest_package(self, testdir):
580580
assert res.ret == 0
581581
res.stdout.fnmatch_lines(["*1 passed*"])
582582

583-
def test_equivalence_pytest_pytest(self):
584-
assert pytest.main == py.test.cmdline.main
583+
def test_equivalence_pytest_pydottest(self) -> None:
584+
# Type ignored because `py.test` is not and will not be typed.
585+
assert pytest.main == py.test.cmdline.main # type: ignore[attr-defined]
585586

586587
def test_invoke_with_invalid_type(self):
587588
with pytest.raises(

0 commit comments

Comments
 (0)