Repository navigation
Expand file tree
/
Copy pathplan_local_java_tests.py
More file actions
3081 lines (2830 loc) · 118 KB
/
Copy pathplan_local_java_tests.py
File metadata and controls
3081 lines (2830 loc) · 118 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
#!/usr/bin/env python3
"""Plan, run, and report the Java tests a branch must pass before it is queued.
Pull-request CI runs the Java unit tests only. The integration tests (ITs) run
in the merge queue, and the JavaUIIT, search-it and scale suites run nightly in
openmetadata-nightly. An IT a change breaks is therefore first seen when the PR
is ejected from the queue, unless the author ran it. This planner maps the
branch diff to the unit tests and ITs it can break and builds the Maven commands
that run them in the failsafe lane and engine profile CI uses.
``.github/java-tests/impact-map.json`` holds ownership rules only: areas own code
by directory and tests by name pattern. The rest is read from the code (who names
a changed class or method, which areas call it, which engine a test assumes), and
whatever the planner cannot place runs more tests, never fewer.
python .github/scripts/plan_local_java_tests.py # list + commands
python .github/scripts/plan_local_java_tests.py --run # run + write results
python .github/scripts/plan_local_java_tests.py --run --update-pr
python .github/scripts/plan_local_java_tests.py --scope focused --run
python .github/scripts/plan_local_java_tests.py --publish-results
See ``.github/java-tests/README.md`` for how tests are selected.
"""
from __future__ import annotations
import argparse
import fnmatch
import hashlib
import json
import os
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
import time
import xml.etree.ElementTree as ET
from collections import Counter
from collections.abc import Iterable
from dataclasses import dataclass, field
from datetime import datetime, timezone
from functools import cached_property
from pathlib import Path
from typing import Any
from urllib.parse import urlparse
IMPACT_MAP = ".github/java-tests/impact-map.json"
RESULTS_DIR = "target/java-tests"
# The summary goes in the PR description. Everything a reviewer reads only on demand (each
# class run, why it was chosen, the commands) goes in the details, posted as a PR comment.
RESULTS_MARKDOWN = f"{RESULTS_DIR}/local-pr-results.md"
DETAILS_MARKDOWN = f"{RESULTS_DIR}/local-pr-results-details.md"
EVIDENCE_JSON = f"{RESULTS_DIR}/evidence.json"
BLOCK_START = "<!-- local-java-test-results:start -->"
BLOCK_END = "<!-- local-java-test-results:end -->"
# Marks the details comment, so a re-run edits it rather than adding another.
DETAILS_MARKER = "<!-- local-java-test-results:details -->"
DEFAULT_PR_HEADING = "#### Backend integration tests"
# The summary each surefire/failsafe execution prints when it finishes. Per-class lines end in
# "Time elapsed: … -- in <class>", so only the summaries match in full.
MAVEN_TOTALS = re.compile(
r"\[(?:INFO|WARNING|ERROR)\] Tests run: (\d+), Failures: (\d+), Errors: (\d+), "
r"Skipped: (\d+)(?:, Flakes: \d+)?"
)
# Surefire's default includes; openmetadata-service overrides them with the same four.
UNIT_TEST_CLASS = re.compile(r"^(Test\w+|\w+Test|\w+Tests|\w+TestCase)$")
IT_CLASS = re.compile(r"^\w+(IT|Test)$")
CONVENTION_SUFFIXES = ("Repository", "Resource", "Mapper", "Index")
MIN_STEM_LENGTH = 3
WORD = re.compile(r"[A-Za-z_]\w*")
COMMENT = re.compile(r"/\*.*?\*/|//[^\n]*", re.DOTALL)
IMPORT_OR_PACKAGE = re.compile(r"^(?:import|package)\s[^;]*;", re.MULTILINE)
HUNK_CONTEXT = re.compile(r"^@@ [^@]* @@ (.*)$")
METHOD_DECLARATION = re.compile(
r"^[+-]\s*(?:@\w+(?:\([^)]*\))?\s+)*(?:(?:public|protected|private|static|final|abstract|"
r"synchronized|default|native)\s+)*(?:<[^>]+>\s+)?[\w.$<>\[\], ?]+\s+(\w+)\s*\("
)
METHOD_BODY_START = re.compile(
r"^[ \t]*(?:@\w+(?:\([^)]*\))?\s*)*(?:(?:public|protected|private|static|final|abstract|"
r"synchronized|default|native)\s+)*(?:<[^>]+>\s+)?[\w.$<>\[\], ?]+\s+(\w+)\s*\([^;{]*\)"
r"\s*(?:throws\s+[\w.,\s]+)?\{",
re.MULTILINE,
)
NOT_METHOD_NAMES = {
"if", "for", "while", "switch", "catch", "return", "new", "throw", "else", "try",
"case", "assert", "super", "this", "synchronized",
} # fmt: skip
MIN_METHOD_NAME_LENGTH = 4
# A helper most IT classes go through (SdkClients, TestNamespace) carries a change to every IT.
UNIVERSAL_HELPER_SHARE = 0.5
# Past this share of the merge-queue lanes, a selection is the full suite in all but name.
FULL_SUITE_SHARE = 0.6
# Surefire has no switch that skips only unit tests, and `-am` would otherwise run
# every upstream module's whole suite before the ITs. `-Dmaven.test.skip` is out too:
# it skips compiling the openmetadata-service test-jar the IT module depends on. A
# filter that matches no class skips them; failIfNoSpecifiedTests=false keeps that legal.
SKIP_UNIT_TESTS = [
"-Dtest=NoUnitTestsInThisRun",
"-Dsurefire.failIfNoSpecifiedTests=false",
]
# Unit steps default to `package`, not `test` (`maven.unitPhase`): in OpenMetadata the relocated
# es.*/os.* search clients only exist once openmetadata-shaded-deps is packaged, so `test -am`
# cannot compile the service. Repackaging the k8s operator's boot jar is the one slow packaging
# step tests never need.
SKIP_REPACKAGE = "-Dspring-boot.repackage.skip=true"
INLINE_CLASS_LIMIT = 30
# GitHub rejects a PR description or comment over 65,536 characters. The class lists go in the
# details comment, next to the selection reasons and the commands. A <details> block only hides
# text, so class lists past CLASS_LIST_BUDGET are reduced to counts instead.
GITHUB_BODY_LIMIT = 65_536
CLASS_LIST_BUDGET = 20_000
# Names of failed, report-less or all-skipped classes given in the summary; the details give
# up to DETAILS_NAME_LIMIT. A run that fails outright fails every test.
SUMMARY_NAME_LIMIT = 10
DETAILS_NAME_LIMIT = 100
@dataclass
class Selection:
reasons: set[str] = field(default_factory=set)
# Engines a mapping or engine rule asked for by name. A reason that names none
# wants the default engine, which is tracked separately so that an engine-specific
# mapping can still narrow a search-it run to its own engine.
engines: set[str] = field(default_factory=set)
wants_default: bool = False
run_engines: list[str] = field(default_factory=list)
@dataclass
class Command:
kind: str
label: str
argv: list[str]
report_dirs: list[str]
expected_classes: list[str] = field(default_factory=list)
full_suite_dirs: list[str] = field(default_factory=list)
engine: str = ""
lane: str = ""
@dataclass
class Plan:
changed_files: list[str]
scope: str = "full"
deferred_commands: list[Command] = field(default_factory=list)
unit_tests: dict[str, dict[str, set[str]]] = field(default_factory=dict)
full_unit_modules: dict[str, set[str]] = field(default_factory=dict)
integration_tests: dict[str, Selection] = field(default_factory=dict)
not_run_locally: dict[str, str] = field(default_factory=dict)
unmapped_files: list[str] = field(default_factory=list)
untested_classes: list[str] = field(default_factory=list)
triggers: dict[str, set[str]] = field(default_factory=dict)
# Why every merge-queue IT runs: reason -> the changed files behind it.
full_suite: dict[str, set[str]] = field(default_factory=dict)
# Engines the changed code (anything but a test class) runs on; smoke runs on each.
smoke_engines: set[str] = field(default_factory=set)
smoke_on_default_engine: bool = False
commands: list[Command] = field(default_factory=list)
def has_tests(self) -> bool:
return bool(
self.unit_tests
or self.full_unit_modules
or self.integration_tests
or self.full_suite
)
def to_json(self) -> dict[str, Any]:
return {
"scope": self.scope,
"deferredCommands": [
display_command(c.argv) for c in self.deferred_commands
],
"changedFiles": self.changed_files,
"unitTests": {
module: {
name: sorted(reasons) for name, reasons in sorted(tests.items())
}
for module, tests in sorted(self.unit_tests.items())
},
"fullUnitModules": {
module: sorted(reasons)
for module, reasons in sorted(self.full_unit_modules.items())
},
"integrationTests": {
path: {"reasons": sorted(sel.reasons), "engines": sel.run_engines}
for path, sel in sorted(self.integration_tests.items())
},
"fullSuite": {
reason: sorted(files)
for reason, files in sorted(self.full_suite.items())
},
"notRunLocally": dict(sorted(self.not_run_locally.items())),
"unmappedFiles": self.unmapped_files,
"untestedClasses": self.untested_classes,
"triggers": {
name: sorted(files) for name, files in sorted(self.triggers.items())
},
"commands": [
{"kind": c.kind, "label": c.label, "command": shlex.join(c.argv)}
for c in self.commands
],
}
def git(repo_root: Path, *args: str) -> str:
return subprocess.run(
["git", *args], cwd=repo_root, check=True, capture_output=True, text=True
).stdout.strip()
def matches(path: str, patterns: list[str]) -> bool:
return any(fnmatch.fnmatchcase(path, pattern) for pattern in patterns)
def simple_name(path: str) -> str:
return path.rsplit("/", 1)[-1].rsplit(".", 1)[0]
def class_fqn(path: str) -> str | None:
"""Fully qualified name of the class a Java source file declares."""
for root in ("/src/main/java/", "/src/test/java/"):
if root in path and path.endswith(".java"):
return path.split(root, 1)[1][: -len(".java")].replace("/", ".")
return None
def class_header(text: str, name: str) -> str | None:
"""The annotations and declaration of class `name` in a Java source, without comments."""
text = COMMENT.sub(" ", text)
declaration = re.search(rf"\bclass\s+{re.escape(name)}\b", text)
if not declaration:
return None
start = 0
for statement in IMPORT_OR_PACKAGE.finditer(text, 0, declaration.start()):
start = statement.end()
return text[start : declaration.end()]
def is_pattern(test: str) -> bool:
"""A glob or a path; a bare class name is one test, which the map must not list."""
return any(char in test for char in "*?[/")
def ant_to_fnmatch(pattern: str) -> str:
"""A failsafe <exclude> as an fnmatch pattern over paths under the IT source root."""
return pattern.replace("**/", "*")
def methods_using(text: str, symbol: str) -> set[str]:
"""Names of the methods in a Java source whose bodies mention `symbol`."""
code = COMMENT.sub(" ", re.sub(r'"(?:\\.|[^"\\])*"', '""', text))
found: set[str] = set()
for declaration in METHOD_BODY_START.finditer(code):
depth, end = 1, declaration.end()
while depth and end < len(code):
depth += {"{": 1, "}": -1}.get(code[end], 0)
end += 1
if re.search(rf"\b{re.escape(symbol)}\b", code[declaration.end() : end]):
found.add(declaration.group(1))
return found - NOT_METHOD_NAMES
def word_index(sources: dict[str, str]) -> dict[str, set[str]]:
"""Which files mention each identifier, as `git grep -w` would find it."""
index: dict[str, set[str]] = {}
for path, text in sources.items():
for word in set(WORD.findall(text)):
index.setdefault(word, set()).add(path)
return index
def plural(count: int, noun: str) -> str:
return (
f"{count} {noun}"
if count == 1
else f"{count} {noun}es"
if noun.endswith("s")
else f"{count} {noun}s"
)
def committed_files(repo_root: Path, ref: str) -> list[str]:
"""The files of commit `ref` (blobs only: a submodule is not a file of the checkout)."""
files = []
for line in git(repo_root, "ls-tree", "-r", ref).splitlines():
meta, _, path = line.partition("\t")
if meta.split()[1:2] == ["blob"]:
files.append(path)
return files
def read_blobs(repo_root: Path, ref: str, paths: list[str]) -> dict[str, str]:
"""The contents of `paths` at `ref`, read in one `git cat-file --batch`; a path the
commit lacks is left out."""
if not paths:
return {}
out = subprocess.run(
["git", "cat-file", "--batch"],
cwd=repo_root,
input="".join(f"{ref}:{path}\n" for path in paths).encode(),
capture_output=True,
check=True,
).stdout
blobs: dict[str, str] = {}
offset = 0
for path in paths:
end = out.index(b"\n", offset)
header = out[offset:end].split()
offset = end + 1
if header[-1:] == [b"missing"] or len(header) != 3:
continue
size = int(header[2])
blobs[path] = out[offset : offset + size].decode("utf-8", errors="replace")
offset += size + 1
return blobs
def branch_changes(
repo_root: Path, merge_base: str, head: str | None
) -> tuple[list[str], list[str]]:
"""(changed, deleted) files since `merge_base`: in commit `head` when given, which is
what a push sends; else in the working tree, untracked files included."""
target = [head] if head else []
changed = git(
repo_root, "diff", "--name-only", "--no-renames", merge_base, *target
).splitlines()
if not head:
changed += git(
repo_root, "ls-files", "--others", "--exclude-standard"
).splitlines()
deleted = git(
repo_root,
"diff",
"--name-only",
"--no-renames",
"--diff-filter=D",
merge_base,
*target,
).splitlines()
return sorted({path for path in changed if path}), [p for p in deleted if p]
def collect_changed_files(repo_root: Path, base: str) -> list[str]:
try:
merge_base = git(repo_root, "merge-base", base, "HEAD")
except subprocess.CalledProcessError:
sys.exit(
f"No merge base between '{base}' and HEAD. Fetch it first "
"(git fetch origin main) or pass another ref with --base."
)
# --no-renames reports both sides of a rename, so a moved class maps through its
# old path as well as its new one.
tracked = git(
repo_root, "diff", "--name-only", "--no-renames", merge_base
).splitlines()
untracked = git(
repo_root, "ls-files", "--others", "--exclude-standard"
).splitlines()
return sorted({path for path in [*tracked, *untracked] if path})
def collect_changed_methods(
repo_root: Path, base: str, paths: list[str]
) -> dict[str, set[str]]:
"""Names of the Java methods the branch changes, per file.
Git's java diff driver names the method around each hunk; a hunk that adds a method
names the one before it, so methods declared on changed lines count too. Extra names
only add tests.
"""
if not paths:
return {}
merge_base = git(repo_root, "merge-base", base, "HEAD")
with tempfile.TemporaryDirectory() as scratch:
attributes = Path(scratch) / "attributes"
attributes.write_text("*.java diff=java\n", encoding="utf-8")
diff = git(
repo_root,
"-c",
f"core.attributesFile={attributes}",
"diff",
"-U0",
"--no-renames",
merge_base,
"--",
*paths,
)
methods: dict[str, set[str]] = {}
current = None
for line in diff.splitlines():
if line.startswith("diff --git "):
current = line.split(" b/", 1)[-1]
continue
if current is None or line.startswith(("+++", "---")):
continue
names = []
hunk = HUNK_CONTEXT.match(line)
if hunk:
names = re.findall(r"(\w+)\s*\(", hunk.group(1))[:1]
elif line.startswith(("+", "-")):
names = METHOD_DECLARATION.findall(line)
methods.setdefault(current, set()).update(
name
for name in names
if len(name) >= MIN_METHOD_NAME_LENGTH and name not in NOT_METHOD_NAMES
)
return {path: names for path, names in methods.items() if names}
def has_uncommitted_changes(repo_root: Path, ignore: list[str]) -> bool:
"""Whether the run tested code the commit doesn't hold.
The plan reads untracked files too, but only those outside the map's `ignore` list
count: an editor or tool file must not mark every run.
"""
if git(repo_root, "status", "--porcelain", "--untracked-files=no"):
return True
untracked = git(
repo_root, "ls-files", "--others", "--exclude-standard"
).splitlines()
return any(path and not matches(path, ignore) for path in untracked)
class Repo:
"""Read-only view of the checkout the planner selects from: the working tree, or with
`ref` the tree of that commit (what a push sends, whatever the working tree holds)."""
def __init__(self, root: Path, impact_map: dict[str, Any], ref: str | None = None):
self.root = root
self.ref = ref
self.maven = impact_map["maven"]
self.it_root = self.maven["integrationTestSourceRoot"]
self.owned_roots = impact_map.get("ownedRoots", [])
self.shared_infrastructure = impact_map.get("sharedInfrastructure", [])
self._imports: dict[str, dict[str, str]] = {}
if ref:
self.files = committed_files(root, ref)
else:
files = git(
root, "ls-files", "--cached", "--others", "--exclude-standard"
).splitlines()
self.files = [path for path in files if (root / path).is_file()]
self.file_set = set(self.files)
self.pom = self._read(f"{self.maven['integrationTestModule']}/pom.xml")
self.it_classes = self._integration_test_classes()
self.unit_test_classes = self._unit_test_classes()
self.lanes = self._lane_membership()
def _read(self, path: str) -> str:
if self.ref:
return read_blobs(self.root, self.ref, [path]).get(path, "")
return (self.root / path).read_text(encoding="utf-8", errors="replace")
def _read_all(self, paths: list[str]) -> dict[str, str]:
if self.ref:
return read_blobs(self.root, self.ref, paths)
return {path: self._read(path) for path in paths}
def exists(self, path: str) -> bool:
"""Whether `path` is a file or a directory of the checkout."""
if not self.ref:
return (self.root / path).exists()
directory = path.rstrip("/") + "/"
return path in self.file_set or any(f.startswith(directory) for f in self.files)
@cached_property
def it_sources(self) -> dict[str, str]:
"""The Java the ITs are made of: the IT tree, and the client code they call the
server through (`testSideSources`, the SDK)."""
roots = (self.it_root + "/", *self.maven.get("testSideSources", []))
return self._read_all(
[
path
for path in self.files
if path.startswith(roots) and path.endswith(".java")
]
)
@cached_property
def it_words(self) -> dict[str, set[str]]:
return word_index(self.it_sources)
@cached_property
def production_sources(self) -> dict[str, str]:
return self._read_all(
[
path
for path in self.files
if path.endswith(".java")
and "/src/main/java/" in path
and matches(path, self.owned_roots)
]
)
@cached_property
def production_words(self) -> dict[str, set[str]]:
return word_index(self.production_sources)
@cached_property
def production_classes(self) -> dict[str, str]:
"""Fully qualified class name -> the production source file that declares it."""
return {
fqn: path
for path in self.files
if "/src/main/java/" in path and (fqn := class_fqn(path))
}
@cached_property
def universal_helpers(self) -> set[str]:
"""Helpers most ITs go through, and the shared IT bootstrap every IT starts from."""
prefix = self.it_root + "/"
its = {prefix + relative for relative in self.it_classes}
return {
path
for path in self.it_sources
if path not in its
and (
matches(path, self.shared_infrastructure)
or len(self.it_words.get(simple_name(path), set()) & its)
> UNIVERSAL_HELPER_SHARE * len(its)
)
}
def imports(self, path: str, text: str) -> dict[str, str]:
"""Simple name -> fully qualified name of each class a Java file imports."""
cached = self._imports.get(path)
if cached is None:
cached = {}
for static, name in re.findall(
r"^import\s+(static\s+)?([\w.]+)\s*;", text, re.MULTILINE
):
owner = name.rsplit(".", 1)[0] if static else name
cached[owner.rsplit(".", 1)[-1]] = owner
self._imports[path] = cached
return cached
def names_class(self, path: str, text: str, fqn: str) -> bool:
"""Whether a file mentioning the simple name of `fqn` means that class. One that
imports another class of the same name does not; one that imports neither may
mean it through its package, a fully qualified name or a comment, so it counts."""
simple = fqn.rsplit(".", 1)[-1]
imported = self.imports(path, text).get(simple)
return imported is None or imported == fqn or fqn in text
@cached_property
def class_headers(self) -> dict[str, str]:
"""Each IT class's annotations and declaration, without comments."""
prefix = self.it_root + "/"
headers = {}
for relative, name in self.it_classes.items():
header = class_header(self.it_sources.get(prefix + relative, ""), name)
if header is not None:
headers[relative] = header
return headers
@cached_property
def never_run(self) -> set[str]:
"""IT classes no lane runs: abstract bases, class-level @Disabled, suite-profile excludes."""
never = {
relative
for relative, header in self.class_headers.items()
if re.search(r"\babstract\b|@Disabled\b", header)
}
for suite in self.maven["suites"].values():
profile = re.search(
rf"<id>{re.escape(suite['profile'])}</id>(.*?)</profile>",
self.pom,
re.DOTALL,
)
excludes = [
ant_to_fnmatch(exclude)
for exclude in re.findall(
r"<exclude>([^<]+)</exclude>", profile.group(1) if profile else ""
)
]
never |= {
relative
for relative in self.it_classes
if any(fnmatch.fnmatchcase(relative, p) for p in suite["tests"])
and any(fnmatch.fnmatchcase(relative, e) for e in excludes)
}
return never
@cached_property
def conditional(self) -> dict[str, str]:
"""IT classes enabled only by a system property the IT pom never sets."""
return {
relative: prop
for relative, header in self.class_headers.items()
for prop in re.findall(
r'@EnabledIfSystemProperty\s*\(\s*named\s*=\s*"([^"]+)"', header
)
if prop not in self.pom
}
def _declared_test_classes(
self, prefix: str, pattern: re.Pattern[str]
) -> dict[str, str]:
candidates = [
path
for path in self.files
if path.startswith(prefix)
and path.endswith(".java")
and pattern.match(simple_name(path))
]
return {
path: simple_name(path)
for path, text in self._read_all(candidates).items()
if class_header(text, simple_name(path)) is not None
}
def _integration_test_classes(self) -> dict[str, str]:
prefix = self.it_root + "/"
return {
path[len(prefix) :]: name
for path, name in self._declared_test_classes(prefix, IT_CLASS).items()
}
def _unit_test_classes(self) -> dict[str, dict[str, str]]:
modules: dict[str, dict[str, str]] = {}
for module in self.maven["unitTestModules"]:
prefix = f"{module}/src/test/java/"
modules[module] = {
name: path
for path, name in self._declared_test_classes(
prefix, UNIT_TEST_CLASS
).items()
}
return modules
def is_abstract_unit_test(self, module: str, name: str) -> bool:
path = self.unit_test_classes.get(module, {}).get(name)
header = class_header(self._read(path), name) if path else None
return bool(header and re.search(r"\babstract\b", header))
def unit_test_subclasses(self, module: str, base: str) -> list[str]:
"""The unit test classes of `module` that extend `base` directly."""
classes = self.unit_test_classes.get(module, {})
subclasses = []
for path in self.referencing_files(base, [f"{module}/src/test/java"]):
name = simple_name(path)
extends = (
rf"\bclass\s+{re.escape(name)}\b[^{{]*\bextends\s+{re.escape(base)}\b"
)
if classes.get(name) == path and re.search(
extends, COMMENT.sub(" ", self._read(path))
):
subclasses.append(name)
return sorted(subclasses)
def _lane_membership(self) -> dict[str, list[str]]:
"""Class-name patterns per lane, read from the IT pom so they cannot drift from CI.
A lane names either comma-separated pom properties (`pomProperties`) or a failsafe
execution whose first `<includes>` lists its classes (`pomExecutionIncludes`).
"""
lanes: dict[str, list[str]] = {}
for lane, config in self.maven["lanes"].items():
patterns: list[str] = []
for prop in config.get("pomProperties", []):
found = re.search(
rf"<{re.escape(prop)}>([^<]*)</{re.escape(prop)}>", self.pom
)
if not found:
raise SystemExit(
f"{IMPACT_MAP}: lane '{lane}' reads <{prop}> from the IT pom, which no longer defines it."
)
patterns += [
item.strip() for item in found.group(1).split(",") if item.strip()
]
execution = config.get("pomExecutionIncludes")
if execution:
found = re.search(
rf"<id>{re.escape(execution)}</id>.*?<includes>(.*?)</includes>",
self.pom,
re.DOTALL,
)
if not found:
raise SystemExit(
f"{IMPACT_MAP}: lane '{lane}' reads the includes of execution '{execution}', "
"which the IT pom no longer defines."
)
patterns += [
simple_name(include)
for include in re.findall(
r"<include>([^<]+)</include>", found.group(1)
)
]
lanes[lane] = patterns
return lanes
def it_paths_matching(self, pattern: str) -> list[str]:
"""Path patterns contain a '/'; everything else matches the class's simple name."""
if "/" in pattern:
return [
path for path in self.it_classes if fnmatch.fnmatchcase(path, pattern)
]
return [
path
for path, name in self.it_classes.items()
if fnmatch.fnmatchcase(name, pattern)
]
def referencing_files(self, symbol: str, roots: list[str]) -> list[str]:
if not roots:
return []
result = subprocess.run(
[
"git",
"grep",
"--untracked",
"-l",
"-w",
"-F",
"-e",
symbol,
"--",
*roots,
],
cwd=self.root,
capture_output=True,
text=True,
)
return [line for line in result.stdout.splitlines() if line.endswith(".java")]
def convention_stem(path: str) -> str | None:
"""Entity name a production file is about, e.g. TableRepository.java -> Table."""
name = simple_name(path)
if path.endswith(".java") and "/src/main/java/" in path:
for suffix in CONVENTION_SUFFIXES:
if name.endswith(suffix) and len(name) > len(suffix):
return name[: -len(suffix)]
return None
if path.endswith("_index_mapping.json"):
return "".join(
part.capitalize() for part in name[: -len("_index_mapping")].split("_")
)
if "/json/schema/entity/" in path and path.endswith(".json"):
return name[:1].upper() + name[1:]
if (
"/json/schema/api/" in path
and name.startswith("create")
and path.endswith(".json")
):
return name[len("create") :]
return None
def generated_class_name(path: str) -> str | None:
"""Class jsonschema2pojo generates for a schema file, e.g. createTable.json -> CreateTable."""
if "/json/schema/" in path and path.endswith(".json"):
name = simple_name(path)
return name[:1].upper() + name[1:]
return None
def stem_matches(stem: str, class_name: str) -> bool:
if len(stem) < MIN_STEM_LENGTH or not class_name.lower().startswith(stem.lower()):
return False
rest = class_name[len(stem) :]
return not rest or rest[0].isupper()
class Planner:
def __init__(self, repo: Repo, impact_map: dict[str, Any]):
self.repo = repo
self.map = impact_map
self.maven = impact_map["maven"]
self.default_engine = self.maven["defaultEngine"]
self.it_reference_cap = self.maven["integrationTestReferenceCap"]
self.unit_reference_cap = self.maven["unitTestReferenceCap"]
self.unit_test_roots = [
f"{module}/src/test/java" for module in self.maven["unitTestModules"]
]
def plan(
self,
changed_files: list[str],
add_its: list[str] = (),
add_units: list[str] = (),
add_areas: list[str] = (),
changed_methods: dict[str, set[str]] | None = None,
reason: str = "",
scope: str = "full",
) -> Plan:
plan = Plan(changed_files=changed_files)
for path in changed_files:
if matches(path, self.map["ignore"]):
continue
self._plan_file(plan, path, (changed_methods or {}).get(path, set()))
if plan.smoke_on_default_engine:
self._add_smoke(plan, "code other than a test class changed", set())
if plan.smoke_engines:
self._add_smoke(
plan, "code other than a test class changed", plan.smoke_engines
)
self._add_author_choices(plan, add_its, add_units, add_areas, reason)
lane_its = self._lane_its()
selected = lane_its & set(plan.integration_tests)
if not plan.full_suite and len(selected) > FULL_SUITE_SHARE * len(lane_its):
plan.full_suite[
f"{len(selected)} of the {len(lane_its)} merge-queue ITs were selected"
] = set()
if plan.full_suite:
for relative in lane_its:
self._add_it(plan, relative, "full suite", set())
self._drop_unrunnable(plan)
plan.commands = self._commands(plan)
if scope == "focused":
return self._focused_plan(plan, add_its, add_units, add_areas, reason)
return plan
def _focused_plan(
self,
broad: Plan,
add_its: list[str],
add_units: list[str],
add_areas: list[str],
reason: str,
) -> Plan:
focused = Plan(broad.changed_files, scope="focused")
focused.unmapped_files = broad.unmapped_files
focused.untested_classes = broad.untested_classes
focused.not_run_locally = dict(broad.not_run_locally)
for path in broad.changed_files:
relative = path.removeprefix(self.repo.it_root + "/")
if (
path.startswith(self.repo.it_root + "/")
and relative in self.repo.it_classes
):
self._add_it(focused, relative, "changed", self._engines_for(path))
module = self._unit_module(path)
name = simple_name(path)
if (
module
and "/src/test/java/" in path
and name in self.repo.unit_test_classes.get(module, {})
):
self._add_unit(focused, module, name, "changed")
if "/src/main/java/" in path and path.endswith(".java"):
for owner, classes in self.repo.unit_test_classes.items():
for candidate in (f"{name}Test", f"{name}Tests"):
if candidate in classes:
self._add_unit(focused, owner, candidate, f"tests {name}")
self._add_author_choices(focused, add_its, add_units, add_areas, reason)
self._drop_unrunnable(focused)
focused.commands = self._commands(focused)
selected = {tuple(c.argv) for c in focused.commands}
focused.deferred_commands = [
c for c in broad.commands if tuple(c.argv) not in selected
]
if broad.commands and not focused.commands:
raise SystemExit(
"Focused scope found no runnable tests; select --add-it or --add-unit with --reason, or use --scope full."
)
return focused
def _add_author_choices(
self,
plan: Plan,
add_its: list[str],
add_units: list[str],
add_areas: list[str],
reason: str,
) -> None:
"""Tests the author or agent adds to the plan. Nothing can take tests out of it."""
if not (add_its or add_units or add_areas):
return
if not reason:
raise SystemExit(
'Say why the plan needs these tests: --reason "<the effect it missed>"'
)
label = f"added by author: {reason}"
for name in add_its:
paths = [
relative
for relative, it_name in self.repo.it_classes.items()
if it_name == name
]
if not paths:
raise SystemExit(f"--add-it: no integration test class is named {name}")
for relative in paths:
self._add_it(plan, relative, label, set())
plan.triggers.setdefault(label, set()).add(name)
for name in add_units:
modules = [
module
for module, classes in self.repo.unit_test_classes.items()
if name in classes
]
if not modules:
raise SystemExit(
f"--add-unit: no unit test class in {self.maven['unitTestModules']} is named {name}"
)
for module in modules:
self._add_unit(plan, module, name, label)
plan.triggers.setdefault(label, set()).add(name)
for name in add_areas:
area = next((a for a in self.map["areas"] if a["name"] == name), None)
if area is None:
raise SystemExit(
f"--add-area: no area is named {name}. Areas: "
+ ", ".join(a["name"] for a in self.map["areas"])
)
self._add_area(plan, area, label, set(), f"area {name}")
def _lane_its(self) -> set[str]:
"""Every IT the merge queue runs: the lane classes, not the suites or what no lane runs."""
not_local = [p for rule in self.maven["notRunLocally"] for p in rule["tests"]]
return {
relative
for relative, name in self.repo.it_classes.items()
if self.lane_for(relative) in self.maven["lanes"]
and relative not in self.repo.never_run
and relative not in self.repo.conditional
and not any(self._it_pattern_matches(relative, name, p) for p in not_local)
}
def _plan_file(self, plan: Plan, path: str, methods: set[str]) -> None:
engines = self._engines_for(path)
it_prefix = self.repo.it_root + "/"
test_source = self._is_test_source(path)
owned = False
if path.startswith(it_prefix):
relative = path[len(it_prefix) :]
if relative in self.repo.it_classes:
self._add_it(plan, relative, "changed", engines)
plan.triggers.setdefault("changed test", set()).add(path)
owned = True
elif path in self.repo.universal_helpers:
# Every IT calls it, so only the changed methods tell which ITs it affects.
found = [
self._add_referencing_its(
plan, path, method, engines, is_method=True
)
for method in sorted(methods)
]
if not any(found):
plan.full_suite.setdefault(
f"{simple_name(path)} is used by most ITs", set()
).add(path)
owned = True
elif path.endswith(".java"):
owned = self._add_referencing_its(
plan, path, simple_name(path), engines
)
module = self._unit_module(path)
if module and f"{module}/src/test/java/" in path and path.endswith(".java"):
name = simple_name(path)
if name in self.repo.unit_test_classes.get(module, {}):
self._add_unit(plan, module, name, "changed")
plan.triggers.setdefault("changed test", set()).add(path)
else:
self._add_referencing_unit_tests(
plan, name, f"test helper {name} changed", exclude=path
)
owned = True
elif "/src/main/java/" in path and path.endswith(".java"):
name = simple_name(path)
# Classes outside the unit modules (the SDK, spec helpers) still get the unit
# tests that use them; only a unit module's own classes must have one.
covered = self._add_unit_tests_for_class(plan, name, path)
if module and not covered and (self.repo.root / path).exists():
plan.untested_classes.append(path)
self._add_referencing_its(plan, path, name, engines)
for method in sorted(methods):
self._add_referencing_its(
plan, path, method, engines, is_method=True, owner=name
)
self._add_callers(plan, path, name, engines, methods)
elif module and f"{module}/src/main/resources/" in path:
self._add_unit_tests_for_resource(plan, path)
generated = generated_class_name(path)
if generated:
self._add_referencing_unit_tests(
plan, generated, f"schema {path.rsplit('/', 1)[-1]} changed"
)
for area in self.map["areas"]:
if matches(path, area["sources"]):
self._add_area(plan, area, f"area {area['name']}", engines, path)
owned = True
stem = convention_stem(path)
if stem and self._add_entity(plan, stem, f"entity {stem}", engines, path):
owned = True
if matches(path, self.map["sharedInfrastructure"]):
plan.full_suite.setdefault("shared infrastructure", set()).add(path)
for owner in self._full_suite_modules(path):
plan.full_unit_modules.setdefault(owner, set()).add(f"{path} changed")