Repository navigation
Expand file tree
/
Copy pathrunner.py
More file actions
1683 lines (1450 loc) · 63.2 KB
/
Copy pathrunner.py
File metadata and controls
1683 lines (1450 loc) · 63.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) 2020, 2026, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# The Universal Permissive License (UPL), Version 1.0
#
# Subject to the condition set forth below, permission is hereby granted to any
# person obtaining a copy of this software, associated documentation and/or
# data (collectively the "Software"), free of charge and under any and all
# copyright rights in the Software, and any and all patent rights owned or
# freely licensable by each licensor hereunder covering either (i) the
# unmodified Software as contributed to or provided by such licensor, or (ii)
# the Larger Works (as defined below), to deal in both
#
# (a) the Software, and
#
# (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
# one is included with the Software each a "Larger Work" to which the Software
# is contributed by such licensors),
#
# without restriction, including without limitation the rights to copy, create
# derivative works of, display, perform, and distribute the Software and make,
# use, sell, offer for sale, import, export, have made, and have sold the
# Software and the Larger Work(s), and to sublicense the foregoing rights on
# either these or other terms.
#
# This license is subject to the following condition:
#
# The above copyright notice and either this complete permission notice or at a
# minimum a reference to the UPL must be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import argparse
import concurrent.futures
import enum
import fnmatch
import json
import os
import pickle
import platform
import re
import select
import shlex
import signal
import socket
import subprocess
import sys
import tempfile
import threading
import time
import tomllib
import traceback
import typing
import unittest
import unittest.loader
import urllib.request
from abc import abstractmethod
from collections import defaultdict
from dataclasses import dataclass, field
from functools import lru_cache
from pathlib import Path
from textwrap import dedent
DIR = Path(__file__).parent.resolve()
GRAALPYTHON_DIR = DIR.parent.parent.resolve()
UNIT_TEST_ROOT = (DIR / 'tests').resolve()
TAGGED_TEST_ROOT = (GRAALPYTHON_DIR / 'lib-python' / '3' / 'test').resolve()
IS_GRAALPY = sys.implementation.name == 'graalpy'
IS_WINDOWS = sys.platform == 'win32'
PLATFORM_KEYS = {sys.platform, platform.machine(), sys.implementation.name}
if IS_GRAALPY:
# noinspection PyUnresolvedReferences
PLATFORM_KEYS.add('native_image' if __graalpython__.is_native else 'jvm')
CURRENT_PLATFORM = f'{sys.platform}-{platform.machine()}'
CURRENT_PLATFORM_KEYS = frozenset({CURRENT_PLATFORM})
RUNNER_ENV = {}
DISABLE_JIT_ENV = {'GRAAL_PYTHON_VM_ARGS': '-X jit=0'}
# The worker transport sends pickled data, so keep it on loopback only.
WORKER_SERVER_HOST = '127.0.0.1'
GITHUB_CI = os.environ.get("GITHUB_CI", None)
if GITHUB_CI:
PLATFORM_KEYS.add("github")
CURRENT_PLATFORM += "-github"
# We leave the JIT enabled for the tests themselves, but disable it for subprocesses
# noinspection PyUnresolvedReferences
if IS_GRAALPY and 'GRAAL_PYTHON_VM_ARGS' not in os.environ:
RUNNER_ENV = DISABLE_JIT_ENV
class Logger:
report_incomplete = sys.stdout.isatty()
def __init__(self):
self.lock = threading.RLock()
self.incomplete_line = None
def log(self, msg='', incomplete=False):
if incomplete and not self.report_incomplete:
return
with self.lock:
end = ('' if incomplete else None)
if self.report_incomplete and self.incomplete_line:
first_line, newline, rest = msg.partition('\n')
pad = len(self.incomplete_line)
print(f"\r{first_line:{pad}}{newline}{rest}", file=sys.stderr, end=end, flush=True)
else:
print(msg, file=sys.stderr, end=end, flush=True)
self.incomplete_line = msg if incomplete else None
logger = Logger()
log = logger.log
class TestStatus(enum.StrEnum):
SUCCESS = "ok"
FAILURE = "FAIL"
ERROR = "ERROR"
SKIPPED = "skipped"
EXPECTED_FAILURE = "expected failure"
UNEXPECTED_SUCCESS = "unexpected success"
SUCCESSFUL_STATES = TestStatus.SUCCESS, TestStatus.SKIPPED, TestStatus.EXPECTED_FAILURE
FAILED_STATES = TestStatus.FAILURE, TestStatus.ERROR, TestStatus.UNEXPECTED_SUCCESS
@dataclass(repr=False, frozen=True)
class TestId:
test_file: Path
test_name: str
def __repr__(self):
return f'{self.test_file}::{self.test_name}'
def normalized(self):
return TestId(self.test_file.resolve(), self.test_name)
@classmethod
def from_str(cls, s: str):
test_file, _, test_id = s.partition('::')
if test_id is None:
raise ValueError(f"Invalid test ID {s}")
return cls(Path(test_file), test_id)
@classmethod
def from_test_case(cls, test_file: Path, test: unittest.TestCase):
test_id = test.id()
if type(test).__module__ == 'unittest.suite' and type(test).__name__ == '_ErrorHolder':
if match := re.match(r'(\S+) \(([^)]+)\)', test_id):
action = match.group(1)
class_name = match.group(2)
if 'Module' in action:
test_id = f'<{action}>'
else:
test_id = f'{class_name}.<{action}>'
elif type(test).id is not unittest.TestCase.id and type(test) is not unittest.FunctionTestCase:
# Qualify doctests so that we know what they are
test_id = f'{type(test).__qualname__}.{test_id}'
return cls(test_file, test_id)
@dataclass(frozen=True)
class TestSpecifier:
test_file: Path
test_name: str | None
def __repr__(self):
if self.test_name is None:
return str(self.test_file)
return f'{self.test_file}::{self.test_name}'
def with_test_file(self, test_file: Path):
return TestSpecifier(test_file, self.test_name)
@classmethod
def from_str(cls, s: str):
test_file, _, test_id = s.partition('::')
return cls(Path(test_file), test_id or None)
def match(self, test_id: TestId):
# Globs in path are expanded when processing specifiers
if self.test_file != test_id.test_file:
return False
if self.test_name is None:
return True
if '*' in self.test_name:
pattern = re.escape(self.test_name).replace(r'\*', '.*') + r'($|\..*)'
return re.match(pattern, test_id.test_name)
return self.test_name == test_id.test_name or test_id.test_name.startswith(self.test_name + '.')
@dataclass
class TestResult:
test_id: TestId
status: TestStatus
param: str | None = None
output: str = ''
duration: float = 0.0
def format_exception(exc):
tb = exc.__traceback__
while tb and '__unittest' in tb.tb_frame.f_globals:
tb = tb.tb_next
exc.__traceback__ = tb
return ''.join(traceback.format_exception(exc))
def out_tell():
try:
return os.lseek(1, 0, os.SEEK_CUR)
except OSError:
return 0
T = typing.TypeVar('T')
def partition_list(l: list[T], fn: typing.Callable[[T], bool]) -> tuple[list[T], list[T]]:
a = []
b = []
for item in l:
(a if fn(item) else b).append(item)
return a, b
class AbstractResult(unittest.TestResult):
def __init__(self, test_suite: 'TestSuite'):
super().__init__()
self.test_suite = test_suite
self.start_time = None
def test_id(self, test):
return TestId.from_test_case(self.test_suite.test_file.path, test)
def startTest(self, test):
self.start_time = time.time()
@abstractmethod
def report_result(self, result: TestResult):
pass
def make_result(self, test, status: TestStatus, **kwargs):
duration = 0.0
if self.start_time:
duration = time.time() - self.start_time
return TestResult(status=status, test_id=self.test_id(test), duration=duration, **kwargs)
def addSuccess(self, test):
super().addSuccess(test)
self.report_result(self.make_result(test, status=TestStatus.SUCCESS))
def addFailure(self, test, err):
super().addFailure(test, err)
self.report_result(self.make_result(test, status=TestStatus.FAILURE, param=format_exception(err[1])))
def addSubTest(self, test, subtest, err):
super().addSubTest(test, subtest, err)
if err:
if issubclass(err[0], test.failureException):
status = TestStatus.FAILURE
else:
status = TestStatus.ERROR
self.report_result(self.make_result(test, status=status, param=format_exception(err[1])))
def addError(self, test, err):
super().addError(test, err)
self.report_result(self.make_result(test, status=TestStatus.ERROR, param=format_exception(err[1])))
def addSkip(self, test, reason):
super().addSkip(test, reason)
self.report_result(self.make_result(test, status=TestStatus.SKIPPED, param=reason))
def addExpectedFailure(self, test, err):
super().addExpectedFailure(test, err)
self.report_result(self.make_result(test, status=TestStatus.EXPECTED_FAILURE, param=format_exception(err[1])))
def addUnexpectedSuccess(self, test):
super().addUnexpectedSuccess(test)
self.report_result(self.make_result(test, status=TestStatus.UNEXPECTED_SUCCESS))
class DirectResult(AbstractResult):
def __init__(self, test_suite: 'TestSuite', test_runner: 'TestRunner'):
super().__init__(test_suite)
self.runner = test_runner
def report_result(self, result: TestResult):
self.runner.report_result(result)
def startTest(self, test):
super().startTest(test)
self.runner.report_start(self.test_id(test))
class AbstractRemoteResult(AbstractResult):
@abstractmethod
def emit(self, **data):
pass
def report_result(self, result: TestResult):
self.emit(
event='testResult',
status=result.status,
test=result.test_id,
param=result.param,
out_pos=out_tell(),
duration=result.duration,
)
def startTest(self, test):
super().startTest(test)
self.emit(
event='testStarted',
test=self.test_id(test),
out_pos=out_tell(),
)
class ConnectionResult(AbstractRemoteResult):
def __init__(self, test_suite: 'TestSuite', conn):
super().__init__(test_suite)
self.conn = conn
def emit(self, **data):
self.conn.send(data)
class SimpleResult(AbstractRemoteResult):
def __init__(self, test_suite: 'TestSuite', data: list[dict]):
super().__init__(test_suite)
self.data = data
def emit(self, **data):
self.data.append(data)
def test_path_to_module(test_file: 'TestFile'):
path = test_file.path.resolve().relative_to(test_file.config.rootdir)
return str(path).removesuffix('.py').replace(os.sep, '.')
class TestRunner:
def __init__(self, *, failfast: bool, report_durations: int | None):
self.failfast = failfast
self.report_durations = report_durations
self.results: list[TestResult] = []
self.total_duration = 0.0
@staticmethod
def report_start(test_id: TestId, prefix=''):
log(f"{prefix}{test_id} ... ", incomplete=True)
def report_result(self, result: TestResult, prefix=''):
self.results.append(result)
message = f"{result.test_id} ... {result.status}"
if result.status == TestStatus.SKIPPED and result.param:
message = f"{prefix}{message} {result.param!r}"
else:
message = f"{prefix}{message} ({result.duration:.2f}s)"
log(message)
def tests_failed(self):
return any(result.status in FAILED_STATES for result in self.results)
def display_summary(self):
counts = defaultdict(int)
for result in self.results:
counts[result.status] += 1
log()
if self.results and self.report_durations:
slowest_tests = sorted(self.results, key=lambda r: r.duration, reverse=True)
if self.report_durations > 0:
slowest_tests = slowest_tests[:self.report_durations]
log("Slowest test durations:")
for result in slowest_tests:
log(f"- {result.test_id}: {result.duration:.2f}s")
log()
for result in self.results:
fail_type = None
match result.status:
case TestStatus.ERROR:
fail_type = 'ERROR'
case TestStatus.FAILURE:
fail_type = 'FAIL'
case TestStatus.UNEXPECTED_SUCCESS:
fail_type = 'UNEXPECTED SUCCESS'
if fail_type:
log("======================================================================")
log(f"{fail_type}: {result.test_id}")
log("----------------------------------------------------------------------")
if result.param:
log(result.param.rstrip('\n'))
if result.output:
log("------------------------- captured output ----------------------------")
log(result.output.rstrip('\n'))
log()
items = []
def add_item(status, name):
if counts[status]:
items.append(f"{name}={counts[status]}")
add_item(TestStatus.SUCCESS, "passed")
add_item(TestStatus.FAILURE, "failures")
add_item(TestStatus.ERROR, "errors")
add_item(TestStatus.SKIPPED, "skipped")
add_item(TestStatus.EXPECTED_FAILURE, "expected failures")
add_item(TestStatus.UNEXPECTED_SUCCESS, "unexpected successes")
total = sum(counts.values())
log(f"Ran {total} tests in {self.total_duration:.2f}s")
log()
summary = ", ".join(items)
overall_status = 'FAILED' if self.tests_failed() else 'OK'
if summary:
log(f"{overall_status} ({summary})")
else:
log(overall_status)
if self.failfast and self.tests_failed():
log("\nWARNING: Did not execute all tests because 'failfast' mode is on")
def run_tests(self, tests: list['TestSuite']):
start_time = time.time()
for test_suite in tests:
result = DirectResult(test_suite, self)
result.failfast = self.failfast
test_suite.run(result)
self.total_duration = time.time() - start_time
self.display_summary()
def generate_mx_report(self, path: str):
# Some reports may be split when ran on github, this sets different file names
report_suffix = os.environ.get("MX_REPORT_SUFFIX")
if report_suffix:
if os.environ.get("GITHUB_CI"):
report_suffix = f"{report_suffix}_{CURRENT_PLATFORM}"
tmppath, ext = os.path.splitext(path)
path = f"{tmppath}{report_suffix}{ext}"
report_data = []
for result in self.results:
# Skip synthetic results for failed class setups and such
if '<' in result.test_id.test_name:
continue
match result.status:
case TestStatus.SUCCESS | TestStatus.EXPECTED_FAILURE:
status = 'PASSED'
case TestStatus.SKIPPED:
status = 'IGNORED'
case _:
status = 'FAILED'
report_data.append({
'name': str(result.test_id).replace('\\', '/'),
'status': status,
'duration': result.duration,
})
with open(path, 'w') as f:
# noinspection PyTypeChecker
json.dump(report_data, f)
def generate_tags(self, append=False):
by_file = defaultdict(list)
for result in self.results:
by_file[result.test_id.test_file].append(result)
for test_file, results in by_file.items():
test_file = configure_test_file(test_file)
update_tags(
test_file,
results,
tag_platform=CURRENT_PLATFORM,
untag_failed=(not append),
untag_skipped=(not append),
untag_missing=(not append),
)
def update_tags(test_file: 'TestFile', results: list[TestResult], tag_platform: str,
untag_failed=False, untag_skipped=False, untag_missing=False):
current = read_tags(test_file, allow_exclusions=True)
exclusions, current = partition_list(current, lambda t: t.is_exclusion)
status_by_id = {r.test_id.normalized(): r.status for r in results}
tag_by_id = {}
for tag in current:
if untag_missing and tag.test_id not in status_by_id:
tag = tag.without_key(tag_platform)
if tag:
tag_by_id[tag.test_id] = tag
for test_id, status in status_by_id.items():
if tag := tag_by_id.get(test_id):
if status == TestStatus.SUCCESS:
tag_by_id[test_id] = tag.with_key(tag_platform)
elif (untag_skipped and status == TestStatus.SKIPPED
or untag_failed and status == TestStatus.FAILURE):
tag = tag.without_key(tag_platform)
if tag:
tag_by_id[test_id] = tag
else:
del tag_by_id[test_id]
elif status == TestStatus.SUCCESS:
tag_by_id[test_id] = Tag.for_key(test_id, tag_platform)
for exclusion in exclusions:
if tag := tag_by_id.get(exclusion.test_id):
if exclusion.keys:
tag = tag.without_keys(exclusion.keys)
else:
tag = None
if not tag:
del tag_by_id[exclusion.test_id]
else:
tag_by_id[exclusion.test_id] = tag
tags = set(tag_by_id.values()) | set(exclusions)
write_tags(test_file, tags)
def write_tags(test_file: 'TestFile', tags: typing.Iterable['Tag']):
tag_file = test_file.get_tag_file()
if not tag_file:
log(f"WARNING: no tag directory for test file {test_file}")
return
if not tags:
tag_file.unlink(missing_ok=True)
return
with open(tag_file, 'w') as f:
for tag in sorted(tags, key=lambda t: (t.test_id.test_name, t.is_exclusion)):
f.write(f'{tag}\n')
def interrupt_process(process: subprocess.Popen):
if IS_WINDOWS:
# Timed-out tests may leave descendants holding the worker's redirected output file open. Kill the whole
# process tree because Windows cannot remove that file while any descendant still has an open handle to it.
# Do this before trying SIGINT: if the parent exits first, taskkill can no longer discover its descendants.
try:
subprocess.run(
['taskkill', '/PID', str(process.pid), '/T', '/F'],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
process.wait()
return
except (OSError, subprocess.CalledProcessError):
pass
if hasattr(signal, 'SIGINT'):
try:
process.send_signal(signal.SIGINT)
process.wait(3)
return
except (OSError, ValueError, subprocess.TimeoutExpired):
pass
process.terminate()
try:
process.wait(3)
except subprocess.TimeoutExpired:
process.kill()
class ParallelTestRunner(TestRunner):
def __init__(self, *, num_processes, subprocess_args, separate_workers, timeout_factor, **kwargs):
super().__init__(**kwargs)
self.num_processes = num_processes
self.subprocess_args = subprocess_args
self.separate_workers = separate_workers
self.timeout_factor = timeout_factor
self.stop_event = threading.Event()
self.crashes = []
self.default_test_timeout = 600
def report_result(self, result: TestResult, prefix=''):
if self.failfast and result.status in FAILED_STATES:
self.stop_event.set()
super().report_result(result, prefix=prefix)
def tests_failed(self):
return super().tests_failed() or bool(self.crashes)
def partition_tests_into_processes(self, suites: list['TestSuite']) -> list[list['Test']]:
if self.separate_workers:
per_file_suites = suites
unpartitioned = []
else:
per_file_suites, unpartitioned = partition_list(
suites,
lambda suite: suite.test_file.config.new_worker_per_file or suite.test_file.test_config.subprocess_args,
)
partitions = [suite.collected_tests for suite in per_file_suites]
# Use timings if available to partition unpartitioned optimally
timings = {}
if unpartitioned and self.num_processes:
configdir = unpartitioned[0].test_file.config.configdir if unpartitioned else None
if configdir:
timing_path = configdir / f"timings-{sys.platform.lower()}.json"
if timing_path.exists():
with open(timing_path, "r", encoding="utf-8") as f:
timings = json.load(f)
timed_files = []
for suite in unpartitioned:
file_path = str(suite.test_file.path).replace("\\", "/")
total = timings.get(file_path, 20.0)
timed_files.append((total, suite))
# Sort descending by expected time
timed_files.sort(reverse=True, key=lambda x: x[0])
# Greedily assign to balance by timing sum
process_loads = [[] for _ in range(min(self.num_processes, len(timed_files)))]
process_times = [0.0] * self.num_processes
for t, suite in timed_files:
i = process_times.index(min(process_times))
process_loads[i].append(suite)
process_times[i] += t
for group in process_loads:
partitions.append([test for suite in group for test in suite.collected_tests])
return partitions
def run_tests(self, tests: list['TestSuite']):
serial_suites, parallel_suites = partition_list(
tests,
lambda suite: suite.test_file.test_config.serial,
)
parallel_partitions = self.partition_tests_into_processes(parallel_suites)
serial_partitions = self.partition_tests_into_processes(serial_suites)
start_time = time.time()
if parallel_partitions:
num_processes = max(1, min(self.num_processes, len(parallel_partitions)))
with concurrent.futures.ThreadPoolExecutor(num_processes) as executor:
self.run_partitions_in_subprocesses(executor, parallel_partitions)
if serial_partitions:
with concurrent.futures.ThreadPoolExecutor(1) as executor:
self.run_partitions_in_subprocesses(executor, serial_partitions)
self.total_duration = time.time() - start_time
self.display_summary()
if self.crashes:
for crash in self.crashes:
log('Internal error, test worker crashed outside of tests:')
log(crash)
def run_partitions_in_subprocesses(self, executor, partitions: list[list['Test']]):
workers = [SubprocessWorker(i, self, partition) for i, partition in enumerate(partitions)]
futures = [executor.submit(worker.run_in_subprocess_and_watch) for worker in workers]
def dump_worker_status():
with logger.lock:
log("=" * 80)
log("Dumping test worker status:")
for i, partition in enumerate(partitions):
not_started = 0
if futures[i].running():
log(f"Worker on {workers[i].thread}: {workers[i].get_status()}")
elif not futures[i].done():
not_started += len(partition)
if not_started:
log(f"There are {not_started} tests not assigned to any worker")
log("=" * 80)
try:
def sigterm_handler(_signum, _frame):
dump_worker_status()
# noinspection PyUnresolvedReferences,PyProtectedMember
os._exit(1)
prev_sigterm = signal.signal(signal.SIGTERM, sigterm_handler)
except Exception:
prev_sigterm = None
try:
try:
concurrent.futures.wait(futures)
for future in futures:
future.result()
except KeyboardInterrupt:
log("Received keyboard interrupt, stopping")
dump_worker_status()
self.stop_event.set()
concurrent.futures.wait(futures)
sys.exit(1)
finally:
if prev_sigterm:
signal.signal(signal.SIGTERM, prev_sigterm)
class SubprocessWorker:
def __init__(self, worker_id: int, runner: ParallelTestRunner, tests: list['Test']):
self.prefix = f'[worker-{worker_id + 1}] '
self.runner = runner
self.subprocess_args = tests[0].test_file.test_config.subprocess_args
assert all(test.test_file.test_config.subprocess_args == self.subprocess_args for test in tests)
self.stop_event = runner.stop_event
self.lock = threading.RLock()
self.remaining_test_ids = [test.test_id for test in tests]
self.tests_by_id = {test.test_id: test for test in tests}
self.out_file: typing.TextIO | None = None
self.last_started_test_id: TestId | None = None
self.last_started_time: float | None = None
self.last_out_pos = 0
self.last_test_id_for_blame: TestId | None = None
self.process: subprocess.Popen | None = None
self.thread = None
def process_event(self, event):
test_id = event['test']
match event['event']:
case 'testStarted':
try:
self.remaining_test_ids.remove(test_id)
except ValueError:
# It executed something we didn't ask for. Not sure why this happens
log(f'WARNING: unexpected test started {test_id}')
self.runner.report_start(test_id, prefix=self.prefix)
with self.lock:
self.last_started_test_id = test_id
self.last_started_time = time.time()
self.last_out_pos = event['out_pos']
case 'testResult':
status = event['status']
out_end = event['out_pos']
test_output = ''
if self.last_out_pos != out_end:
self.out_file.seek(self.last_out_pos)
test_output = self.out_file.read(out_end - self.last_out_pos)
result = TestResult(
test_id=test_id,
status=status,
param=event.get('param'),
output=test_output,
duration=event.get('duration'),
)
self.runner.report_result(result, prefix=self.prefix)
with self.lock:
self.last_started_test_id = None
self.last_started_time = time.time() # Starts timeout for the following teardown/setup
self.last_test_id_for_blame = test_id
self.last_out_pos = event['out_pos']
if test_id.test_name.endswith('>'):
class_name = test_id.test_name[:test_id.test_name.find('<')].rstrip('.')
specifier = TestSpecifier(test_id.test_file, class_name or None)
self.remaining_test_ids = [
test for test in self.remaining_test_ids if not specifier.match(test)
]
def get_status(self):
with self.lock:
if not self.process:
process_status = "not started"
elif self.process.poll() is not None:
process_status = f"exitted with code {self.process.returncode}"
else:
process_status = "running"
last_test_id = self.get_test_to_blame()
if last_test_id is not None:
if last_test_id is not self.last_started_test_id:
last_test_id = f'{last_test_id} (approximate)'
duration = time.time() - self.last_started_time
test_status = f"executing {last_test_id} for {duration:.2f}s"
else:
test_status = "no current test"
remaining = len(self.remaining_test_ids)
return f"test: {test_status}; remaining: {remaining}; process status: {process_status}"
def get_test_to_blame(self):
if self.last_started_test_id:
return self.last_started_test_id
# XXX unittest doesn't report module/class setups/teardowns, so if a test hard crashes or times out during
# those, we can't tell which one is to blame. So we make a combined result for both as a last resort
next_test_id = self.remaining_test_ids[0] if self.remaining_test_ids else None
if self.last_test_id_for_blame is None:
return TestId(next_test_id.test_file, f'<before> {next_test_id}')
if next_test_id is None:
return TestId(self.last_test_id_for_blame.test_file, f'<after> {self.last_test_id_for_blame}')
return TestId(
Path(''),
f'<between> {self.last_test_id_for_blame} <and> {next_test_id}',
)
def run_in_subprocess_and_watch(self):
self.thread = threading.current_thread()
with (
# Do not lose the test report if a leaked Windows process still has the diagnostic output file open.
tempfile.TemporaryDirectory(
prefix='graalpytest-', ignore_cleanup_errors=IS_WINDOWS
) as tmp_dir,
socket.create_server((WORKER_SERVER_HOST, 0)) as server,
):
tmp_dir = Path(tmp_dir)
port = server.getsockname()[1]
assert port
retries = 3
while self.remaining_test_ids and not self.stop_event.is_set():
last_remaining_count = len(self.remaining_test_ids)
with open(tmp_dir / 'out', 'w+') as self.out_file:
self.last_out_pos = 0
self.last_started_time = time.time()
cmd = [
sys.executable,
*self.runner.subprocess_args,
*self.subprocess_args,
'-u',
__file__,
'worker',
'--port', str(port),
]
if self.runner.failfast:
cmd.append('--failfast')
self.process = None
try:
self.process = subprocess.Popen(cmd, stdout=self.out_file, stderr=self.out_file)
server.settimeout(180.0)
sock = server.accept()[0]
except (TimeoutError, OSError):
if self.process:
interrupt_process(self.process)
retries -= 1
if retries:
continue
sys.exit("Worker failed to start/connect to runner multiple times")
with sock:
conn = Connection(sock)
conn.send([TestSpecifier(t.test_file, t.test_name) for t in self.remaining_test_ids])
timed_out = None
try:
while True:
while conn.poll(0.1):
event = conn.recv()
self.process_event(event)
if self.stop_event.is_set():
interrupt_process(self.process)
break
if self.last_started_test_id:
last_started_test = self.tests_by_id.get(self.last_started_test_id)
timeout = (
last_started_test.test_file.test_config.per_test_timeout
or self.runner.default_test_timeout
)
else:
timeout = self.runner.default_test_timeout
timeout *= self.runner.timeout_factor
if time.time() - self.last_started_time >= timeout:
interrupt_process(self.process)
timed_out = timeout
break
except (ConnectionClosed, OSError):
# The socket closed or got connection reset, that's normal if the worker exitted or crashed
pass
try:
self.process.wait(self.runner.default_test_timeout)
except subprocess.TimeoutExpired:
log("Warning: Worker didn't shutdown in a timely manner, interrupting it")
interrupt_process(self.process)
returncode = self.process.wait()
if self.stop_event.is_set():
return
if returncode != 0 or timed_out is not None:
self.out_file.seek(self.last_out_pos)
output = self.out_file.read()
if timed_out is not None:
message = f"Timed out in {timed_out}s"
elif returncode >= 0:
message = f"Test process exitted with code {returncode}"
else:
try:
signal_name = signal.Signals(-returncode).name
except ValueError:
signal_name = str(-returncode)
message = f"Test process killed by signal {signal_name}"
blame_id = self.get_test_to_blame()
self.runner.report_result(TestResult(
test_id=blame_id,
status=TestStatus.ERROR,
param=message,
output=output,
duration=(time.time() - self.last_started_time),
), prefix=self.prefix)
if blame_id is not self.last_started_test_id:
# If we're here, it means we didn't know exactly which test we were executing, we were
# somewhere in between
if self.last_test_id_for_blame:
# Retry the same test again, if it crashes again, we would get into the else branch
self.last_started_test_id = None
self.last_test_id_for_blame = None
continue
else:
# The current test caused the crash for sure, continue with the next
if self.remaining_test_ids:
del self.remaining_test_ids[0]
self.last_started_test_id = None
if last_remaining_count == len(self.remaining_test_ids):
log(f"Worker is not making progress, remaining: {self.remaining_test_ids}")
def platform_keys_match(items: typing.Iterable[str]):
matches = []
for item in items:
if GITHUB_CI:
if not "github" in item.split('-'):
continue
matches.append(all(key in PLATFORM_KEYS for key in item.split('-')))
return any(matches)
@dataclass
class TestFileConfig:
serial: bool | None = None
partial_splits: bool | None = None
per_test_timeout: float | None = None
subprocess_args: tuple[str, ...] = ()
exclude: bool = False
@classmethod
def from_dict(cls, config: dict):
subprocess_args = tuple(config.get('subprocess_args', ()))
subprocess_args_on = config.get('subprocess_args_on')
if subprocess_args and subprocess_args_on is not None and not platform_keys_match(subprocess_args_on):
subprocess_args = ()
return cls(
serial=config.get('serial', cls.serial),
partial_splits=config.get('partial_splits_individual_tests', cls.partial_splits),
per_test_timeout=config.get('per_test_timeout', cls.per_test_timeout),
subprocess_args=subprocess_args,
exclude=platform_keys_match(config.get('exclude_on', ())),
)
def combine(self, other: 'TestFileConfig'):
return TestFileConfig(
serial=(self.serial if other.serial is None else other.serial),
partial_splits=(self.partial_splits if other.partial_splits is None else other.partial_splits),
per_test_timeout=(self.per_test_timeout if other.per_test_timeout is None else other.per_test_timeout),
subprocess_args=self.subprocess_args + other.subprocess_args,
exclude=self.exclude or other.exclude,
)
class TestFileRule:
def __init__(self, rule: dict):
selector = [name.removesuffix('.py') for name in rule['selector']]
globs, exact_matches = partition_list(selector, lambda x: '*' in x)
self.exact_matches = frozenset(exact_matches)
self.globs = [re.compile(fnmatch.translate(glob)) for glob in globs]
self.test_config = TestFileConfig.from_dict(rule)
def matches(self, name):
return name in self.exact_matches or any(glob.match(name) for glob in self.globs)
@dataclass
class Config:
configdir: Path = Path('.').resolve()
rootdir: Path = Path('.').resolve()
tags_dir: Path | None = None
run_top_level_functions: bool = False
new_worker_per_file: bool = False
rules: list[TestFileRule] = field(default_factory=list)
@classmethod
@lru_cache
def parse_config(cls, config_path: Path):
with open(config_path, 'rb') as f:
config_dict = tomllib.load(f)
settings = config_dict.get('settings', {})