Skip to content

Commit bfc1d25

Browse files
authored
gh-109413: Add more type hints to libregrtest (#126352)
1 parent fe5a6ab commit bfc1d25

File tree

12 files changed

+71
-63
lines changed

12 files changed

+71
-63
lines changed

Lib/test/libregrtest/findtests.py

+8-6
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

+15-14
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

@@ -154,7 +155,7 @@ def __init__(self, ns: Namespace, _add_python_opts: bool = False):
154155
self.next_single_test: TestName | None = None
155156
self.next_single_filename: StrPath | None = None
156157

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

160161
def find_tests(self, tests: TestList | None = None) -> tuple[TestTuple, TestList | None]:
@@ -230,11 +231,11 @@ def find_tests(self, tests: TestList | None = None) -> tuple[TestTuple, TestList
230231
return (tuple(selected), tests)
231232

232233
@staticmethod
233-
def list_tests(tests: TestTuple):
234+
def list_tests(tests: TestTuple) -> None:
234235
for name in tests:
235236
print(name)
236237

237-
def _rerun_failed_tests(self, runtests: RunTests):
238+
def _rerun_failed_tests(self, runtests: RunTests) -> RunTests:
238239
# Configure the runner to re-run tests
239240
if self.num_workers == 0 and not self.single_process:
240241
# Always run tests in fresh processes to have more deterministic
@@ -266,7 +267,7 @@ def _rerun_failed_tests(self, runtests: RunTests):
266267
self.run_tests_sequentially(runtests)
267268
return runtests
268269

269-
def rerun_failed_tests(self, runtests: RunTests):
270+
def rerun_failed_tests(self, runtests: RunTests) -> None:
270271
if self.python_cmd:
271272
# Temp patch for https://github.com/python/cpython/issues/94052
272273
self.log(
@@ -335,7 +336,7 @@ def run_bisect(self, runtests: RunTests) -> None:
335336
if not self._run_bisect(runtests, name, progress):
336337
return
337338

338-
def display_result(self, runtests):
339+
def display_result(self, runtests: RunTests) -> None:
339340
# If running the test suite for PGO then no one cares about results.
340341
if runtests.pgo:
341342
return
@@ -365,7 +366,7 @@ def run_test(
365366

366367
return result
367368

368-
def run_tests_sequentially(self, runtests) -> None:
369+
def run_tests_sequentially(self, runtests: RunTests) -> None:
369370
if self.coverage:
370371
tracer = trace.Trace(trace=False, count=True)
371372
else:
@@ -422,7 +423,7 @@ def run_tests_sequentially(self, runtests) -> None:
422423
if previous_test:
423424
print(previous_test)
424425

425-
def get_state(self):
426+
def get_state(self) -> str:
426427
state = self.results.get_state(self.fail_env_changed)
427428
if self.first_state:
428429
state = f'{self.first_state} then {state}'
@@ -452,7 +453,7 @@ def finalize_tests(self, coverage: trace.CoverageResults | None) -> None:
452453
if self.junit_filename:
453454
self.results.write_junit(self.junit_filename)
454455

455-
def display_summary(self):
456+
def display_summary(self) -> None:
456457
duration = time.perf_counter() - self.logger.start_time
457458
filtered = bool(self.match_tests)
458459

@@ -466,7 +467,7 @@ def display_summary(self):
466467
state = self.get_state()
467468
print(f"Result: {state}")
468469

469-
def create_run_tests(self, tests: TestTuple):
470+
def create_run_tests(self, tests: TestTuple) -> RunTests:
470471
return RunTests(
471472
tests,
472473
fail_fast=self.fail_fast,
@@ -674,9 +675,9 @@ def _execute_python(self, cmd, environ):
674675
f"Command: {cmd_text}")
675676
# continue executing main()
676677

677-
def _add_python_opts(self):
678-
python_opts = []
679-
regrtest_opts = []
678+
def _add_python_opts(self) -> None:
679+
python_opts: list[str] = []
680+
regrtest_opts: list[str] = []
680681

681682
environ, keep_environ = self._add_cross_compile_opts(regrtest_opts)
682683
if self.ci_mode:
@@ -709,7 +710,7 @@ def _init(self):
709710

710711
self.tmp_dir = get_temp_dir(self.tmp_dir)
711712

712-
def main(self, tests: TestList | None = None):
713+
def main(self, tests: TestList | None = None) -> NoReturn:
713714
if self.want_add_python_opts:
714715
self._add_python_opts()
715716

@@ -738,7 +739,7 @@ def main(self, tests: TestList | None = None):
738739
sys.exit(exitcode)
739740

740741

741-
def main(tests=None, _add_python_opts=False, **kwargs):
742+
def main(tests=None, _add_python_opts=False, **kwargs) -> NoReturn:
742743
"""Run the Python suite."""
743744
ns = _parse_args(sys.argv[1:], **kwargs)
744745
Regrtest(ns, _add_python_opts=_add_python_opts).main(tests=tests)

Lib/test/libregrtest/pgo.py

+1-1
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

+1-1
Original file line numberDiff line numberDiff line change
@@ -262,7 +262,7 @@ def dash_R_cleanup(fs, ps, pic, zdc, abcs):
262262
sys._clear_internal_caches()
263263

264264

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

Lib/test/libregrtest/result.py

+1
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

+7-7
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ def get_state(self, fail_env_changed: bool) -> str:
7171

7272
return ', '.join(state)
7373

74-
def get_exitcode(self, fail_env_changed, fail_rerun):
74+
def get_exitcode(self, fail_env_changed: bool, fail_rerun: bool) -> int:
7575
exitcode = 0
7676
if self.bad:
7777
exitcode = EXITCODE_BAD_TEST
@@ -87,7 +87,7 @@ def get_exitcode(self, fail_env_changed, fail_rerun):
8787
exitcode = EXITCODE_BAD_TEST
8888
return exitcode
8989

90-
def accumulate_result(self, result: TestResult, runtests: RunTests):
90+
def accumulate_result(self, result: TestResult, runtests: RunTests) -> None:
9191
test_name = result.test_name
9292
rerun = runtests.rerun
9393
fail_env_changed = runtests.fail_env_changed
@@ -135,7 +135,7 @@ def get_coverage_results(self) -> trace.CoverageResults:
135135
counts = {loc: 1 for loc in self.covered_lines}
136136
return trace.CoverageResults(counts=counts)
137137

138-
def need_rerun(self):
138+
def need_rerun(self) -> bool:
139139
return bool(self.rerun_results)
140140

141141
def prepare_rerun(self, *, clear: bool = True) -> tuple[TestTuple, FilterDict]:
@@ -158,7 +158,7 @@ def prepare_rerun(self, *, clear: bool = True) -> tuple[TestTuple, FilterDict]:
158158

159159
return (tuple(tests), match_tests_dict)
160160

161-
def add_junit(self, xml_data: list[str]):
161+
def add_junit(self, xml_data: list[str]) -> None:
162162
import xml.etree.ElementTree as ET
163163
for e in xml_data:
164164
try:
@@ -167,7 +167,7 @@ def add_junit(self, xml_data: list[str]):
167167
print(xml_data, file=sys.__stderr__)
168168
raise
169169

170-
def write_junit(self, filename: StrPath):
170+
def write_junit(self, filename: StrPath) -> None:
171171
if not self.testsuite_xml:
172172
# Don't create empty XML file
173173
return
@@ -192,7 +192,7 @@ def write_junit(self, filename: StrPath):
192192
for s in ET.tostringlist(root):
193193
f.write(s)
194194

195-
def display_result(self, tests: TestTuple, quiet: bool, print_slowest: bool):
195+
def display_result(self, tests: TestTuple, quiet: bool, print_slowest: bool) -> None:
196196
if print_slowest:
197197
self.test_times.sort(reverse=True)
198198
print()
@@ -234,7 +234,7 @@ def display_result(self, tests: TestTuple, quiet: bool, print_slowest: bool):
234234
print()
235235
print("Test suite interrupted by signal SIGINT.")
236236

237-
def display_summary(self, first_runtests: RunTests, filtered: bool):
237+
def display_summary(self, first_runtests: RunTests, filtered: bool) -> None:
238238
# Total tests
239239
stats = self.stats
240240
text = f'run={stats.tests_run:,}'

Lib/test/libregrtest/runtests.py

+8-8
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) -> 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

+5-4
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

+1-1
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)