-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathtest_harness.py
More file actions
302 lines (261 loc) · 9.4 KB
/
Copy pathtest_harness.py
File metadata and controls
302 lines (261 loc) · 9.4 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
from __future__ import annotations
import hashlib
import os
import re
import shutil
import subprocess
import sys
from dataclasses import dataclass
from pathlib import Path
from stdlib_overlay import (
STDLIB_OVERLAY_ROOT,
STDLIB_PATCH_ROOT,
prepare_stdlib_source,
rustc_info,
)
ROOT = Path(__file__).resolve().parent
TARGET_SPEC = ROOT / "jvm-unknown-jvm.json"
TEST_TARGET_DIR = ROOT / "target" / "test-suite"
TEST_CONFIG = ROOT / "config.toml"
CORE_BUILD_MANIFEST = ROOT / "tests" / "support" / "core_build" / "Cargo.toml"
TEST_TYPES = ("binary", "multicrate", "integration", "kotlin", "cargo_jvm")
CACHE_TAG = (
"Signature: 8a477f597d28d172789f06886806bc55\n"
"# This file is a cache directory tag created by rustc_codegen_jvm.\n"
)
_STDLIB_SOURCE: Path | None = None
_STDLIB_FINGERPRINT: str | None = None
@dataclass(frozen=True)
class TestCase:
directory: Path
kind: str
package_name: str
@property
def name(self) -> str:
return self.directory.name
@property
def artifact_name(self) -> str:
return self.package_name.replace("-", "_")
def cpu_count() -> int:
return os.cpu_count() or 1
def resolve_workers(requested: int | None) -> int:
if requested is not None:
if requested < 1:
raise ValueError("--jobs must be at least 1")
return requested
return min(cpu_count(), 4)
def cargo_jobs(workers: int) -> int:
return max(1, cpu_count() // workers)
def package_name(manifest: Path) -> str:
in_package = False
for line in manifest.read_text(encoding="utf-8").splitlines():
stripped = line.strip()
if stripped.startswith("["):
in_package = stripped == "[package]"
continue
if in_package:
match = re.fullmatch(r'name\s*=\s*"([^"]+)"', stripped)
if match:
return match.group(1)
raise ValueError(f"missing package name in {manifest}")
def discover_tests(
only_run: set[str] | None = None,
dont_run: set[str] | None = None,
) -> list[TestCase]:
excluded = dont_run or set()
tests: list[TestCase] = []
for kind in TEST_TYPES:
parent = ROOT / "tests" / kind
if not parent.is_dir():
continue
for directory in sorted(path for path in parent.iterdir() if path.is_dir()):
manifest = directory / "Cargo.toml"
if not manifest.exists():
continue
if only_run is not None and directory.name not in only_run:
continue
if directory.name in excluded:
continue
tests.append(TestCase(directory, kind, package_name(manifest)))
return tests
def validate_configuration() -> None:
missing = [path for path in (TARGET_SPEC, TEST_CONFIG) if not path.exists()]
if missing:
paths = ", ".join(str(path) for path in missing)
raise RuntimeError(
f"missing generated test configuration: {paths}; run `python3 build.py all`"
)
def prepare_stdlib() -> tuple[Path, str]:
global _STDLIB_SOURCE, _STDLIB_FINGERPRINT
if _STDLIB_SOURCE is None or _STDLIB_FINGERPRINT is None:
sysroot, _, commit = rustc_info()
_STDLIB_SOURCE, overlay_hash = prepare_stdlib_source(sysroot, commit)
_STDLIB_FINGERPRINT = f"{commit}:{overlay_hash}"
return _STDLIB_SOURCE, _STDLIB_FINGERPRINT
def stdlib_build_environment(base: dict[str, str] | None = None) -> dict[str, str]:
source, _ = prepare_stdlib()
environment = (base if base is not None else os.environ).copy()
environment["__CARGO_TESTS_ONLY_SRC_ROOT"] = str(source)
return environment
def prepare_shared_cache() -> bool:
"""Invalidate all test artifacts when the compiler toolchain inputs change."""
validate_configuration()
_, stdlib_fingerprint = prepare_stdlib()
inputs = [
Path(__file__),
TARGET_SPEC,
TEST_CONFIG,
ROOT / "runtime" / "build" / "libs" / "runtime-0.1.0.jar",
ROOT / "java-linker" / "target" / "release" / (
"java-linker.exe" if os.name == "nt" else "java-linker"
),
ROOT / "cargo-jvm" / "target" / "release" / (
"cargo-jvm.exe" if os.name == "nt" else "cargo-jvm"
),
]
inputs.extend(path for path in STDLIB_OVERLAY_ROOT.rglob("*") if path.is_file())
inputs.extend(path for path in STDLIB_PATCH_ROOT.rglob("*.patch") if path.is_file())
backend_candidates = list((ROOT / "target" / "release").glob("*rustc_codegen_jvm.*"))
inputs.extend(path for path in backend_candidates if path.suffix in {".dll", ".dylib", ".so"})
digest = hashlib.sha256()
digest.update(stdlib_fingerprint.encode("utf-8"))
for path in sorted(inputs):
if not path.exists():
raise RuntimeError(f"missing test toolchain input: {path}; run `python3 build.py all`")
digest.update(str(path).encode())
digest.update(path.read_bytes())
fingerprint = digest.hexdigest()
marker = TEST_TARGET_DIR / ".harness-fingerprint"
if marker.exists() and marker.read_text(encoding="utf-8") == fingerprint:
(TEST_TARGET_DIR / "CACHEDIR.TAG").write_text(CACHE_TAG, encoding="utf-8")
return False
if TEST_TARGET_DIR.exists():
shutil.rmtree(TEST_TARGET_DIR)
TEST_TARGET_DIR.mkdir(parents=True)
(TEST_TARGET_DIR / "CACHEDIR.TAG").write_text(CACHE_TAG, encoding="utf-8")
marker.write_text(fingerprint, encoding="utf-8")
return True
def cargo_build_command(manifest: Path, release: bool, jobs: int) -> list[str]:
command = [
"cargo",
"build",
"--manifest-path",
str(manifest),
"--target",
str(TARGET_SPEC),
"-Zjson-target-spec",
"-Zbuild-std=std,panic_unwind",
"-Zbuild-std-features=panic-unwind",
"--target-dir",
str(TEST_TARGET_DIR),
"--config",
str(TEST_CONFIG),
"--jobs",
str(jobs),
]
if release:
command.extend(
["--release", "--config", 'profile.release.debug="line-tables-only"']
)
return command
def run_command(
command: list[str],
*,
cwd: Path | None = None,
env: dict[str, str] | None = None,
input_text: str | None = None,
) -> subprocess.CompletedProcess[str]:
if input_text is None:
return subprocess.run(
command,
cwd=cwd or ROOT,
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
encoding="utf-8",
errors="replace",
)
# Text-mode pipes translate LF to CRLF on Windows. Feed UTF-8 bytes so a
# test fixture reaches Rust's stdin unchanged on every host.
completed = subprocess.run(
command,
cwd=cwd or ROOT,
env=env,
input=input_text.encode("utf-8"),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
return subprocess.CompletedProcess(
completed.args,
completed.returncode,
completed.stdout.decode("utf-8", errors="replace"),
completed.stderr.decode("utf-8", errors="replace"),
)
def prime_core(release: bool) -> subprocess.CompletedProcess[str]:
validate_configuration()
return run_command(
cargo_build_command(CORE_BUILD_MANIFEST, release, cpu_count()),
env=stdlib_build_environment(),
)
def build_test(
test: TestCase,
release: bool,
jobs: int,
*,
env: dict[str, str] | None = None,
) -> subprocess.CompletedProcess[str]:
if test.kind == "cargo_jvm":
cargo_jvm = ROOT / "cargo-jvm" / "target" / "release" / (
"cargo-jvm.exe" if os.name == "nt" else "cargo-jvm"
)
command = [
sys.executable,
str(test.directory / "run.py"),
"--cargo-jvm",
str(cargo_jvm),
"--backend",
str(ROOT),
"--target-dir",
str(TEST_TARGET_DIR),
]
if release:
command.append("--release")
return run_command(command, env=stdlib_build_environment(env))
if test.kind in ("integration", "kotlin"):
cargo_jvm = ROOT / "cargo-jvm" / "target" / "release" / (
"cargo-jvm.exe" if os.name == "nt" else "cargo-jvm"
)
command = [
str(cargo_jvm),
"package",
"--manifest-path",
str(test.directory / "Cargo.toml"),
"--target-dir",
str(TEST_TARGET_DIR),
"--jobs",
str(jobs),
"--output",
str(jar_path(test, release)),
]
if release:
command.extend(
["--release", "--config", 'profile.release.debug="line-tables-only"']
)
environment = stdlib_build_environment(env)
environment["CARGO_JVM_BACKEND_PATH"] = str(ROOT)
return run_command(command, env=environment)
return run_command(
cargo_build_command(test.directory / "Cargo.toml", release, jobs),
env=stdlib_build_environment(env),
)
def jar_path(test: TestCase, release: bool) -> Path:
profile = "release" if release else "debug"
profile_dir = TEST_TARGET_DIR / "jvm-unknown-jvm" / profile
direct = profile_dir / f"{test.artifact_name}.jar"
if direct.exists():
return direct
candidates = list((profile_dir / "deps").glob(f"{test.artifact_name}-*.jar"))
if candidates:
return max(candidates, key=lambda path: path.stat().st_mtime_ns)
return direct