8000 [3.13] gh-109413: Add more type hints to `libregrtest` (GH-126352) (#… · python/cpython@32012ed · GitHub
[go: up one dir, main page]

Skip to content

Commit 32012ed

Browse files
[3.13] gh-109413: Add more type hints to libregrtest (GH-126352) (#126388)
gh-109413: Add more type hints to `libregrtest` (GH-126352) (cherry picked from commit bfc1d25) Co-authored-by: sobolevn <mail@sobolevn.me>
1 parent 0cd6036 commit 32012ed

File tree

12 files changed

+70
-62
lines changed

12 files changed

+70
-62
lines changed

Lib/test/libregrtest/findtests.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import os
22
import sys
33
import unittest
4+
from collections.abc import Container
45

56
from test import support
67

@@ -34,7 +35,7 @@ def findtestdir(path: StrPath | None = None) -> StrPath:
3435
return path or os.path.dirname(os.path.dirname(__file__)) or os.curdir
3536

3637

37-
def findtests(*, testdir: StrPath | None = None, exclude=(),
38+
def findtests(*, testdir: StrPath | None = None, exclude: Container[str] = (),
3839
split_test_dirs: set[TestName] = SPLITTESTDIRS,
3940
base_mod: str = "") -> TestList:
4041
"""Return a list of all applicable test modules."""
@@ -60,8 +61,9 @@ def findtests(*, testdir: StrPath | None = None, exclude=(),
6061
return sorted(tests)
6162

6263

63-
def split_test_packages(tests, *, testdir: StrPath | None = None, exclude=(),
64-
split_test_dirs=SPLITTESTDIRS):
64+
def split_test_packages(tests, *, testdir: StrPath | None = None,
65+
exclude: Container[str] = (),
66+
split_test_dirs=SPLITTESTDIRS) -> list[TestName]:
6567
testdir = findtestdir(testdir)
6668
splitted = []
6769
for name in tests:
@@ -75,9 +77,9 @@ def split_test_packages(tests, *, testdir: StrPath | None = None, exclude=(),
7577
return splitted
7678

7779

78-
def _list_cases(suite):
80+
def _list_cases(suite: unittest.TestSuite) -> None:
7981
for test in suite:
80-
if isinstance(test, unittest.loader._FailedTest):
82+
if isinstance(test, unittest.loader._FailedTest): # type: ignore[attr-defined]
8183
continue
8284
if isinstance(test, unittest.TestSuite):
8385
_list_cases(test)
@@ -87,7 +89,7 @@ def _list_cases(suite):
8789

8890
def list_cases(tests: TestTuple, *,
8991
match_tests: TestFilter | None = None,
90-
test_dir: StrPath | None = None):
92+
test_dir: StrPath | None = None) -> None:
9193
support.verbose = False
9294
set_match_tests(match_tests)
9395

Lib/test/libregrtest/main.py

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import sysconfig
77
import time
88
import trace
9+
from typing import NoReturn
910

1011
from test.support import (os_helper, MS_WINDOWS, flush_std_streams,
1112
suppress_immortalization)
@@ -155,7 +156,7 @@ def __init__(self, ns: Namespace, _add_python_opts: bool = False):
155156
self.next_single_test: TestName | None = None
156157
self.next_single_filename: StrPath | None = None
157158

158-
def log(self, line=''):
159+
def log(self, line: str = '') -> None:
159160
self.logger.log(line)
160161

161162
def find_tests(self, tests: TestList | None = None) -> tuple[TestTuple, TestList | None]:
@@ -233,11 +234,11 @@ def find_tests(self, tests: TestList | None = None) -> tuple[TestTuple, TestList
233234
return (tuple(selected), tests)
234235

235236
@staticmethod
236-
def list_tests(tests: TestTuple):
237+
def list_tests(tests: TestTuple) -> None:
237238
for name in tests:
238239
print(name)
239240

240-
def _rerun_failed_tests(self, runtests: RunTests):
241+
def _rerun_failed_tests(self, runtests: RunTests) -> RunTests:
241242
# Configure the runner to re-run tests
242243
if self.num_workers == 0 and not self.single_process:
243244
# Always run tests in fresh processes to have more deterministic
@@ -269,7 +270,7 @@ def _rerun_failed_tests(self, runtests: RunTests):
269270
self.run_tests_sequentially(runtests)
270271
return runtests
271272

272-
def rerun_failed_tests(self, runtests: RunTests):
273+
def rerun_failed_tests(self, runtests: RunTests) -> None:
273274
if self.python_cmd:
274275
# Temp patch for https://github.com/python/cpython/issues/94052
275276
self.log(
@@ -338,7 +339,7 @@ def run_bisect(self, runtests: RunTests) -> None:
338339
if not self._run_bisect(runtests, name, progress):
339340
return
340341

341-
def display_result(self, runtests):
342+
def display_result(self, runtests: RunTests) -> None:
342343
# If running the test suite for PGO then no one cares about results.
343344
if runtests.pgo:
344345
return
@@ -368,7 +369,7 @@ def run_test(
368369

369370
return result
370371

371-
def run_tests_sequentially(self, runtests) -> None:
372+
def run_tests_sequentially(self, runtests: RunTests) -> None:
372373
if self.coverage:
373374
tracer = trace.Trace(trace=False, count=True)
374375
else:
@@ -425,7 +426,7 @@ def run_tests_sequentially(self, runtests) -> None:
425426
if previous_test:
426427
print(previous_test)
427428

428-
def get_state(self):
429+
def get_state(self) -> str:
429430
state = self.results.get_state(self.fail_env_changed)
430431
if self.first_state:
431432
state = f'{self.first_state} then {state}'
@@ -474,7 +475,7 @@ def display_summary(self) -> None:
474475
state = self.get_state()
475476
print(f"Result: {state}")
476477

477-
def create_run_tests(self, tests: TestTuple):
478+
def create_run_tests(self, tests: TestTuple) -> RunTests:
478479
return RunTests(
479480
tests,
480481
fail_fast=self.fail_fast,
@@ -685,9 +686,9 @@ def _execute_python(self, cmd, environ):
685686
f"Command: {cmd_text}")
686687
# continue executing main()
687688

688-
def _add_python_opts(self):
689-
python_opts = []
690-
regrtest_opts = []
689+
def _add_python_opts(self) -> None:
690+
python_opts: list[str] = []
691+
regrtest_opts: list[str] = []
691692

692693
environ, keep_environ = self._add_cross_compile_opts(regrtest_opts)
693694
if self.ci_mode:
@@ -728,7 +729,7 @@ def tmp_dir(self) -> StrPath:
728729
)
729730
return self._tmp_dir
730731

731-
def main(self, tests: TestList | None = None):
732+
def main(self, tests: TestList | None = None) -> NoReturn:
732733
if self.want_add_python_opts:
733734
self._add_python_opts()
734735

@@ -757,7 +758,7 @@ def main(self, tests: TestList | None = None):
757758
sys.exit(exitcode)
758759

759760

760-
def main(tests=None, _add_python_opts=False, **kwargs):
761+
def main(tests=None, _add_python_opts=False, **kwargs) -> NoReturn:
761762
"""Run the Python suite."""
762763
ns = _parse_args(sys.argv[1:], **kwargs)
763764
Regrtest(ns, _add_python_opts=_add_python_opts).main(tests=tests)

Lib/test/libregrtest/pgo.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@
5050
'test_xml_etree_c',
5151
]
5252

53-
def setup_pgo_tests(cmdline_args, pgo_extended: bool):
53+
def setup_pgo_tests(cmdline_args, pgo_extended: bool) -> None:
5454
if not cmdline_args and not pgo_extended:
5555
# run default set of tests for PGO training
5656
cmdline_args[:] = PGO_TESTS[:]

Lib/test/libregrtest/refleak.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -263,7 +263,7 @@ def dash_R_cleanup(fs, ps, pic, zdc, abcs):
263263
sys._clear_internal_caches()
264264

265265

266-
def warm_caches():
266+
def warm_caches() -> None:
267267
# char cache
268268
s = bytes(range(256))
269269
for i in range(256):

Lib/test/libregrtest/result.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,7 @@ def __str__(self) -> str:
149149
case State.DID_NOT_RUN:
150150
return f"{self.test_name} ran no tests"
151151
case State.TIMEOUT:
152+
assert self.duration is not None, "self.duration is None"
152153
return f"{self.test_name} timed out ({format_duration(self.duration)})"
153154
case _:
154155
raise ValueError("unknown result state: {state!r}")

Lib/test/libregrtest/results.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ def get_state(self, fail_env_changed: bool) -> str:
7575

7676
return ', '.join(state)
7777

78-
def get_exitcode(self, fail_env_changed, fail_rerun):
78+
def get_exitcode(self, fail_env_changed: bool, fail_rerun: bool) -> int:
7979
exitcode = 0
8080
if self.bad:
8181
exitcode = EXITCODE_BAD_TEST
@@ -91,7 +91,7 @@ def get_exitcode(self, fail_env_changed, fail_rerun):
9191
exitcode = EXITCODE_BAD_TEST
9292
return exitcode
9393

94-
def accumulate_result(self, result: TestResult, runtests: RunTests):
94+
def accumulate_result(self, result: TestResult, runtests: RunTests) -> None:
9595
test_name = result.test_name
9696
rerun = runtests.rerun
9797
fail_env_changed = runtests.fail_env_changed
@@ -139,7 +139,7 @@ def get_coverage_results(self) -> trace.CoverageResults:
139139
counts = {loc: 1 for loc in self.covered_lines}
140140
return trace.CoverageResults(counts=counts)
141141

142-
def need_rerun(self):
142+
def need_rerun(self) -> bool:
143143
return bool(self.rerun_results)
144144

145145
def prepare_rerun(self, *, clear: bool = True) -> tuple[TestTuple, FilterDict]:
@@ -162,7 +162,7 @@ def prepare_rerun(self, *, clear: bool = True) -> tuple[TestTuple, FilterDict]:
162162

163163
return (tuple(tests), match_tests_dict)
164164

165-
def add_junit(self, xml_data: list[str]):
165+
def add_junit(self, xml_data: list[str]) -> None:
166166
import xml.etree.ElementTree as ET
167167
for e in xml_data:
168168
try:
@@ -171,7 +171,7 @@ def add_junit(self, xml_data: list[str]):
171171
print(xml_data, file=sys.__stderr__)
172172
raise
173173

174-
def write_junit(self, filename: StrPath):
174+
def write_junit(self, filename: StrPath) -> None:
175175
if not self.testsuite_xml:
176176
# Don't create empty XML file
177177
return
@@ -196,7 +196,7 @@ def write_junit(self, filename: StrPath):
196196
for s in ET.tostringlist(root):
197197
f.write(s)
198198

199-
def display_result(self, tests: TestTuple, quiet: bool, print_slowest: bool):
199+
def display_result(self, tests: TestTuple, quiet: bool, print_slowest: bool) -> None:
200200
if print_slowest:
201201
self.test_times.sort(reverse=True)
202202
print()
@@ -238,7 +238,7 @@ def display_result(self, tests: TestTuple, quiet: bool, print_slowest: bool):
238238
print()
239239
print("Test suite interrupted by signal SIGINT.")
240240

241-
def display_summary(self, first_runtests: RunTests, filtered: bool):
241+
def display_summary(self, first_runtests: RunTests, filtered: bool) -> None:
242242
# Total tests
243243
stats = self.stats
244244
text = f'run={stats.tests_run:,}'

Lib/test/libregrtest/runtests.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,12 @@
55
import shlex
66
import subprocess
77
import sys
8-
from typing import Any
8+
from typing import Any, Iterator
99

1010
from test import support
1111

1212
from .utils import (
13-
StrPath, StrJSON, TestTuple, TestFilter, FilterTuple, FilterDict)
13+
StrPath, StrJSON, TestTuple, TestName, TestFilter, FilterTuple, FilterDict)
1414

1515

1616
class JsonFileType:
@@ -41,8 +41,8 @@ def configure_subprocess(self, popen_kwargs: dict[str, Any]) -> None:
4141
popen_kwargs['startupinfo'] = startupinfo
4242

4343
@contextlib.contextmanager
44-
def inherit_subprocess(self):
45-
if self.file_type == JsonFileType.WINDOWS_HANDLE:
44+
def inherit_subprocess(self) -> Iterator[None]:
45+
if sys.platform == 'win32' and self.file_type == JsonFileType.WINDOWS_HANDLE:
4646
os.set_handle_inheritable(self.file, True)
4747
try:
4848
yield
@@ -106,25 +106,25 @@ def copy(self, **override) -> 'RunTests':
106106
state.update(override)
107107
return RunTests(**state)
108108

109-
def create_worker_runtests(self, **override):
109+
def create_worker_runtests(self, **override) -> 'WorkerRunTests':
110110
state = dataclasses.asdict(self)
111111
state.update(override)
112112
return WorkerRunTests(**state)
113113

114-
def get_match_tests(self, test_name) -> FilterTuple | None:
114+
def get_match_tests(self, test_name: TestName) -> FilterTuple | None:
115115
if self.match_tests_dict is not None:
116116
return self.match_tests_dict.get(test_name, None)
117117
else:
118118
return None
119119

120-
def get_jobs(self):
120+
def get_jobs(self) -> int | None:
121121
# Number of run_single_test() calls needed to run all tests.
122122
# None means that there is not bound limit (--forever option).
123123
if self.forever:
124124
return None
125125
return len(self.tests)
126126

127-
def iter_tests(self):
127+
def iter_tests(self) -> Iterator[TestName]:
128128
if self.forever:
129129
while True:
130130
yield from self.tests

Lib/test/libregrtest/setup.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,17 +25,18 @@ def setup_test_dir(testdir: str | None) -> None:
2525
sys.path.insert(0, os.path.abspath(testdir))
2626

2727

28-
def setup_process():
28+
def setup_process() -> None:
2929
fix_umask()
3030

31+
assert sys.__stderr__ is not None, "sys.__stderr__ is None"
3132
try:
3233
stderr_fd = sys.__stderr__.fileno()
3334
except (ValueError, AttributeError):
3435
# Catch ValueError to catch io.UnsupportedOperation on TextIOBase
3536
# and ValueError on a closed stream.
3637
#
3738
# Catch AttributeError for stderr being None.
38-
stderr_fd = None
39+
pass
3940
else:
4041
# Display the Python traceback on fatal errors (e.g. segfault)
4142
faulthandler.enable(all_threads=True, file=stderr_fd)
@@ -68,7 +69,7 @@ def setup_process():
6869
for index, path in enumerate(module.__path__):
6970
module.__path__[index] = os.path.abspath(path)
7071
if getattr(module, '__file__', None):
71-
module.__file__ = os.path.abspath(module.__file__)
72+
module.__file__ = os.path.abspath(module.__file__) # type: ignore[type-var]
7273

7374
if hasattr(sys, 'addaudithook'):
7475
# Add an auditing hook for all tests to ensure PySys_Audit is tested
@@ -87,7 +88,7 @@ def _test_audit_hook(name, args):
8788
os.environ.setdefault(UNICODE_GUARD_ENV, FS_NONASCII)
8889

8990

90-
def setup_tests(runtests: RunTests):
91+
def setup_tests(runtests: RunTests) -> None:
9192
support.verbose = runtests.verbose
9293
support.failfast = runtests.fail_fast
9394
support.PGO = runtests.pgo

Lib/test/libregrtest/tsan.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,6 @@
2828
]
2929

3030

31-
def setup_tsan_tests(cmdline_args):
31+
def setup_tsan_tests(cmdline_args) -> None:
3232
if not cmdline_args:
3333
cmdline_args[:] = TSAN_TESTS[:]

0 commit comments

Comments
 (0)
0