Skip to content

Commit 5293016

Browse files
authored
Merge pull request #13459 from pytest-dev/pyright-minor-fixes
Minor fixes for pyright errors
2 parents b6e8144 + 7a48181 commit 5293016

File tree

9 files changed

+65
-27
lines changed

9 files changed

+65
-27
lines changed

.coveragerc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,5 +29,6 @@ exclude_lines =
2929

3030
^\s*if TYPE_CHECKING:
3131
^\s*@overload( |$)
32+
^\s*def .+: \.\.\.$
3233

3334
^\s*@pytest\.mark\.xfail

.pre-commit-config.yaml

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,24 @@ repos:
4747
# for mypy running on python>=3.11 since exceptiongroup is only a dependency
4848
# on <3.11
4949
- exceptiongroup>=1.0.0rc8
50+
- repo: https://github.com/RobertCraigie/pyright-python
51+
rev: v1.1.401
52+
hooks:
53+
- id: pyright
54+
files: ^(src/|scripts/)
55+
additional_dependencies:
56+
- iniconfig>=1.1.0
57+
- attrs>=19.2.0
58+
- pluggy>=1.5.0
59+
- packaging
60+
- tomli
61+
- types-setuptools
62+
- types-tabulate
63+
# for mypy running on python>=3.11 since exceptiongroup is only a dependency
64+
# on <3.11
65+
- exceptiongroup>=1.0.0rc8
66+
# Manual because passing pyright is a work in progress.
67+
stages: [manual]
5068
- repo: https://github.com/tox-dev/pyproject-fmt
5169
rev: "v2.6.0"
5270
hooks:

pyproject.toml

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -528,3 +528,17 @@ warn_unreachable = true
528528
warn_unused_configs = true
529529
no_implicit_reexport = true
530530
warn_unused_ignores = true
531+
532+
[tool.pyright]
533+
include = [
534+
"src",
535+
"testing",
536+
"scripts",
537+
]
538+
extraPaths = [
539+
"src",
540+
]
541+
pythonVersion = "3.9"
542+
typeCheckingMode = "basic"
543+
reportMissingImports = "none"
544+
reportMissingModuleSource = "none"

src/_pytest/assertion/__init__.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from collections.abc import Generator
77
import sys
88
from typing import Any
9+
from typing import Protocol
910
from typing import TYPE_CHECKING
1011

1112
from _pytest.assertion import rewrite
@@ -82,15 +83,18 @@ def register_assert_rewrite(*names: str) -> None:
8283
if not isinstance(name, str):
8384
msg = "expected module names as *args, got {0} instead" # type: ignore[unreachable]
8485
raise TypeError(msg.format(repr(names)))
86+
rewrite_hook: RewriteHook
8587
for hook in sys.meta_path:
8688
if isinstance(hook, rewrite.AssertionRewritingHook):
87-
importhook = hook
89+
rewrite_hook = hook
8890
break
8991
else:
90-
# TODO(typing): Add a protocol for mark_rewrite() and use it
91-
# for importhook and for PytestPluginManager.rewrite_hook.
92-
importhook = DummyRewriteHook() # type: ignore
93-
importhook.mark_rewrite(*names)
92+
rewrite_hook = DummyRewriteHook()
93+
rewrite_hook.mark_rewrite(*names)
94+
95+
96+
class RewriteHook(Protocol):
97+
def mark_rewrite(self, *names: str) -> None: ...
9498

9599

96100
class DummyRewriteHook:

src/_pytest/config/__init__.py

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@
7070

7171

7272
if TYPE_CHECKING:
73-
from _pytest.assertions.rewrite import AssertionRewritingHook
73+
from _pytest.assertion.rewrite import AssertionRewritingHook
7474
from _pytest.cacheprovider import Cache
7575
from _pytest.terminal import TerminalReporter
7676

@@ -273,9 +273,11 @@ def directory_arg(path: str, optname: str) -> str:
273273
"faulthandler",
274274
)
275275

276-
builtin_plugins = set(default_plugins)
277-
builtin_plugins.add("pytester")
278-
builtin_plugins.add("pytester_assertions")
276+
builtin_plugins = {
277+
*default_plugins,
278+
"pytester",
279+
"pytester_assertions",
280+
}
279281

280282

281283
def get_config(
@@ -397,7 +399,8 @@ class PytestPluginManager(PluginManager):
397399
"""
398400

399401
def __init__(self) -> None:
400-
import _pytest.assertion
402+
from _pytest.assertion import DummyRewriteHook
403+
from _pytest.assertion import RewriteHook
401404

402405
super().__init__("pytest")
403406

@@ -443,7 +446,7 @@ def __init__(self) -> None:
443446
self.enable_tracing()
444447

445448
# Config._consider_importhook will set a real object if required.
446-
self.rewrite_hook = _pytest.assertion.DummyRewriteHook()
449+
self.rewrite_hook: RewriteHook = DummyRewriteHook()
447450
# Used to know when we are importing conftests after the pytest_configure stage.
448451
self._configured = False
449452

@@ -469,21 +472,21 @@ def parse_hookimpl_opts(
469472
if not inspect.isroutine(method):
470473
return None
471474
# Collect unmarked hooks as long as they have the `pytest_' prefix.
472-
return _get_legacy_hook_marks( # type: ignore[return-value]
475+
legacy = _get_legacy_hook_marks(
473476
method, "impl", ("tryfirst", "trylast", "optionalhook", "hookwrapper")
474477
)
478+
return cast(HookimplOpts, legacy)
475479

476480
def parse_hookspec_opts(self, module_or_class, name: str) -> HookspecOpts | None:
477481
""":meta private:"""
478482
opts = super().parse_hookspec_opts(module_or_class, name)
479483
if opts is None:
480484
method = getattr(module_or_class, name)
481485
if name.startswith("pytest_"):
482-
opts = _get_legacy_hook_marks( # type: ignore[assignment]
483-
method,
484-
"spec",
485-
("firstresult", "historic"),
486+
legacy = _get_legacy_hook_marks(
487+
method, "spec", ("firstresult", "historic")
486488
)
489+
opts = cast(HookspecOpts, legacy)
487490
return opts
488491

489492
def register(self, plugin: _PluggyPlugin, name: str | None = None) -> str | None:
@@ -1581,7 +1584,7 @@ def addinivalue_line(self, name: str, line: str) -> None:
15811584
assert isinstance(x, list)
15821585
x.append(line) # modifies the cached list inline
15831586

1584-
def getini(self, name: str):
1587+
def getini(self, name: str) -> Any:
15851588
"""Return configuration value from an :ref:`ini file <configfiles>`.
15861589
15871590
If a configuration value is not defined in an
@@ -1725,7 +1728,7 @@ def _get_override_ini_value(self, name: str) -> str | None:
17251728
value = user_ini_value
17261729
return value
17271730

1728-
def getoption(self, name: str, default=notset, skip: bool = False):
1731+
def getoption(self, name: str, default: Any = notset, skip: bool = False):
17291732
"""Return command line option value.
17301733
17311734
:param name: Name of the option. You may also specify

src/_pytest/mark/expression.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -305,7 +305,7 @@ def __init__(self, code: types.CodeType) -> None:
305305
self.code = code
306306

307307
@classmethod
308-
def compile(self, input: str) -> Expression:
308+
def compile(cls, input: str) -> Expression:
309309
"""Compile a match expression.
310310
311311
:param input: The input expression - one line.

src/_pytest/pytester.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1116,7 +1116,8 @@ def inline_run(
11161116
rec = []
11171117

11181118
class Collect:
1119-
def pytest_configure(x, config: Config) -> None:
1119+
@staticmethod
1120+
def pytest_configure(config: Config) -> None:
11201121
rec.append(self.make_hook_recorder(config.pluginmanager))
11211122

11221123
plugins.append(Collect())

src/_pytest/raises.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -588,7 +588,7 @@ class RaisesExc(AbstractRaises[BaseExcT_co_default]):
588588
# At least one of the three parameters must be passed.
589589
@overload
590590
def __init__(
591-
self: RaisesExc[BaseExcT_co_default],
591+
self,
592592
expected_exception: (
593593
type[BaseExcT_co_default] | tuple[type[BaseExcT_co_default], ...]
594594
),
@@ -969,9 +969,7 @@ def __init__(
969969
# that are *very* hard to reconcile while adhering to the overloads, so we cast
970970
# it to avoid an error when passing it to super().__init__
971971
check = cast(
972-
"Callable[["
973-
"BaseExceptionGroup[ExcT_1|BaseExcT_1|BaseExceptionGroup[BaseExcT_2]]"
974-
"], bool]",
972+
"Callable[[BaseExceptionGroup[ExcT_1|BaseExcT_1|BaseExceptionGroup[BaseExcT_2]]], bool]",
975973
check,
976974
)
977975
super().__init__(match=match, check=check)
@@ -1107,7 +1105,7 @@ def matches(
11071105
def matches(
11081106
self,
11091107
exception: BaseException | None,
1110-
) -> TypeGuard[BaseExceptionGroup[BaseExcT_co]]:
1108+
) -> bool:
11111109
"""Check if an exception matches the requirements of this RaisesGroup.
11121110
If it fails, `RaisesGroup.fail_reason` will be set.
11131111
@@ -1271,7 +1269,7 @@ def _check_exceptions(
12711269
self,
12721270
_exception: BaseException,
12731271
actual_exceptions: Sequence[BaseException],
1274-
) -> TypeGuard[BaseExceptionGroup[BaseExcT_co]]:
1272+
) -> bool:
12751273
"""Helper method for RaisesGroup.matches that attempts to pair up expected and actual exceptions"""
12761274
# The _exception parameter is not used, but necessary for the TypeGuard
12771275

src/_pytest/tmpdir.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,6 @@ def tmp_path(
265265
yield path
266266

267267
# Remove the tmpdir if the policy is "failed" and the test passed.
268-
tmp_path_factory: TempPathFactory = request.session.config._tmp_path_factory # type: ignore
269268
policy = tmp_path_factory._retention_policy
270269
result_dict = request.node.stash[tmppath_result_key]
271270

0 commit comments

Comments
 (0)