Repository navigation
Expand file tree
/
Copy pathrun-tests-macos.js
More file actions
816 lines (695 loc) · 28.1 KB
/
Copy pathrun-tests-macos.js
File metadata and controls
816 lines (695 loc) · 28.1 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
// Runs macOS TestRunner.app and streams runtime logs directly.
// Optional args:
// - junit output path (defaults to build/test-results/macos-junit.xml)
//
// Env:
// - MACOS_TEST_SKIP_BUILD=1 skips xcodebuild app build.
// - MACOS_TEST_CLEAN_BUILD=1 deletes derived data before build.
// - MACOS_TEST_ENGINE selects the runtime engine build to use when runtime
// artifacts need rebuilding. Supported: v8, hermes, quickjs, jsc. Defaults to v8.
// - MACOS_TEST_FFI_BACKEND selects the FFI backend build to use when runtime
// artifacts need rebuilding. Supported: auto, napi, v8, hermes, quickjs, jsc.
// Defaults to auto.
// - MACOS_TEST_GSD_BACKEND selects generated signature dispatch backend.
// Supported: auto, v8, jsc, quickjs, hermes, napi, none. Defaults to auto.
// - MACOS_COMMAND_TIMEOUT_MS overrides timeout for build commands (default: 10 minutes).
// - MACOS_COMMAND_MAX_BUFFER_BYTES overrides spawnSync maxBuffer for captured command output (default: 64 MiB).
// - MACOS_TEST_TIMEOUT_MS overrides max test runtime after launch (default: 2 minutes).
// - MACOS_TEST_INACTIVITY_TIMEOUT_MS overrides max no-log interval after launch (default: 45 seconds).
// - MACOS_LOG_JUNIT=0 disables streaming TKUnit/JUnit lines to console.
// - MACOS_TESTS filters test modules (comma-separated substrings passed as -tests).
// - MACOS_TEST_SPECS filters spec names (comma-separated substrings passed as -specs).
// - MACOS_TEST_VERBOSE_SPECS=1 prints Jasmine spec start/done markers.
const fs = require("fs");
const path = require("path");
const cp = require("child_process");
const crypto = require("crypto");
const os = require("os");
const projectPath = path.join(__dirname, "../platforms/apple/NativeScriptRuntime.xcodeproj");
const scheme = "TestRunner";
const configuration = "Debug";
const derivedDataPath = path.join(__dirname, "../build", "derived-data", "macos-tests");
const testRunnerAppSourcePath = path.join(__dirname, "../platforms/apple/test/runtime/runner", "app");
const nativeScriptXCFramework = path.join(__dirname, "../dist", "NativeScript.xcframework");
const tkLiveSyncXCFramework = path.join(__dirname, "../dist", "TKLiveSync.xcframework");
const nativeScriptSourceRoot = path.join(__dirname, "../NativeScript");
const metadataGeneratorRoot = path.join(__dirname, "../metadata-generator");
const metadataGeneratorBinary = path.join(
metadataGeneratorRoot,
"dist",
"arm64",
"bin",
"objc-metadata-generator"
);
const metadataGeneratorBuildStepScript = path.join(
metadataGeneratorRoot,
"dist",
"arm64",
"bin",
"build-step-metadata-generator.py"
);
const metadataGeneratorSymbolAnalyzer = path.join(
metadataGeneratorRoot,
"dist",
"arm64",
"bin",
"ns-metadata-symbols"
);
const metadataGeneratorSourceInputs = [
path.join(metadataGeneratorRoot, "src"),
path.join(metadataGeneratorRoot, "include"),
path.join(metadataGeneratorRoot, "tests"),
path.join(metadataGeneratorRoot, "symbol-analyzer", "Cargo.toml"),
path.join(metadataGeneratorRoot, "symbol-analyzer", "Cargo.lock"),
path.join(metadataGeneratorRoot, "symbol-analyzer", "src"),
path.join(metadataGeneratorRoot, "symbol-analyzer", "tests"),
path.join(metadataGeneratorRoot, "build-step-metadata-generator.py"),
path.join(metadataGeneratorRoot, "CMakeLists.txt"),
path.join(__dirname, "build_metadata_generator.sh")
];
const buildStatePath = path.join(derivedDataPath, ".macos-test-build-state.json");
const macosBuildInputs = [
path.join(__dirname, "../platforms/apple/NativeScriptRuntime.xcodeproj", "project.pbxproj"),
path.join(__dirname, "../platforms/apple/test/runtime/runner", "Source Files"),
path.join(__dirname, "../platforms/apple/test/runtime/runner", "Info.plist"),
path.join(__dirname, "../platforms/apple/test/runtime/fixtures"),
path.join(__dirname, "../platforms/apple/TKLiveSync"),
...metadataGeneratorSourceInputs,
nativeScriptXCFramework,
tkLiveSyncXCFramework
];
const resultsDir = path.join(__dirname, "../build", "test-results");
const defaultJunitPath = path.join(resultsDir, "macos-junit.xml");
function parseTimeoutMs(name, fallback) {
const value = Number(process.env[name] || fallback);
if (!Number.isFinite(value) || value <= 0) {
return fallback;
}
return value;
}
function parsePositiveInt(name, fallback) {
const value = Number(process.env[name] || fallback);
if (!Number.isFinite(value) || value <= 0) {
return fallback;
}
return Math.floor(value);
}
const commandTimeoutMs = parseTimeoutMs("MACOS_COMMAND_TIMEOUT_MS", 10 * 60 * 1000);
const commandMaxBufferBytes = parsePositiveInt("MACOS_COMMAND_MAX_BUFFER_BYTES", 64 * 1024 * 1024);
const testTimeoutMs = parseTimeoutMs("MACOS_TEST_TIMEOUT_MS", 2 * 60 * 1000);
const inactivityTimeoutMs = parseTimeoutMs("MACOS_TEST_INACTIVITY_TIMEOUT_MS", 45 * 1000);
const emitJunitLogs = process.env.MACOS_LOG_JUNIT !== "0";
const requestedTests = (process.env.MACOS_TESTS || "").trim();
const requestedSpecs = (process.env.MACOS_TEST_SPECS || "").trim();
const verboseSpecs = process.env.MACOS_TEST_VERBOSE_SPECS === "1";
const requestedEngine = (process.env.MACOS_TEST_ENGINE || "v8").trim().toLowerCase();
const requestedFfiBackend = (process.env.MACOS_TEST_FFI_BACKEND || "auto").trim().toLowerCase();
const requestedGsdBackend = (process.env.MACOS_TEST_GSD_BACKEND || process.env.NS_GSD_BACKEND || "auto").trim().toLowerCase();
const launchedMarker = "Application Start!";
const junitPrefix = "TKUnit: ";
const junitEndTag = "</testsuites>";
const consoleLogMarker = "CONSOLE LOG:";
const crashReportsDir = path.join(os.homedir(), "Library", "Logs", "DiagnosticReports");
const generatedRuntimeBuildOutputs = new Set([
path.join(nativeScriptSourceRoot, "ffi", "objc", "shared", "GeneratedSignatureDispatch.inc"),
path.join(nativeScriptSourceRoot, "ffi", "objc", "shared", "GeneratedSignatureDispatch.inc.stamp"),
path.join(nativeScriptSourceRoot, "ffi", "objc", "shared", "GeneratedGsdSignatureDispatch.inc"),
path.join(nativeScriptSourceRoot, "ffi", "objc", "shared", "GeneratedGsdSignatureDispatch.inc.stamp")
]);
function parseArgs() {
const args = process.argv.slice(2).filter(Boolean);
if (args.length === 0) {
return { junitOutPath: defaultJunitPath };
}
return { junitOutPath: path.resolve(args[0]) };
}
function run(command, args, options = {}) {
const effectiveTimeout = options.timeout ?? commandTimeoutMs;
const result = cp.spawnSync(command, args, {
encoding: "utf8",
timeout: effectiveTimeout,
maxBuffer: commandMaxBufferBytes,
...options
});
if (result.error) {
if (result.error.code === "ETIMEDOUT") {
throw new Error(`Command timed out after ${effectiveTimeout}ms: ${command} ${args.join(" ")}`);
}
throw result.error;
}
return result;
}
function getPathStats(targetPath) {
if (!fs.existsSync(targetPath)) {
return { files: 0, bytes: 0, maxMtimeMs: 0 };
}
const queue = [targetPath];
let files = 0;
let bytes = 0;
let maxMtimeMs = 0;
while (queue.length > 0) {
const currentPath = queue.pop();
if (generatedRuntimeBuildOutputs.has(currentPath)) {
continue;
}
let stats;
try {
stats = fs.lstatSync(currentPath);
} catch (_) {
continue;
}
if (stats.mtimeMs > maxMtimeMs) {
maxMtimeMs = stats.mtimeMs;
}
if (stats.isDirectory()) {
const entries = fs.readdirSync(currentPath);
for (const entry of entries) {
queue.push(path.join(currentPath, entry));
}
continue;
}
if (stats.isFile() || stats.isSymbolicLink()) {
files += 1;
bytes += stats.size;
}
}
return { files, bytes, maxMtimeMs };
}
function createBuildFingerprint(inputs) {
const snapshot = inputs.map((inputPath) => ({
path: inputPath,
...getPathStats(inputPath)
}));
return crypto.createHash("sha1").update(JSON.stringify(snapshot)).digest("hex");
}
function readBuildState() {
if (!fs.existsSync(buildStatePath)) {
return null;
}
try {
return JSON.parse(fs.readFileSync(buildStatePath, "utf8"));
} catch (_) {
return null;
}
}
function writeBuildState(nativeFingerprint) {
fs.mkdirSync(path.dirname(buildStatePath), { recursive: true });
fs.writeFileSync(buildStatePath, JSON.stringify({ nativeFingerprint, createdAt: Date.now() }));
}
function syncAppResources(destinationAppResourcesPath) {
fs.mkdirSync(destinationAppResourcesPath, { recursive: true });
const result = run("rsync", [
"-a",
"--delete",
`${testRunnerAppSourcePath}/`,
`${destinationAppResourcesPath}/`
]);
if (result.status !== 0) {
throw new Error(`Failed to sync TestRunner app resources: ${result.stderr || result.stdout || "unknown rsync error"}`);
}
}
function stripConsoleLogPrefix(line) {
const markerIndex = line.indexOf(consoleLogMarker);
if (markerIndex < 0) {
return line;
}
return line.slice(markerIndex + consoleLogMarker.length).trimStart();
}
function quoteForLLDB(arg) {
return `"${String(arg).replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
}
function getProcessExitStatus(code, signal) {
if (typeof code === "number") {
return { code, display: String(code) };
}
if (signal) {
const signalNumber = os.constants.signals[signal];
if (typeof signalNumber === "number") {
const mappedCode = 128 + signalNumber;
return { code: mappedCode, display: `${mappedCode} (signal ${signal})` };
}
return { code: 1, display: `signal ${signal}` };
}
return { code: 1, display: "unknown" };
}
function isLikelyCrash(code, signal) {
if (signal) {
return true;
}
return code === 134 || code === 139;
}
function readRecentCrashReportForPid(pid, launchedAtMs) {
if (!pid || !fs.existsSync(crashReportsDir)) {
return null;
}
const candidates = fs.readdirSync(crashReportsDir)
.filter((name) => name.startsWith("TestRunner") && (name.endsWith(".ips") || name.endsWith(".crash")))
.map((name) => {
const fullPath = path.join(crashReportsDir, name);
let stats;
try {
stats = fs.statSync(fullPath);
} catch (_) {
return null;
}
return {
fullPath,
mtimeMs: stats.mtimeMs
};
})
.filter(Boolean)
.filter((item) => item.mtimeMs >= (launchedAtMs - 5000))
.sort((a, b) => b.mtimeMs - a.mtimeMs);
const pidMatchers = [
`"pid" : ${pid}`,
`"pid":${pid}`,
`Process: TestRunner [${pid}]`,
`Process: TestRunner [${pid}]`
];
for (const candidate of candidates) {
let content;
try {
content = fs.readFileSync(candidate.fullPath, "utf8");
} catch (_) {
continue;
}
if (pidMatchers.some((matcher) => content.includes(matcher))) {
return { path: candidate.fullPath, content };
}
}
return null;
}
function formatBacktraceFromIPS(ipsContent) {
const firstNewline = ipsContent.indexOf("\n");
if (firstNewline < 0) {
return null;
}
let report;
try {
report = JSON.parse(ipsContent.slice(firstNewline + 1).trim());
} catch (_) {
return null;
}
const threads = report.threads || [];
if (!Array.isArray(threads) || threads.length === 0) {
return null;
}
const faultingThread = Number.isInteger(report.faultingThread) ? report.faultingThread : 0;
const images = report.usedImages || [];
const lines = [];
const exceptionType = report.exception && report.exception.type ? report.exception.type : "unknown";
const exceptionSignal = report.exception && report.exception.signal ? report.exception.signal : "unknown";
lines.push(`Exception: ${exceptionType} (${exceptionSignal})`);
lines.push(`Faulting thread: ${faultingThread}`);
for (let threadIndex = 0; threadIndex < threads.length; threadIndex++) {
const thread = threads[threadIndex];
if (!thread || !Array.isArray(thread.frames)) {
continue;
}
const threadHeader = threadIndex === faultingThread
? `Thread ${threadIndex} Crashed${thread.queue ? ` (${thread.queue})` : ""}:`
: `Thread ${threadIndex}${thread.queue ? ` (${thread.queue})` : ""}:`;
lines.push(threadHeader);
for (let frameIndex = 0; frameIndex < thread.frames.length; frameIndex++) {
const frame = thread.frames[frameIndex];
const imageName = (typeof frame.imageIndex === "number" && images[frame.imageIndex] && images[frame.imageIndex].name)
? images[frame.imageIndex].name
: `image[${frame.imageIndex ?? "?"}]`;
const symbol = frame.symbol || (typeof frame.imageOffset === "number" ? `0x${frame.imageOffset.toString(16)}` : "<unknown>");
const symbolLocation = typeof frame.symbolLocation === "number" ? ` + ${frame.symbolLocation}` : "";
const sourceLocation = frame.sourceFile
? ` (${path.basename(frame.sourceFile)}${typeof frame.sourceLine === "number" ? `:${frame.sourceLine}` : ""})`
: "";
lines.push(`${String(frameIndex).padStart(3, " ")} ${imageName} ${symbol}${symbolLocation}${sourceLocation}`);
}
}
return lines.join("\n");
}
function formatBacktraceFromCrashText(crashContent) {
const match = crashContent.match(/Thread\s+\d+\s+Crashed:[\s\S]*?(?=\n\nThread\s+\d+|\nBinary Images:|$)/);
return match ? match[0] : null;
}
function emitLLDBBacktrace(appBinaryPath, runArgs) {
const runCommand = runArgs.length > 0
? `run ${runArgs.map(quoteForLLDB).join(" ")}`
: "run";
const args = [
"lldb",
"--batch",
"--one-line", "process handle -p true -s false -n false SIGSEGV SIGBUS SIGABRT SIGILL SIGTRAP",
"--one-line", runCommand,
"--one-line", "thread backtrace all",
"--",
appBinaryPath
];
const result = cp.spawnSync("xcrun", args, {
encoding: "utf8",
timeout: commandTimeoutMs,
maxBuffer: commandMaxBufferBytes
});
if (result.error) {
console.error(`ERROR: Unable to collect LLDB backtrace: ${result.error.message}`);
return;
}
const output = `${result.stdout || ""}${result.stderr || ""}`.trim();
if (output.length === 0) {
console.error("ERROR: LLDB produced no backtrace output.");
return;
}
console.error("\n--- Crash Backtrace (LLDB) ---");
console.error(output);
}
async function emitCrashBacktrace(appBinaryPath, runArgs, launchedAtMs, pid) {
const deadline = Date.now() + 5000;
while (Date.now() < deadline) {
const report = readRecentCrashReportForPid(pid, launchedAtMs);
if (report) {
const formatted = report.path.endsWith(".ips")
? formatBacktraceFromIPS(report.content)
: formatBacktraceFromCrashText(report.content);
if (formatted) {
console.error(`\n--- Crash Backtrace (${report.path}) ---`);
console.error(formatted);
return;
}
break;
}
await new Promise((resolve) => setTimeout(resolve, 200));
}
emitLLDBBacktrace(appBinaryPath, runArgs);
}
function runBuildAndRequireSuccess(command, args, timeoutMs = commandTimeoutMs) {
const result = cp.spawnSync(command, args, {
encoding: "utf8",
timeout: timeoutMs,
maxBuffer: commandMaxBufferBytes
});
if (result.error && result.error.code === "ETIMEDOUT") {
console.error(`ERROR: Command timed out after ${timeoutMs}ms: ${command} ${args.join(" ")}`);
if (result.stdout && result.stdout.trim().length > 0) {
console.error(result.stdout.trimEnd());
}
if (result.stderr && result.stderr.trim().length > 0) {
console.error(result.stderr.trimEnd());
}
process.exit(1);
}
if (result.error) {
throw result.error;
}
if (result.status !== 0) {
console.error(`ERROR: Build command failed: ${command} ${args.join(" ")}`);
if (result.stdout && result.stdout.trim().length > 0) {
console.error(result.stdout.trimEnd());
}
if (result.stderr && result.stderr.trim().length > 0) {
console.error(result.stderr.trimEnd());
}
process.exit(1);
}
}
function ensureMetadataGeneratorBuilt() {
const sourceMtime = metadataGeneratorSourceInputs.reduce(
(latest, inputPath) => Math.max(latest, getPathStats(inputPath).maxMtimeMs),
0
);
const artifactMtime = Math.min(
getPathStats(metadataGeneratorBinary).maxMtimeMs,
getPathStats(metadataGeneratorSymbolAnalyzer).maxMtimeMs,
getPathStats(metadataGeneratorBuildStepScript).maxMtimeMs
);
if (artifactMtime > 0 && artifactMtime >= sourceMtime) {
return;
}
console.log("Metadata generator is missing or stale; running build-metagen...");
const hostArch = os.arch() === "x64" ? "x86_64" : os.arch();
runBuildAndRequireSuccess(
"env",
[`METADATA_GENERATOR_ARCHS=${hostArch}`, "npm", "run", "build-metagen"],
commandTimeoutMs
);
}
function ensureMacOSRuntimeArtifactsBuilt() {
const cachePath = path.join(__dirname, "../dist", "intermediates", "macos", "CMakeCache.txt");
const sourceInputs = [
nativeScriptSourceRoot,
...metadataGeneratorSourceInputs,
path.join(__dirname, "build_nativescript.sh")
];
const sourceMtime = sourceInputs.reduce(
(latest, inputPath) => Math.max(latest, getPathStats(inputPath).maxMtimeMs),
0
);
const artifactMtime = getPathStats(nativeScriptXCFramework).maxMtimeMs;
let configuredEngine = null;
let configuredFfiBackend = null;
let configuredGsdBackend = null;
if (fs.existsSync(cachePath)) {
try {
const cache = fs.readFileSync(cachePath, "utf8");
const engineMatch = cache.match(/^TARGET_ENGINE:STRING=(.+)$/m);
if (engineMatch) {
configuredEngine = engineMatch[1].trim().toLowerCase();
}
const ffiBackendMatch = cache.match(/^NS_FFI_BACKEND:STRING=(.+)$/m);
if (ffiBackendMatch) {
configuredFfiBackend = ffiBackendMatch[1].trim().toLowerCase();
}
const gsdBackendMatch = cache.match(/^NS_GSD_BACKEND:STRING=(.+)$/m);
if (gsdBackendMatch) {
configuredGsdBackend = gsdBackendMatch[1].trim().toLowerCase();
}
} catch (_) {
configuredEngine = null;
configuredFfiBackend = null;
}
}
if (artifactMtime > 0 &&
artifactMtime >= sourceMtime &&
configuredEngine === requestedEngine &&
configuredFfiBackend === requestedFfiBackend &&
configuredGsdBackend === requestedGsdBackend) {
return;
}
const supportedEngines = new Set(["v8", "hermes", "quickjs", "jsc"]);
if (!supportedEngines.has(requestedEngine)) {
throw new Error(`Unsupported MACOS_TEST_ENGINE: ${requestedEngine}`);
}
const supportedFfiBackends = new Set(["auto", "napi", "v8", "hermes", "quickjs", "jsc"]);
if (!supportedFfiBackends.has(requestedFfiBackend)) {
throw new Error(`Unsupported MACOS_TEST_FFI_BACKEND: ${requestedFfiBackend}`);
}
const supportedGsdBackends = new Set(["auto", "v8", "jsc", "quickjs", "hermes", "napi", "none"]);
if (!supportedGsdBackends.has(requestedGsdBackend)) {
throw new Error(`Unsupported MACOS_TEST_GSD_BACKEND: ${requestedGsdBackend}`);
}
console.log(`NativeScript macOS artifacts are missing, stale, or built for '${configuredEngine ?? "unknown"}/${configuredFfiBackend ?? "unknown"}/${configuredGsdBackend ?? "unknown"}'; running ${requestedEngine}/${requestedFfiBackend}/${requestedGsdBackend} build...`);
runBuildAndRequireSuccess(
path.join(__dirname, "build_nativescript.sh"),
["--macos", "--no-iphone", "--no-simulator", `--${requestedEngine}`, `--ffi-backend=${requestedFfiBackend}`, `--gsd-backend=${requestedGsdBackend}`],
commandTimeoutMs
);
}
function buildTestRunnerApp() {
const appBundlePath = path.join(
derivedDataPath,
"Build",
"Products",
configuration,
"TestRunner.app"
);
const appResourcesPath = path.join(appBundlePath, "Contents", "Resources", "app");
const appPath = path.join(appBundlePath, "Contents", "MacOS", "TestRunner");
if (process.env.MACOS_TEST_CLEAN_BUILD === "1") {
fs.rmSync(derivedDataPath, { recursive: true, force: true });
}
ensureMetadataGeneratorBuilt();
ensureMacOSRuntimeArtifactsBuilt();
const nativeFingerprint = `${requestedEngine}:${requestedFfiBackend}:${requestedGsdBackend}:${createBuildFingerprint(macosBuildInputs)}`;
const existingBuildState = readBuildState();
const canReuseBuild = process.env.MACOS_TEST_CLEAN_BUILD !== "1" &&
fs.existsSync(appPath) &&
existingBuildState &&
existingBuildState.nativeFingerprint === nativeFingerprint;
console.log("Building...");
if (!canReuseBuild) {
const args = [
"-project", projectPath,
"-scheme", scheme,
"-configuration", configuration,
"-destination", "platform=macOS,arch=arm64",
"-derivedDataPath", derivedDataPath,
"CODE_SIGN_STYLE=Manual",
"CODE_SIGNING_ALLOWED=NO",
"CODE_SIGNING_REQUIRED=NO",
"CODE_SIGN_IDENTITY=",
"DEVELOPMENT_TEAM=",
"build"
];
runBuildAndRequireSuccess("xcodebuild", args, commandTimeoutMs);
}
syncAppResources(appResourcesPath);
writeBuildState(nativeFingerprint);
if (!fs.existsSync(appPath)) {
console.error(`ERROR: Built app executable not found at expected path: ${appPath}`);
process.exit(1);
}
return appPath;
}
function extractCount(xml, attribute) {
const regex = new RegExp(`${attribute}="(\\d+)"`, "g");
let total = 0;
let match;
while ((match = regex.exec(xml)) !== null) {
total += Number(match[1]);
}
return total;
}
function main() {
const { junitOutPath } = parseArgs();
fs.mkdirSync(path.dirname(junitOutPath), { recursive: true });
fs.mkdirSync(resultsDir, { recursive: true });
const skipBuild = process.env.MACOS_TEST_SKIP_BUILD === "1";
const appBinaryPath = skipBuild
? path.join(
derivedDataPath,
"Build",
"Products",
configuration,
"TestRunner.app",
"Contents",
"MacOS",
"TestRunner"
)
: buildTestRunnerApp();
if (!fs.existsSync(appBinaryPath)) {
console.error(`ERROR: App executable not found: ${appBinaryPath}`);
process.exit(1);
}
const runArgs = ["-logjunit"];
if (verboseSpecs) {
runArgs.push("-verbose-specs");
}
if (requestedTests.length > 0) {
runArgs.push("-tests", requestedTests);
}
if (requestedSpecs.length > 0) {
runArgs.push("-specs", requestedSpecs);
}
console.log(`Launching app and streaming logs: ${appBinaryPath} ${runArgs.join(" ")}`);
const results = fs.createWriteStream(junitOutPath);
let completedSuccessfully = false;
let completionKillIssued = false;
let junitBuffer = "";
let appLaunched = false;
let timeoutTimer = null;
let inactivityTimer = null;
let childPid = null;
let launchedAtMs = Date.now();
function clearTimers() {
if (timeoutTimer) {
clearTimeout(timeoutTimer);
timeoutTimer = null;
}
if (inactivityTimer) {
clearTimeout(inactivityTimer);
inactivityTimer = null;
}
}
function failAndExit(message, processHandle) {
console.error(message);
clearTimers();
results.end();
if (processHandle && !processHandle.killed) {
processHandle.kill("SIGKILL");
}
process.exit(1);
}
function scheduleInactivityTimeout(processHandle) {
if (inactivityTimer) {
clearTimeout(inactivityTimer);
}
inactivityTimer = setTimeout(() => {
failAndExit(`ERROR: No logs received for ${inactivityTimeoutMs}ms after launch.`, processHandle);
}, inactivityTimeoutMs);
}
timeoutTimer = setTimeout(() => {
failAndExit(`ERROR: Launch timeout after ${testTimeoutMs}ms.`, null);
}, testTimeoutMs);
const child = cp.spawn(appBinaryPath, runArgs, {
stdio: ["ignore", "pipe", "pipe"]
});
childPid = child.pid;
launchedAtMs = Date.now();
function createChunkHandler() {
let leftover = "";
return function handleChunk(chunk) {
const text = chunk.toString();
const chunks = leftover + text;
const lines = chunks.split(/\r?\n/);
for (let i = 0; i < lines.length - 1; i++) {
const line = lines[i];
process.stdout.write(`${stripConsoleLogPrefix(line)}\n`);
if (appLaunched) {
scheduleInactivityTimeout(child);
}
if (!appLaunched && line.indexOf(launchedMarker) !== -1) {
appLaunched = true;
if (timeoutTimer) {
clearTimeout(timeoutTimer);
}
timeoutTimer = setTimeout(() => {
failAndExit(`ERROR: Tests run timeout after ${testTimeoutMs}ms.`, child);
}, testTimeoutMs);
scheduleInactivityTimeout(child);
console.log("Application launched. Start test run timeout.");
}
const prefixIndex = line.indexOf(junitPrefix);
if (prefixIndex < 0) {
continue;
}
const data = line.slice(prefixIndex + junitPrefix.length);
results.write(data + "\n");
junitBuffer += data + "\n";
if (emitJunitLogs) {
// Already printed via process.stdout.write(text), keep behavior toggled for parity.
}
if (data.indexOf(junitEndTag) !== -1) {
completedSuccessfully = true;
clearTimers();
if (!completionKillIssued && child && !child.killed) {
completionKillIssued = true;
child.kill("SIGKILL");
}
}
}
leftover = lines[lines.length - 1];
};
}
child.stdout.on("data", createChunkHandler());
child.stderr.on("data", createChunkHandler());
child.on("error", (error) => {
failAndExit(`ERROR: Failed to start TestRunner process: ${error.message}`, child);
});
child.on("close", async (code, signal) => {
clearTimers();
results.end();
const exitStatus = getProcessExitStatus(code, signal);
if (!completedSuccessfully) {
if (code !== 0 || signal) {
await emitCrashBacktrace(appBinaryPath, runArgs, launchedAtMs, childPid);
}
console.error(`ERROR: Test run failed before JUnit completion. Exit code: ${exitStatus.display}`);
process.exit(exitStatus.code);
return;
}
const tests = extractCount(junitBuffer, "tests");
const failures = extractCount(junitBuffer, "failures");
const errors = extractCount(junitBuffer, "errors");
const skipped = extractCount(junitBuffer, "skipped");
console.log(`Summary: tests=${tests}, failures=${failures}, errors=${errors}, skipped=${skipped}`);
console.log(`Test run finished. JUnit written to: ${junitOutPath}`);
process.exit(failures > 0 || errors > 0 ? 1 : 0);
});
}
main();