Skip to content

Commit b366374

Browse files
David Fritzschedavidfritzsche
David Fritzsche
authored andcommitted
Prepare for removal of deprecated path argument to pytest_collect_file()
Replace usage of the path argument to the pytest pytest_collect_file hook with usage of the file_path argument introduced in pytest 7. As pytest 7 is also our oldest supported version, we can rely on the availability of the file_path argument. This change will help to avoid breakage when a future pytest version drops the deprecated path argument. Also drops other untested code for pytest < 7 compatibility.
1 parent 2fb944d commit b366374

File tree

3 files changed

+30
-58
lines changed

3 files changed

+30
-58
lines changed

README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,9 @@ decorators are extracted from the ast.
140140

141141
## unreleased
142142

143+
* Replace usage of deprecated path argument to pytest hook
144+
``pytest_collect_file()`` with usage of the file_path argument
145+
introduced in pytest 7 ([#51][i51], [#52][p52])
143146

144147
## v0.1.2 (2024-02-26)
145148

@@ -218,6 +221,7 @@ decorators are extracted from the ast.
218221
[i35]: https://github.com/davidfritzsche/pytest-mypy-testing/issues/35
219222
[i36]: https://github.com/davidfritzsche/pytest-mypy-testing/issues/36
220223
[i46]: https://github.com/davidfritzsche/pytest-mypy-testing/issues/46
224+
[i51]: https://github.com/davidfritzsche/pytest-mypy-testing/issues/51
221225

222226
[p6]: https://github.com/davidfritzsche/pytest-mypy-testing/pull/6
223227
[p7]: https://github.com/davidfritzsche/pytest-mypy-testing/pull/7
@@ -240,3 +244,4 @@ decorators are extracted from the ast.
240244
[p48]: https://github.com/davidfritzsche/pytest-mypy-testing/pull/48
241245
[p49]: https://github.com/davidfritzsche/pytest-mypy-testing/pull/49
242246
[p50]: https://github.com/davidfritzsche/pytest-mypy-testing/pull/50
247+
[p52]: https://github.com/davidfritzsche/pytest-mypy-testing/pull/52

src/pytest_mypy_testing/plugin.py

Lines changed: 18 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import pytest
1111
from _pytest._code.code import ReprEntry, ReprFileLocation
1212
from _pytest.config import Config
13+
from _pytest.python import path_matches_patterns
1314

1415
from .message import Message, Severity
1516
from .output_processing import OutputMismatch, diff_message_sequences
@@ -57,12 +58,7 @@ def __init__(
5758

5859
@classmethod
5960
def from_parent(cls, parent, name, mypy_item):
60-
if PYTEST_VERSION_INFO < (5, 4):
61-
return cls(
62-
parent=parent, name=name, config=parent.config, mypy_item=mypy_item
63-
)
64-
else:
65-
return super().from_parent(parent=parent, name=name, mypy_item=mypy_item)
61+
return super().from_parent(parent=parent, name=name, mypy_item=mypy_item)
6662

6763
def runtest(self) -> None:
6864
returncode, actual_messages = self.parent.run_mypy(self.mypy_item)
@@ -75,14 +71,12 @@ def runtest(self) -> None:
7571
raise MypyAssertionError(item=self, errors=errors)
7672

7773
def reportinfo(self) -> Tuple[Union["os.PathLike[str]", str], Optional[int], str]:
78-
return self.parent.fspath, self.mypy_item.lineno, self.name
74+
return self.parent.path, self.mypy_item.lineno, self.name
7975

8076
def repr_failure(self, excinfo, style=None):
8177
if not excinfo.errisinstance(MypyAssertionError):
8278
return super().repr_failure(excinfo, style=style) # pragma: no cover
83-
reprfileloc_key = (
84-
"filelocrepr" if PYTEST_VERSION_INFO < (5, 4) else "reprfileloc"
85-
)
79+
reprfileloc_key = "reprfileloc"
8680
exception_repr = excinfo.getrepr(style="short")
8781
exception_repr.reprcrash.message = ""
8882
exception_repr.reprtraceback.reprentries = [
@@ -93,7 +87,7 @@ def repr_failure(self, excinfo, style=None):
9387
reprfuncargs=None,
9488
**{
9589
reprfileloc_key: ReprFileLocation(
96-
path=self.parent.fspath,
90+
path=str(self.parent.path),
9791
lineno=mismatch.lineno,
9892
message=mismatch.error_message,
9993
)
@@ -124,19 +118,12 @@ def __init__(
124118
**kwargs,
125119
)
126120
self.add_marker("mypy")
127-
if PYTEST_VERSION_INFO >= (7,):
128-
self.mypy_file = parse_file(self.path, config=config)
129-
else:
130-
self.mypy_file = parse_file(self.fspath, config=config)
121+
self.mypy_file = parse_file(self.path, config=config)
131122
self._mypy_result: Optional[MypyResult] = None
132123

133124
@classmethod
134125
def from_parent(cls, parent, **kwargs):
135-
if PYTEST_VERSION_INFO < (5, 4):
136-
config = getattr(parent, "config", None)
137-
return cls(parent=parent, config=config, **kwargs)
138-
else:
139-
return super().from_parent(parent=parent, **kwargs)
126+
return super().from_parent(parent=parent, **kwargs)
140127

141128
def collect(self) -> Iterator[PytestMypyTestItem]:
142129
for item in self.mypy_file.items:
@@ -146,7 +133,7 @@ def collect(self) -> Iterator[PytestMypyTestItem]:
146133

147134
def run_mypy(self, item: MypyTestItem) -> Tuple[int, List[Message]]:
148135
if self._mypy_result is None:
149-
self._mypy_result = self._run_mypy(self.fspath)
136+
self._mypy_result = self._run_mypy(self.path)
150137
return (
151138
self._mypy_result.returncode,
152139
sorted(
@@ -211,31 +198,21 @@ def _run_mypy(self, filename: Union[pathlib.Path, os.PathLike, str]) -> MypyResu
211198
)
212199

213200

214-
if PYTEST_VERSION_INFO < (7,):
215-
216-
def pytest_collect_file(path, parent):
217-
if path.ext == ".mypy-testing" or _is_pytest_test_file(path, parent):
218-
file = PytestMypyFile.from_parent(parent=parent, fspath=path)
219-
if file.mypy_file.items:
220-
return file
221-
return None
222-
223-
else:
224-
225-
def pytest_collect_file(file_path, path, parent): # type: ignore
226-
if path.ext == ".mypy-testing" or _is_pytest_test_file(path, parent):
227-
file = PytestMypyFile.from_parent(parent=parent, path=file_path)
228-
if file.mypy_file.items:
229-
return file
230-
return None
201+
def pytest_collect_file(file_path: pathlib.Path, parent):
202+
if file_path.suffix == ".mypy-testing" or _is_pytest_test_file(file_path, parent):
203+
file = PytestMypyFile.from_parent(parent=parent, path=file_path)
204+
if file.mypy_file.items:
205+
return file
206+
return None
231207

232208

233-
def _is_pytest_test_file(path, parent):
209+
def _is_pytest_test_file(file_path: pathlib.Path, parent):
234210
"""Return `True` if *path* is considered to be a pytest test file."""
235211
# Based on _pytest/python.py::pytest_collect_file
236212
fn_patterns = parent.config.getini("python_files") + ["__init__.py"]
237-
return path.ext == ".py" and (
238-
parent.session.isinitpath(path) or any(path.fnmatch(pat) for pat in fn_patterns)
213+
return file_path.suffix == ".py" and (
214+
parent.session.isinitpath(file_path)
215+
or path_matches_patterns(file_path, fn_patterns)
239216
)
240217

241218

tests/test_plugin.py

Lines changed: 7 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,6 @@
1818
from pytest_mypy_testing.strutil import dedent
1919

2020

21-
try:
22-
from py._path.local import LocalPath
23-
except ModuleNotFoundError:
24-
from _pytest._py.path import LocalPath
25-
26-
2721
PYTEST_VERSION = pytest.__version__
2822
PYTEST_VERSION_INFO = tuple(int(part) for part in PYTEST_VERSION.split(".")[:3])
2923

@@ -33,18 +27,15 @@
3327
WARNING = Severity.WARNING
3428

3529

36-
def call_pytest_collect_file(fspath, parent):
37-
if PYTEST_VERSION_INFO < (7,):
38-
return pytest_collect_file(fspath, parent)
39-
else:
40-
return pytest_collect_file(pathlib.Path(str(fspath)), fspath, parent) # type: ignore
30+
def call_pytest_collect_file(file_path: pathlib.Path, parent):
31+
return pytest_collect_file(file_path, parent)
4132

4233

4334
def test_create_mypy_assertion_error():
4435
MypyAssertionError(None, [])
4536

4637

47-
def mk_dummy_parent(tmp_path, filename, content=""):
38+
def mk_dummy_parent(tmp_path: pathlib.Path, filename, content=""):
4839
path = tmp_path / filename
4940
path.write_text(content)
5041

@@ -59,7 +50,6 @@ def mk_dummy_parent(tmp_path, filename, content=""):
5950
config=config,
6051
session=session,
6152
nodeid="dummy",
62-
fspath=LocalPath(path),
6353
path=path,
6454
)
6555

@@ -69,8 +59,8 @@ def mk_dummy_parent(tmp_path, filename, content=""):
6959
@pytest.mark.parametrize("filename", ["z.py", "test_z.mypy-testing"])
7060
def test_pytest_collect_file_not_test_file_name(tmp_path, filename: str):
7161
parent = mk_dummy_parent(tmp_path, filename)
72-
fspath = parent.fspath
73-
actual = call_pytest_collect_file(fspath, parent)
62+
file_path = parent.path
63+
actual = call_pytest_collect_file(file_path, parent)
7464
assert actual is None
7565

7666

@@ -89,8 +79,8 @@ def foo():
8979
filename=str(parent.path), source_lines=content.splitlines()
9080
)
9181

92-
fspath = parent.fspath
93-
actual = call_pytest_collect_file(fspath, parent)
82+
file_path = parent.path
83+
actual = call_pytest_collect_file(file_path, parent)
9484
assert isinstance(actual, PytestMypyFile)
9585

9686
assert len(actual.mypy_file.items) == 1

0 commit comments

Comments
 (0)