Repository navigation
Expand file tree
/
Copy pathe2eRunRecord.test.js
More file actions
1998 lines (1851 loc) · 73 KB
/
Copy pathe2eRunRecord.test.js
File metadata and controls
1998 lines (1851 loc) · 73 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
const { execFileSync, spawn, spawnSync } = require('child_process');
const fs = require('fs');
const os = require('os');
const path = require('path');
const repoRoot = path.resolve(__dirname, '../../..');
const runRecord = require(path.join(repoRoot, 'tests/e2e/runRecord'));
jest.setTimeout(30000);
const recordLib = path.join(repoRoot, 'scripts/e2e/lib/e2e-run-record.sh');
const releaseScript = path.join(repoRoot, 'scripts/e2e/release-e2e-resources.sh');
function cleanEnv(extra) {
const env = { ...process.env };
for (const key of Object.keys(env)) {
if (
key.startsWith('RNFB_') ||
key.startsWith('E2E_') ||
key.startsWith('JET_') ||
key === 'RCT_METRO_PORT'
) {
delete env[key];
}
}
return { ...env, ...extra };
}
function writeExecutable(file, body) {
fs.writeFileSync(file, body);
fs.chmodSync(file, 0o755);
}
/** Fake bin dir: check passes, sleep is instant, lsof reports $RNFB_FAKE_LSOF. */
function fakeReleaseBin(dir) {
writeExecutable(
path.join(dir, 'bash'),
`#!/bin/bash
if [[ "$1" == *"/check-e2e-resources.sh" ]]; then
exit 0
fi
exec /bin/bash "$@"
`,
);
writeExecutable(path.join(dir, 'sleep'), '#!/bin/bash\nexit 0\n');
writeExecutable(
path.join(dir, 'lsof'),
`#!/bin/bash
if [[ "$*" == "-nP -iTCP -sTCP:LISTEN" && -f "$RNFB_FAKE_LSOF" ]]; then
cat "$RNFB_FAKE_LSOF"
exit 0
fi
[[ "$1" == "-a" ]] && exec ${realBin('lsof')} "$@"
exit 1
`,
);
}
function startSleeper() {
const child = spawn('/bin/sleep', ['60'], { stdio: 'ignore' });
const exited = new Promise(resolve => child.once('exit', (_code, signal) => resolve(signal)));
return { child, exited };
}
function settle(promise, ms) {
return Promise.race([
promise,
new Promise(resolve => setTimeout(() => resolve('running'), ms).unref()),
]);
}
/** Long-lived process whose args carry a device token needle (qemu @AVD / launchd_sim UDID). */
function startTokenProcess(...tokenArgs) {
const child = spawn(
process.execPath,
['-e', 'setTimeout(() => {}, 60000)', ...tokenArgs, HOST_MARK],
{ stdio: 'ignore' },
);
const exited = new Promise(resolve => child.once('exit', (_code, signal) => resolve(signal)));
return { child, exited };
}
function startTokenProcessIn(cwd, ...tokenArgs) {
const child = spawn(
process.execPath,
['-e', 'setTimeout(() => {}, 60000)', ...tokenArgs, HOST_MARK],
{ stdio: 'ignore', cwd },
);
const exited = new Promise(resolve => child.once('exit', (_code, signal) => resolve(signal)));
return { child, exited };
}
function pidAlive(pid) {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
async function waitGone(pid, ms) {
const end = Date.now() + ms;
while (Date.now() < end) {
if (!pidAlive(pid)) {
return true;
}
await new Promise(resolve => setTimeout(resolve, 50));
}
return !pidAlive(pid);
}
/**
* Start argv in the background of a throwaway shell so it is reparented away from this
* Jest worker: ownership must then come from the run record alone.
*/
function startDetached(argv, cwd = os.tmpdir()) {
const marked = argv[0] === process.execPath ? [...argv, HOST_MARK] : argv;
const out = execFileSync(
'/bin/sh',
['-c', '"$@" >/dev/null 2>&1 </dev/null & echo $!', 'sh', ...marked],
{
encoding: 'utf8',
cwd,
},
);
return Number(out.trim());
}
function alive(pid) {
try {
process.kill(pid, 0);
return true;
} catch (_) {
return false;
}
}
function killQuietly(pid) {
try {
process.kill(pid, 'SIGKILL');
} catch (_) {
// already gone
}
}
async function waitFor(predicate, ms = 5000) {
const deadline = Date.now() + ms;
while (Date.now() < deadline) {
if (predicate()) {
return true;
}
await new Promise(resolve => setTimeout(resolve, 100));
}
return predicate();
}
function freePort() {
return new Promise((resolve, reject) => {
const server = require('net').createServer();
server.once('error', reject);
server.listen(0, '127.0.0.1', () => {
const { port } = server.address();
server.close(() => resolve(port));
});
});
}
function realBin(name) {
return execFileSync('/bin/sh', ['-c', `command -v ${name}`], { encoding: 'utf8' }).trim();
}
/*
* Host device discovery sees only the fake devices this run started (they carry
* HOST_MARK): a real emulator or simulator, or another run of this suite (same fake
* names, same cwd), must not change results. ps (every form), pgrep and pkill hide
* unmarked qemu-system and launchd_sim processes; adb and simctl list no devices. pkill
* accepts only -f, -<signal number> and -<SIGNAME>, and exits 2 on anything else. Tests
* that need other answers put their own adb / xcrun earlier on PATH.
*/
const HOST_MARK = `rnfb-run-record-test=${process.pid}-${Date.now()}`;
const hostStubDir = fs.mkdtempSync(path.join(os.tmpdir(), 'rnfb-run-record-host-'));
const hostPath = process.env.PATH;
const hostPs = realBin('ps');
const deviceFilter = `re='qemu-system|launchd_sim'
foreign_device() { [[ "$1" =~ $re && "$1" != *${JSON.stringify(HOST_MARK)}* ]]; }`;
writeExecutable(
path.join(hostStubDir, 'ps'),
`#!/bin/bash
# awk is much faster than a bash [[ =~ ]] per line; under yarn test:full the slow
# filter previously made listProcesses hit execFileSync's timeout and return [].
mark=${JSON.stringify(HOST_MARK)}
${realBin('ps')} "$@" | awk -v mark="$mark" '
/qemu-system|launchd_sim/ && index(\$0, mark) == 0 { next }
{ print }
'
exit "\${PIPESTATUS[0]}"
`,
);
writeExecutable(
path.join(hostStubDir, 'pgrep'),
`#!/bin/bash
${deviceFilter}
out="$(${realBin('pgrep')} "$@")" || exit
kept=1
while IFS= read -r line; do
[[ -n "$line" ]] || continue
foreign_device "$(${realBin('ps')} -p "\${line%% *}" -o args= 2>/dev/null)" && continue
printf '%s\\n' "$line"
kept=0
done <<<"$out"
exit "$kept"
`,
);
writeExecutable(
path.join(hostStubDir, 'pkill'),
`#!/bin/bash
unsupported() {
echo "pkill test stub: unsupported argument '$1' (only -f, -<signal number>, -<SIGNAME>)" >&2
exit 2
}
sig=TERM
full=
patterns=()
for a in "$@"; do
case "$a" in
-f) full=-f ;;
-*)
name="\${a#-}"
name="\${name#SIG}"
[[ "$name" =~ ^([0-9]+|[A-Z][A-Z0-9]*)$ ]] && kill -l "$name" >/dev/null 2>&1 || unsupported "$a"
sig="$name"
;;
*) patterns+=("$a") ;;
esac
done
[[ \${#patterns[@]} -eq 1 ]] || unsupported "\${patterns[*]:-<no pattern>}"
pids="$(${JSON.stringify(path.join(hostStubDir, 'pgrep'))} $full "\${patterns[0]}")" || exit 1
kill -s "$sig" $pids
`,
);
writeExecutable(
path.join(hostStubDir, 'adb'),
`#!/bin/bash\n[[ "$1" == devices ]] && printf 'List of devices attached\\n\\n' && exit 0\nexit 1\n`,
);
writeExecutable(
path.join(hostStubDir, 'xcrun'),
`#!/bin/bash\n[[ "$*" == *-j* ]] && printf '{"devices":{}}\\n'\nexit 0\n`,
);
process.env.PATH = `${hostStubDir}:${hostPath}`;
afterAll(function () {
process.env.PATH = hostPath;
fs.rmSync(hostStubDir, { recursive: true, force: true });
});
describe('e2e run record (shell)', function () {
let dir;
beforeEach(function () {
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'rnfb-run-record-'));
});
afterEach(function () {
fs.rmSync(dir, { recursive: true, force: true });
});
function runLib(script, extraEnv = {}) {
return execFileSync('/bin/bash', ['-c', `source "${recordLib}"\n${script}`], {
encoding: 'utf8',
env: cleanEnv({ RNFB_E2E_RUN_RECORD_DIR: dir, ...extraEnv }),
});
}
it('keys the record by slot identity or serial', function () {
expect(runLib('e2e_run_record_dir', { RNFB_E2E_SLOT: '3' }).trim()).toBe(
path.join(dir, 'slot-3'),
);
expect(runLib('e2e_run_record_dir', { E2E_SLOT_OVERRIDE: '2' }).trim()).toBe(
path.join(dir, 'slot-2'),
);
expect(runLib('e2e_run_record_dir').trim()).toBe(path.join(dir, 'serial'));
});
it('owns descendants of a recorded pid and nothing else', function () {
const out = runLib(`
/bin/sleep 30 & child=$!
e2e_run_record_pid $$ root
e2e_run_record_load
e2e_pid_owned "$child" && echo CHILD_OWNED
e2e_pid_owned 1 || echo INIT_NOT_OWNED
kill "$child"
`);
expect(out).toMatch(/CHILD_OWNED/);
expect(out).toMatch(/INIT_NOT_OWNED/);
});
it('drops pid entries whose start time no longer matches (pid reuse)', function () {
const out = runLib(`
e2e_run_record_put "pid-$$" pid "$$" "Thu Jan 1 00:00:00 1970" stale
e2e_run_record_load
e2e_pid_owned $$ || echo STALE_NOT_OWNED
[[ -e "$(e2e_run_record_dir)/pid-$$" ]] || echo STALE_DROPPED
`);
expect(out).toMatch(/STALE_NOT_OWNED/);
expect(out).toMatch(/STALE_DROPPED/);
});
it('names pid entries per process instance so a reused pid never overwrites or drops another', function () {
const out = runLib(`
e2e_run_record_pid $$ root
ls "$(e2e_run_record_dir)"
`);
expect(out.trim()).toMatch(new RegExp(`^pid-${'\\d+'}-[A-Za-z0-9_]+$`));
});
it('keeps a device entry only while its recorded instance is alive', async function () {
const token = startTokenProcess('qemu-system-fake', '@TestingAVD-2', '-port', '5560');
try {
const start = runRecord.processStartTime(token.child.pid);
const out = runLib(`
e2e_run_record_put android-emulator-5560 android emulator-5560 TestingAVD-2 ${token.child.pid} "${start}"
e2e_run_record_put android-emulator-5562 android emulator-5562 TestingAVD-3 ${token.child.pid} "${start}"
e2e_run_record_put android-emulator-5554 android emulator-5554 TestingAVD ${token.child.pid} "${start}"
e2e_run_record_load
e2e_run_record_device_owned android emulator-5560 && echo LIVE_OWNED
e2e_run_record_device_owned android emulator-5562 || echo WRONG_AVD_NOT_OWNED
e2e_run_record_device_owned android emulator-5554 || echo PREFIX_AVD_NOT_OWNED
ls "$(e2e_run_record_dir)"
`);
expect(out).toMatch(/LIVE_OWNED/);
// Same qemu pid but another AVD in its args: not that instance.
expect(out).toMatch(/WRONG_AVD_NOT_OWNED/);
// Serial TestingAVD must not match a qemu for @TestingAVD-2 (complete-name match).
expect(out).toMatch(/PREFIX_AVD_NOT_OWNED/);
expect(out).toMatch(/android-emulator-5560/);
expect(out).not.toMatch(/android-emulator-5562/);
expect(out).not.toMatch(/android-emulator-5554/);
} finally {
token.child.kill('SIGKILL');
await token.exited;
}
const after = runLib(`e2e_run_record_load; ls "$(e2e_run_record_dir)"`);
expect(after).not.toMatch(/android-emulator-5560/);
});
});
describe('release-e2e-resources.sh scope', function () {
let dir;
const sleepers = [];
beforeEach(function () {
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'rnfb-release-scope-'));
fakeReleaseBin(dir);
});
afterEach(function () {
for (const { child } of sleepers.splice(0)) {
if (child.exitCode === null && child.signalCode === null) {
child.kill('SIGKILL');
}
}
fs.rmSync(dir, { recursive: true, force: true });
});
function release(args, extraEnv = {}) {
return execFileSync('/bin/bash', [releaseScript, ...args], {
encoding: 'utf8',
cwd: repoRoot,
stdio: ['ignore', 'pipe', 'pipe'],
env: cleanEnv({
PATH: `${dir}:${process.env.PATH}`,
RNFB_E2E_RUN_RECORD_DIR: path.join(dir, 'rec'),
RNFB_FAKE_LSOF: path.join(dir, 'lsof.out'),
...extraEnv,
}),
});
}
it('kills only the recorded listener on a slot port and leaves an unrecorded one', async function () {
const ours = startSleeper();
const theirs = startSleeper();
sleepers.push(ours, theirs);
// slot-1 android: jet :13010, jet-control :13011
fs.writeFileSync(
path.join(dir, 'lsof.out'),
[
'COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME',
`node ${ours.child.pid} me 20u IPv4 0x1 0t0 TCP 127.0.0.1:13010 (LISTEN)`,
`node ${theirs.child.pid} me 21u IPv4 0x2 0t0 TCP 127.0.0.1:13011 (LISTEN)`,
'',
].join('\n'),
);
runRecord.recordPid(ours.child.pid, 'jet:13010', {
RNFB_E2E_SLOT: '1',
RNFB_E2E_RUN_RECORD_DIR: path.join(dir, 'rec'),
});
const out = release(['--platform=android', '--slot=1', '--only=jet']);
expect(out).toMatch(
/identity: slot-1 .*scope=recorded \(\+ identity-AVD this-checkout-unrecorded\)/,
);
expect(out).toMatch(new RegExp(`SIGTERM :13010 pids=${ours.child.pid}\\b`));
expect(out).not.toMatch(new RegExp(`pids=.*\\b${theirs.child.pid}\\b`));
expect(await settle(ours.exited, 2000)).toBe('SIGTERM');
expect(await settle(theirs.exited, 200)).toBe('running');
});
it('macOS Jet records itself, so the default release frees its ports after an interrupted run', async function () {
// Stands in for `npx jet --target=macos` (cwd tests-macos): Jet loads .jetrc.js in the
// process that listens on the Jet and control ports.
const jetrcPath = path.join(repoRoot, 'tests-macos/.jetrc.js');
const child = spawn(
process.execPath,
[
'-e',
`require(${JSON.stringify(jetrcPath)}).recordJetProcess(13210); console.log('ready'); setTimeout(() => {}, 60000)`,
],
{
cwd: path.join(repoRoot, 'tests-macos'),
stdio: ['ignore', 'pipe', 'ignore'],
env: cleanEnv({ RNFB_E2E_SLOT: '1', RNFB_E2E_RUN_RECORD_DIR: path.join(dir, 'rec') }),
},
);
const exited = new Promise(resolve => child.once('exit', (_code, signal) => resolve(signal)));
sleepers.push({ child, exited });
await new Promise(resolve => child.stdout.once('data', resolve));
// slot-1 macos: jet :13210, jet-control :13211
fs.writeFileSync(
path.join(dir, 'lsof.out'),
[
'COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME',
`node ${child.pid} me 20u IPv4 0x1 0t0 TCP 127.0.0.1:13210 (LISTEN)`,
`node ${child.pid} me 21u IPv4 0x2 0t0 TCP 127.0.0.1:13211 (LISTEN)`,
'',
].join('\n'),
);
expect(
fs.readdirSync(path.join(dir, 'rec', 'slot-1')).filter(n => n.startsWith('pid-')),
).toHaveLength(1);
const out = release(['--platform=macos', '--slot=1', '--only=jet']);
expect(out).toMatch(/scope=recorded \(\+ identity-AVD this-checkout-unrecorded\)/);
expect(out).toMatch(new RegExp(`SIGTERM :13210 pids=${child.pid}\\b`));
expect(await settle(exited, 2000)).toBe('SIGTERM');
});
it('macOS .jetrc before() records the Jet process before it waits for Metro or spawns the app', function () {
const src = fs.readFileSync(path.join(repoRoot, 'tests-macos/.jetrc.js'), 'utf8');
const before = src.slice(src.indexOf('async before(config)'), src.indexOf('async after('));
const at = needle => {
const i = before.indexOf(needle);
expect(i).toBeGreaterThanOrEqual(0);
return i;
};
expect(src).toMatch(/recordPid\(process\.pid, `jet:\$\{jetPort\}`\)/);
expect(at('recordJetProcess(jetPort);')).toBeGreaterThan(at('throw foreignHolderError('));
expect(at('recordJetProcess(jetPort);')).toBeLessThan(at('await waitForMetroMacosBundle('));
expect(at('recordJetProcess(jetPort);')).toBeLessThan(at('spawn(macBinary'));
});
it('release names an unrecorded holder from this checkout without asserting why it is unrecorded', function () {
const pid = startDetached(['/bin/sleep', '60'], repoRoot);
try {
fs.writeFileSync(
path.join(dir, 'lsof.out'),
`sleep ${pid} me 21u IPv4 0x2 0t0 TCP 127.0.0.1:13210 (LISTEN)\n`,
);
const { stderr } = runRelease(['--platform=macos', '--slot=1', '--only=jet']);
expect(stderr).toMatch(
new RegExp(
`:13210 pid=${pid} .*owner=this-checkout-unrecorded — not recorded by this checkout's runs, left running: it runs from this checkout but no run recorded it \\(for example started outside yarn tests:\\*, before the run record existed, or by a step that does not record what it starts\\)`,
),
);
expect(alive(pid)).toBe(true);
} finally {
killQuietly(pid);
}
});
it('kills unrecorded listeners only with the manual --include-unrecorded flag', async function () {
const theirs = startSleeper();
sleepers.push(theirs);
fs.writeFileSync(
path.join(dir, 'lsof.out'),
`node ${theirs.child.pid} me 21u IPv4 0x2 0t0 TCP 127.0.0.1:13011 (LISTEN)\n`,
);
release(['--platform=android', '--slot=1', '--only=jet']);
expect(await settle(theirs.exited, 200)).toBe('running');
const out = release(['--platform=android', '--slot=1', '--only=jet', '--include-unrecorded']);
expect(out).toMatch(/scope=include-unrecorded \(manual\)/);
expect(await settle(theirs.exited, 2000)).toBe('SIGTERM');
});
it('never stops the adb server or stray emulators unless --all-slots is passed', async function () {
const log = path.join(dir, 'actions.log');
writeExecutable(
path.join(dir, 'adb'),
`#!/bin/bash
printf 'adb %s\\n' "$*" >> "${log}"
if [[ "$1" == "devices" ]]; then
printf 'List of devices attached\\nemulator-16222\\tdevice\\n'
fi
if [[ "$*" == "-s emulator-5558 emu avd name" ]]; then
printf '%s\\r\\nOK\\r\\n' "\${RNFB_FAKE_AVD_NAME:-TestingAVD-1}"
fi
exit 0
`,
);
writeExecutable(
path.join(dir, 'pkill'),
`#!/bin/bash\nprintf 'pkill %s\\n' "$*" >> "${log}"\nexit 0\n`,
);
release(['--platform=android', '--slot=1', '--devices', '--only=android-emulator']);
const scoped = fs.existsSync(log) ? fs.readFileSync(log, 'utf8') : '';
expect(scoped).not.toMatch(/emu kill/);
expect(scoped).not.toMatch(/kill-server/);
expect(scoped).not.toMatch(/^pkill /m);
const slotRecord = path.join(dir, 'rec', 'slot-1');
const entry = path.join(slotRecord, 'android-emulator-5558');
fs.mkdirSync(slotRecord, { recursive: true });
// Recorded instance gone (another owner rebooted TestingAVD-1): nothing is stopped.
fs.writeFileSync(
entry,
'android\temulator-5558\tTestingAVD-1\t999999\tThu Jan 1 00:00:00 1970\n',
);
release(['--platform=android', '--slot=1', '--devices', '--only=android-emulator']);
const stale = fs.existsSync(log) ? fs.readFileSync(log, 'utf8') : '';
expect(stale).not.toMatch(/emu kill/);
expect(stale).not.toMatch(/^pkill /m);
expect(fs.existsSync(entry)).toBe(false);
const qemu = startTokenProcess('qemu-system-fake', '@TestingAVD-1', '-port', '5558');
sleepers.push(qemu);
fs.writeFileSync(
entry,
`android\temulator-5558\tTestingAVD-1\t${qemu.child.pid}\t${runRecord.processStartTime(qemu.child.pid)}\n`,
);
release(['--platform=android', '--slot=1', '--devices', '--only=android-emulator']);
const recorded = fs.readFileSync(log, 'utf8');
expect(recorded).toMatch(/adb -s emulator-5558 emu kill/);
// Only that qemu pid is signalled — never a pkill by AVD name.
expect(recorded).not.toMatch(/^pkill /m);
expect(recorded).not.toMatch(/emulator-16222 emu kill/);
expect(await settle(qemu.exited, 2000)).toBe('SIGTERM');
// The recorded serial's console answers with another AVD (fallback serial): no emu
// kill on it, only the recorded qemu pid is signalled.
fs.rmSync(log);
const qemu2 = startTokenProcess('qemu-system-fake', '@TestingAVD-1', '-port', '5558');
sleepers.push(qemu2);
fs.writeFileSync(
entry,
`android\temulator-5558\tTestingAVD-1\t${qemu2.child.pid}\t${runRecord.processStartTime(qemu2.child.pid)}\n`,
);
release(['--platform=android', '--slot=1', '--devices', '--only=android-emulator'], {
RNFB_FAKE_AVD_NAME: 'SomeoneElsesAVD',
});
const mismatched = fs.readFileSync(log, 'utf8');
expect(mismatched).toMatch(/adb -s emulator-5558 emu avd name/);
expect(mismatched).not.toMatch(/emu kill/);
expect(await settle(qemu2.exited, 2000)).toBe('SIGTERM');
fs.rmSync(log);
release(['--platform=android', '--all-slots', '--devices', '--only=android-emulator']);
const wiped = fs.readFileSync(log, 'utf8');
expect(wiped).toMatch(/adb -s emulator-16222 emu kill/);
expect(wiped).not.toMatch(/kill-server/);
});
it('default --devices also stops an emulator a recorded process spawned', async function () {
const log = path.join(dir, 'actions.log');
writeExecutable(
path.join(dir, 'adb'),
`#!/bin/bash
printf 'adb %s\\n' "$*" >> "${log}"
[[ "$*" == "-s emulator-16224 emu avd name" ]] && printf 'TestingAVD-1\\r\\nOK\\r\\n'
exit 0
`,
);
const childPidFile = path.join(dir, 'child.pid');
const qemuArgs = JSON.stringify([
'-e',
'setTimeout(() => {}, 60000)',
'qemu-system-fake',
'@TestingAVD-1',
'-port',
'16224',
HOST_MARK,
]);
const parent = spawn(
process.execPath,
[
'-e',
`const c = require('child_process').spawn(process.execPath, ${qemuArgs}, { stdio: 'ignore' });
require('fs').writeFileSync(${JSON.stringify(childPidFile)}, String(c.pid));
setTimeout(() => {}, 60000);`,
],
{ stdio: 'ignore', cwd: os.tmpdir() },
);
const parentExited = new Promise(resolve => parent.once('exit', resolve));
let qemuPid;
try {
const end = Date.now() + 5000;
while (!fs.existsSync(childPidFile) && Date.now() < end) {
await new Promise(resolve => setTimeout(resolve, 50));
}
qemuPid = Number(fs.readFileSync(childPidFile, 'utf8'));
release(['--platform=android', '--slot=1', '--devices', '--only=android-emulator']);
expect(pidAlive(qemuPid)).toBe(true);
runRecord.recordPid(parent.pid, 'jet:13010', {
RNFB_E2E_SLOT: '1',
RNFB_E2E_RUN_RECORD_DIR: path.join(dir, 'rec'),
});
const out = release([
'--platform=android',
'--slot=1',
'--devices',
'--only=android-emulator',
]);
expect(out).toMatch(
new RegExp(
`stop serial=emulator-16224 avd=TestingAVD-1 qemu=${qemuPid} \\(child of a recorded process\\)`,
),
);
expect(fs.readFileSync(log, 'utf8')).toMatch(/adb -s emulator-16224 emu kill/);
expect(await waitGone(qemuPid, 3000)).toBe(true);
} finally {
if (qemuPid && pidAlive(qemuPid)) {
process.kill(qemuPid, 'SIGKILL');
}
parent.kill('SIGKILL');
await parentExited;
}
});
it('default --devices stops this checkout’s unrecorded emulator on the identity’s AVD; never another owner’s', async function () {
writeExecutable(path.join(dir, 'adb'), '#!/bin/bash\nexit 0\n');
const own = startTokenProcessIn(
repoRoot,
'qemu-system-fake',
'@TestingAVD-1',
'-port',
'16226',
);
const foreign = startTokenProcessIn(
os.tmpdir(),
'qemu-system-fake',
'@TestingAVD-1',
'-port',
'16228',
);
const otherIdentity = startTokenProcessIn(
repoRoot,
'qemu-system-fake',
'@TestingAVD-2',
'-port',
'16230',
);
// Register before nested setup so a mkdir/mkdtemp failure cannot leak the tokens.
sleepers.push(own, foreign, otherIdentity);
// Nested worktree under this path (e.g. .claude/): prefix-match alone would claim it.
// Parent may be absent on a clean CI checkout (.claude is gitignored).
const nestedParent = path.join(repoRoot, '.claude');
fs.mkdirSync(nestedParent, { recursive: true });
const nestedRoot = fs.mkdtempSync(path.join(nestedParent, 'rnfb-nested-release-'));
try {
execFileSync('git', ['init', '--quiet'], { cwd: nestedRoot });
const nested = startTokenProcessIn(
nestedRoot,
'qemu-system-fake',
'@TestingAVD-1',
'-port',
'16231',
);
sleepers.push(nested);
const run = args =>
spawnSync('/bin/bash', [releaseScript, ...args], {
encoding: 'utf8',
cwd: repoRoot,
env: cleanEnv({
PATH: `${dir}:${process.env.PATH}`,
RNFB_E2E_RUN_RECORD_DIR: path.join(dir, 'rec'),
RNFB_FAKE_LSOF: path.join(dir, 'lsof.out'),
}),
});
const scoped = ['--platform=android', '--slot=1', '--devices', '--only=android-emulator'];
const out = run(scoped);
expect(out.stdout).toMatch(
new RegExp(`qemu=${own.child.pid} \\(owner=this-checkout-unrecorded\\)`),
);
expect(await settle(own.exited, 2000)).toBe('SIGTERM');
expect(out.stderr).toMatch(
new RegExp(
`serial=emulator-16228 avd=TestingAVD-1 .*owner=unrecorded — not this checkout's, left running`,
),
);
expect(await settle(foreign.exited, 300)).toBe('running');
expect(out.stdout).not.toMatch(/16230/);
expect(await settle(otherIdentity.exited, 300)).toBe('running');
expect(out.stderr).toMatch(
new RegExp(
`serial=emulator-16231 avd=TestingAVD-1 .*owner=unrecorded — not this checkout's, left running`,
),
);
expect(await settle(nested.exited, 300)).toBe('running');
} finally {
fs.rmSync(nestedRoot, { recursive: true, force: true });
}
});
function runRelease(args, extraEnv = {}) {
return spawnSync('/bin/bash', [releaseScript, ...args], {
encoding: 'utf8',
cwd: repoRoot,
env: cleanEnv({
PATH: `${dir}:${process.env.PATH}`,
RNFB_E2E_RUN_RECORD_DIR: path.join(dir, 'rec'),
RNFB_FAKE_LSOF: path.join(dir, 'lsof.out'),
...extraEnv,
}),
});
}
describe('harness device reboot (launchApp-retry cold boot)', function () {
const { bootAndRecord } = require(path.join(repoRoot, 'tests/e2e/deviceBoot'));
const slotEnv = () => ({
RNFB_E2E_SLOT: '1',
RNFB_E2E_RUN_RECORD_DIR: path.join(dir, 'rec'),
});
const scoped = ['--platform=android', '--slot=1', '--devices', '--only=android-emulator'];
const testsDir = path.join(repoRoot, 'tests');
const started = [];
afterEach(function () {
for (const pid of started.splice(0)) {
if (pidAlive(pid)) {
process.kill(pid, 'SIGKILL');
}
}
});
// Stands in for coldBootAndroidEmulator: the old qemu is gone and a new one is spawned
// by the (unrecorded) Detox worker from tests/, then reparented once that worker exits.
function coldBoot(port, cwd = testsDir) {
const pid = startDetached(
[
process.execPath,
'-e',
'setTimeout(() => {}, 60000)',
'qemu-system-fake',
'@TestingAVD-1',
'-port',
port,
],
cwd,
);
started.push(pid);
return pid;
}
// As the harness wrapper does: the cold boot spawned `-port <port>` itself.
function recordColdBoot(port) {
return runRecord.recordAndroidDevice(`emulator-${port}`, 'TestingAVD-1', slotEnv(), {
requireSerial: true,
});
}
function check() {
return spawnSync(
'/bin/bash',
[
path.join(repoRoot, 'scripts/e2e/check-e2e-resources.sh'),
'--platform=android',
'--slot=1',
],
{
encoding: 'utf8',
cwd: repoRoot,
env: cleanEnv({
PATH: `${dir}:${process.env.PATH}`,
RNFB_E2E_RUN_RECORD_DIR: path.join(dir, 'rec'),
RNFB_FAKE_LSOF: path.join(dir, 'lsof.out'),
// As export-slot-env android 1 pins them.
ANDROID_SERIAL: 'emulator-5558',
RNFB_ANDROID_CONSOLE_PORT: '5558',
RNFB_ANDROID_AVD: 'TestingAVD-1',
}),
},
);
}
beforeEach(function () {
writeExecutable(path.join(dir, 'adb'), '#!/bin/bash\nexit 0\n');
});
it('without a re-record, release --devices still stops this checkout’s cold-booted emulator', async function () {
const qemuPid = coldBoot('16250');
const out = runRelease(scoped);
expect(out.stdout).toMatch(
new RegExp(
`stop serial=emulator-16250 avd=TestingAVD-1 qemu=${qemuPid} \\(owner=this-checkout-unrecorded\\)`,
),
);
expect(out.stdout + out.stderr).not.toMatch(/--include-unrecorded/);
expect(await waitGone(qemuPid, 3000)).toBe(true);
});
it('check is BUSY for a FreePortFinder identity-AVD qemu; default --devices clears it', async function () {
const qemuPid = coldBoot('16250');
const result = check();
expect(result.status).toBe(1);
expect(result.stdout).toMatch(
new RegExp(
`BUSY\\s+android emulator emulator-16250 avd=TestingAVD-1 qemu pid=${qemuPid} cwd=${testsDir} owner=this-checkout-unrecorded — no run recorded it \\(e\\.g\\. cold-boot respawn\\); free with yarn tests:e2e:release --devices --slot=1`,
),
);
// BUSY line names --devices; must not push --include-unrecorded for this category.
expect(result.stdout).not.toMatch(/include-unrecorded/);
expect(result.stderr).not.toMatch(/--include-unrecorded --only [^\n]*\bandroid-emulator\b/);
const out = runRelease(scoped);
expect(out.stdout).toMatch(
new RegExp(
`stop serial=emulator-16250 avd=TestingAVD-1 qemu=${qemuPid} \\(owner=this-checkout-unrecorded\\)`,
),
);
expect(out.stdout + out.stderr).not.toMatch(/--include-unrecorded/);
expect(await waitGone(qemuPid, 3000)).toBe(true);
// Fake adb exit-0 makes app probes BUSY; assert the FreePortFinder qemu line is gone.
expect(check().stdout).not.toMatch(/emulator-16250/);
// check BUSY on this qemu is what makes release soft-kill miss → forceful round;
// the force path itself is covered by clear_android_emulator hard + existing
// stopQemuPids SIGTERM-ignore coverage below.
});
it('bootAndRecord re-records the cold-booted instance, so release --devices stops it', async function () {
let qemuPid;
await bootAndRecord(
async () => {
qemuPid = coldBoot('16252');
},
() => expect(recordColdBoot('16252')).toBe('emulator-16252'),
);
expect(fs.readdirSync(path.join(dir, 'rec', 'slot-1'))).toContain('android-emulator-16252');
const out = runRelease(scoped);
expect(out.stdout).toMatch(
new RegExp(
`stop serial=emulator-16252 avd=TestingAVD-1 qemu=${qemuPid} \\(recorded instance\\)`,
),
);
expect(await waitGone(qemuPid, 3000)).toBe(true);
});
it('bootAndRecord records even when the boot throws after the new instance is up', async function () {
let qemuPid;
await expect(
bootAndRecord(
async () => {
qemuPid = coldBoot('16254');
throw new Error('cold-boot spawn did not register');
},
() => recordColdBoot('16254'),
),
).rejects.toThrow('did not register');
expect(fs.readdirSync(path.join(dir, 'rec', 'slot-1'))).toContain('android-emulator-16254');
runRelease(scoped);
expect(await waitGone(qemuPid, 3000)).toBe(true);
});
it('check is BUSY for this checkout’s unrecorded emulator on the identity AVD at its allocated serial', function () {
const qemuPid = coldBoot('5558');
const result = check();
expect(result.status).toBe(1);
expect(result.stdout).toMatch(
new RegExp(
`BUSY\\s+android emulator emulator-5558 avd=TestingAVD-1 qemu pid=${qemuPid} cwd=${testsDir} owner=this-checkout-unrecorded — no run recorded it \\(e\\.g\\. cold-boot respawn\\); free with yarn tests:e2e:release --devices --slot=1`,
),
);
// Default --devices frees this category; footer must not list android-emulator under
// --include-unrecorded (fake adb may still note android-apps separately).
expect(result.stdout).not.toMatch(/include-unrecorded/);
expect(result.stderr).not.toMatch(/--include-unrecorded --only [^\n]*\bandroid-emulator\b/);
recordColdBoot('5558');
// A live recorded instance is owned by the run record (release --devices frees it);
// host-clear does not fail solely on a warm AVD the run still owns.
expect(check().stdout).not.toMatch(/android emulator emulator-5558/);
});
it("check is BUSY for another owner's emulator on this identity's serial, INFO with a remedy elsewhere", function () {
const foreignCwd = fs.mkdtempSync(path.join(os.tmpdir(), 'rnfb-other-owner-'));
try {
const onOurs = coldBoot('5558', foreignCwd);
const onSlot2 = coldBoot('5560', foreignCwd);
const result = check();
expect(result.status).toBe(1);
expect(result.stdout).toMatch(
new RegExp(
`BUSY\\s+android emulator emulator-5558 avd=TestingAVD-1 qemu pid=${onOurs} cwd=${fs.realpathSync(foreignCwd)} owner=unrecorded — another owner's emulator on this identity's serial emulator-5558; release leaves it running \\(free it from its owner, or move this run to a free slot\\)`,
),
);
expect(result.stdout).toMatch(
new RegExp(
`INFO\\s+android emulator emulator-5560 avd=TestingAVD-1 qemu pid=${onSlot2} .*owner=unrecorded — not this checkout's; release leaves it running \\(free it from its owner, or move this run to a free slot\\)`,
),
);
expect(result.stderr).toMatch(
/owner=unrecorded: held by another owner .*first free slot: \d+/,
);
} finally {
fs.rmSync(foreignCwd, { recursive: true, force: true });
}
});
it('requireSerial never adopts a lone same-AVD emulator on another serial', function () {
coldBoot('16240');
expect(
runRecord.recordAndroidDevice('emulator-5558', 'TestingAVD-1', slotEnv(), {
requireSerial: true,
}),
).toBeNull();
expect(fs.existsSync(path.join(dir, 'rec', 'slot-1'))).toBe(false);
expect(runRecord.recordAndroidDevice('emulator-5558', 'TestingAVD-1', slotEnv())).toBe(
'emulator-16240',
);
});
it("the cold-boot stop ends only this run's emulator; another owner's same-AVD one survives", async function () {
const { ownQemuPids, ownQemuRunning, stopQemuPids } = require(
path.join(repoRoot, 'tests/e2e/androidColdBoot'),
);
const foreignCwd = fs.mkdtempSync(path.join(os.tmpdir(), 'rnfb-other-owner-'));
try {
const ownOnPort = coldBoot('5558');
const ownRecorded = coldBoot('16264');
expect(recordColdBoot('16264')).toBe('emulator-16264');
const foreign = coldBoot('16262', foreignCwd);
const foreignOtherAvd = startDetached(
[
process.execPath,
'-e',
'setTimeout(() => {}, 60000)',
'qemu-system-fake',
'@Other',
'-port',
'5558',
],
foreignCwd,
);
started.push(foreignOtherAvd);
// Another owner's same-AVD qemu on our console port (the tokens bind no socket).
const foreignOnOurPort = coldBoot('5558', foreignCwd);
// One process snapshot for both helpers: separate listProcesses/lsof rounds under
// host load previously let ownQemuRunning pass while ownQemuPids saw [].
expect(
await waitFor(() => {
const processes = runRecord.listProcesses();
return (
ownQemuRunning('5558', 'TestingAVD-1', { env: slotEnv(), processes }) &&
ownQemuPids('5558', 'TestingAVD-1', { env: slotEnv(), processes })
.slice()
.sort()
.join(',') === [ownOnPort, ownRecorded].slice().sort().join(',')
);
}),
).toBe(true);
const processes = runRecord.listProcesses();
const pids = ownQemuPids('5558', 'TestingAVD-1', { env: slotEnv(), processes });
expect(pids.slice().sort()).toEqual([ownOnPort, ownRecorded].slice().sort());
await stopQemuPids(pids, { timeoutMs: 5000, pollMs: 50 });
expect(pidAlive(ownOnPort)).toBe(false);
expect(pidAlive(ownRecorded)).toBe(false);
expect(await waitGone(foreign, 300)).toBe(false);
expect(pidAlive(foreignOtherAvd)).toBe(true);
expect(pidAlive(foreignOnOurPort)).toBe(true);
// Neither waited on nor re-recorded as this run's relaunch.
expect(ownQemuRunning('5558', 'TestingAVD-1', { env: slotEnv() })).toBe(false);
expect(ownQemuRunning('16262', 'TestingAVD-1', { env: slotEnv() })).toBe(false);
expect(recordColdBoot('5558')).toBeNull();
expect(fs.readdirSync(path.join(dir, 'rec', 'slot-1'))).not.toContain(
'android-emulator-5558',
);
} finally {
fs.rmSync(foreignCwd, { recursive: true, force: true });
}
});
it('the cold-boot stop SIGKILLs an own qemu that ignores SIGTERM', async function () {
const { stopQemuPids } = require(path.join(repoRoot, 'tests/e2e/androidColdBoot'));
const stubborn = startDetached(
[