-
Notifications
You must be signed in to change notification settings - Fork 29.7k
/
test-watch-mode.mjs
768 lines (674 loc) Β· 23.5 KB
/
test-watch-mode.mjs
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
import * as common from '../common/index.mjs';
import tmpdir from '../common/tmpdir.js';
import assert from 'node:assert';
import path from 'node:path';
import { execPath } from 'node:process';
import { describe, it } from 'node:test';
import { spawn } from 'node:child_process';
import { writeFileSync, readFileSync, mkdirSync } from 'node:fs';
import { inspect } from 'node:util';
import { pathToFileURL } from 'node:url';
import { once } from 'node:events';
import { createInterface } from 'node:readline';
if (common.isIBMi)
common.skip('IBMi does not support `fs.watch()`');
const supportsRecursive = common.isMacOS || common.isWindows;
function restart(file, content = readFileSync(file)) {
// To avoid flakiness, we save the file repeatedly until test is done
writeFileSync(file, content);
const timer = setInterval(() => writeFileSync(file, content), common.platformTimeout(2500));
return () => clearInterval(timer);
}
let tmpFiles = 0;
function createTmpFile(content = 'console.log("running");', ext = '.js', basename = tmpdir.path) {
const file = path.join(basename, `${tmpFiles++}${ext}`);
writeFileSync(file, content);
return file;
}
function runInBackground({ args = [], options = {}, completed = 'Completed running', shouldFail = false }) {
let future = Promise.withResolvers();
let child;
let stderr = '';
let stdout = [];
const run = () => {
args.unshift('--no-warnings');
child = spawn(execPath, args, { encoding: 'utf8', stdio: 'pipe', ...options });
child.stderr.on('data', (data) => {
stderr += data;
});
const rl = createInterface({ input: child.stdout });
rl.on('line', (data) => {
if (!data.startsWith('Waiting for graceful termination') && !data.startsWith('Gracefully restarted')) {
stdout.push(data);
if (data.startsWith(completed)) {
future.resolve({ stderr, stdout });
future = Promise.withResolvers();
stdout = [];
stderr = '';
} else if (data.startsWith('Failed running')) {
if (shouldFail) {
future.resolve({ stderr, stdout });
} else {
future.reject({ stderr, stdout });
}
future = Promise.withResolvers();
stdout = [];
stderr = '';
}
}
});
};
return {
async done() {
child?.kill();
future.resolve();
return { stdout, stderr };
},
restart(timeout = 1000) {
if (!child) {
run();
}
const timer = setTimeout(() => {
if (!future.resolved) {
child.kill();
future.reject(new Error('Timed out waiting for restart'));
}
}, timeout);
return future.promise.finally(() => {
clearTimeout(timer);
});
}
};
}
async function runWriteSucceed({
file,
watchedFile,
watchFlag = '--watch',
args = [file],
completed = 'Completed running',
restarts = 2,
options = {},
shouldFail = false
}) {
args.unshift('--no-warnings');
if (watchFlag !== null) args.unshift(watchFlag);
const child = spawn(execPath, args, { encoding: 'utf8', stdio: 'pipe', ...options });
let completes = 0;
let cancelRestarts = () => {};
let stderr = '';
const stdout = [];
child.stderr.on('data', (data) => {
stderr += data;
});
try {
// Break the chunks into lines
for await (const data of createInterface({ input: child.stdout })) {
if (!data.startsWith('Waiting for graceful termination') && !data.startsWith('Gracefully restarted')) {
stdout.push(data);
}
if (data.startsWith(completed)) {
completes++;
if (completes === restarts) {
break;
}
if (completes === 1) {
cancelRestarts = restart(watchedFile);
}
}
if (!shouldFail && data.startsWith('Failed running')) {
break;
}
}
} finally {
child.kill();
cancelRestarts();
}
return { stdout, stderr, pid: child.pid };
}
async function failWriteSucceed({ file, watchedFile }) {
const child = spawn(execPath, ['--watch', '--no-warnings', file], { encoding: 'utf8', stdio: 'pipe' });
let cancelRestarts = () => {};
try {
// Break the chunks into lines
for await (const data of createInterface({ input: child.stdout })) {
if (data.startsWith('Completed running')) {
break;
}
if (data.startsWith('Failed running')) {
cancelRestarts = restart(watchedFile, 'console.log("test has ran");');
}
}
} finally {
child.kill();
cancelRestarts();
}
}
tmpdir.refresh();
describe('watch mode', { concurrency: !process.env.TEST_PARALLEL, timeout: 60_000 }, () => {
it('should watch changes to a file', async () => {
const file = createTmpFile();
const { stderr, stdout } = await runWriteSucceed({ file, watchedFile: file, watchFlag: '--watch=true', options: {
timeout: 10000
} });
assert.strictEqual(stderr, '');
assert.deepStrictEqual(stdout, [
'running',
`Completed running ${inspect(file)}`,
`Restarting ${inspect(file)}`,
'running',
`Completed running ${inspect(file)}`,
]);
});
it('should watch changes to a file - event loop ended', async () => {
const file = createTmpFile();
const { stderr, stdout } = await runWriteSucceed({ file, watchedFile: file });
assert.strictEqual(stderr, '');
assert.deepStrictEqual(stdout, [
'running',
`Completed running ${inspect(file)}`,
`Restarting ${inspect(file)}`,
'running',
`Completed running ${inspect(file)}`,
]);
});
it('should reload env variables when --env-file changes', async () => {
const envKey = `TEST_ENV_${Date.now()}`;
const jsFile = createTmpFile(`console.log('ENV: ' + process.env.${envKey});`);
const envFile = createTmpFile(`${envKey}=value1`, '.env');
const { done, restart } = runInBackground({ args: ['--watch', `--env-file=${envFile}`, jsFile] });
try {
await restart();
writeFileSync(envFile, `${envKey}=value2`);
// Second restart, after env change
const { stdout, stderr } = await restart();
assert.strictEqual(stderr, '');
assert.deepStrictEqual(stdout, [
`Restarting ${inspect(jsFile)}`,
'ENV: value2',
`Completed running ${inspect(jsFile)}`,
]);
} finally {
await done();
}
});
it('should load new env variables when --env-file changes', async () => {
const envKey = `TEST_ENV_${Date.now()}`;
const envKey2 = `TEST_ENV_2_${Date.now()}`;
const jsFile = createTmpFile(`console.log('ENV: ' + process.env.${envKey} + '\\n' + 'ENV2: ' + process.env.${envKey2});`);
const envFile = createTmpFile(`${envKey}=value1`, '.env');
const { done, restart } = runInBackground({ args: ['--watch', `--env-file=${envFile}`, jsFile] });
try {
await restart();
await writeFileSync(envFile, `${envKey}=value1\n${envKey2}=newValue`);
// Second restart, after env change
const { stderr, stdout } = await restart();
assert.strictEqual(stderr, '');
assert.deepStrictEqual(stdout, [
`Restarting ${inspect(jsFile)}`,
'ENV: value1',
'ENV2: newValue',
`Completed running ${inspect(jsFile)}`,
]);
} finally {
await done();
}
});
it('should watch changes to a failing file', async () => {
const file = createTmpFile('throw new Error("fails");');
const { stderr, stdout } = await runWriteSucceed({
file,
watchedFile: file,
completed: 'Failed running',
shouldFail: true
});
assert.match(stderr, /Error: fails\r?\n/);
assert.deepStrictEqual(stdout, [
`Failed running ${inspect(file)}`,
`Restarting ${inspect(file)}`,
`Failed running ${inspect(file)}`,
]);
});
it('should watch changes to a file with watch-path', {
skip: !supportsRecursive,
}, async () => {
const dir = tmpdir.resolve('subdir1');
mkdirSync(dir);
const file = createTmpFile();
const watchedFile = createTmpFile('', '.js', dir);
const args = ['--watch-path', dir, file];
const { stderr, stdout } = await runWriteSucceed({ file, watchedFile, args });
assert.strictEqual(stderr, '');
assert.deepStrictEqual(stdout, [
'running',
`Completed running ${inspect(file)}`,
`Restarting ${inspect(file)}`,
'running',
`Completed running ${inspect(file)}`,
]);
assert.strictEqual(stderr, '');
});
it('should watch when running an non-existing file - when specified under --watch-path', {
skip: !supportsRecursive
}, async () => {
const dir = tmpdir.resolve('subdir2');
mkdirSync(dir);
const file = path.join(dir, 'non-existing.js');
const watchedFile = createTmpFile('', '.js', dir);
const args = ['--watch-path', dir, file];
const { stderr, stdout } = await runWriteSucceed({
file,
watchedFile,
args,
completed: 'Failed running',
shouldFail: true
});
assert.match(stderr, /Error: Cannot find module/g);
assert.deepStrictEqual(stdout, [
`Failed running ${inspect(file)}`,
`Restarting ${inspect(file)}`,
`Failed running ${inspect(file)}`,
]);
});
it('should watch when running an non-existing file - when specified under --watch-path with equals', {
skip: !supportsRecursive
}, async () => {
const dir = tmpdir.resolve('subdir3');
mkdirSync(dir);
const file = path.join(dir, 'non-existing.js');
const watchedFile = createTmpFile('', '.js', dir);
const args = [`--watch-path=${dir}`, file];
const { stderr, stdout } = await runWriteSucceed({
file,
watchedFile,
args,
completed: 'Failed running',
shouldFail: true
});
assert.match(stderr, /Error: Cannot find module/g);
assert.deepStrictEqual(stdout, [
`Failed running ${inspect(file)}`,
`Restarting ${inspect(file)}`,
`Failed running ${inspect(file)}`,
]);
});
it('should watch changes to a file - event loop blocked', { timeout: 10_000 }, async () => {
const file = createTmpFile(`
console.log("running");
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0);
console.log("don't show me");`);
const { stderr, stdout } = await runWriteSucceed({ file, watchedFile: file, completed: 'running' });
assert.strictEqual(stderr, '');
assert.deepStrictEqual(stdout, [
'running',
`Restarting ${inspect(file)}`,
'running',
]);
});
it('should watch changes to dependencies - cjs', async () => {
const dependency = createTmpFile('module.exports = {};');
const file = createTmpFile(`
const dependency = require(${JSON.stringify(dependency)});
console.log(dependency);
`);
const { stderr, stdout } = await runWriteSucceed({ file, watchedFile: dependency });
assert.strictEqual(stderr, '');
assert.deepStrictEqual(stdout, [
'{}',
`Completed running ${inspect(file)}`,
`Restarting ${inspect(file)}`,
'{}',
`Completed running ${inspect(file)}`,
]);
});
it('should watch changes to dependencies - esm', async () => {
const dependency = createTmpFile('module.exports = {};');
const file = createTmpFile(`
import dependency from ${JSON.stringify(pathToFileURL(dependency))};
console.log(dependency);
`, '.mjs');
const { stderr, stdout } = await runWriteSucceed({ file, watchedFile: dependency });
assert.strictEqual(stderr, '');
assert.deepStrictEqual(stdout, [
'{}',
`Completed running ${inspect(file)}`,
`Restarting ${inspect(file)}`,
'{}',
`Completed running ${inspect(file)}`,
]);
});
it('should restart multiple times', async () => {
const file = createTmpFile();
const { stderr, stdout } = await runWriteSucceed({ file, watchedFile: file, restarts: 3 });
assert.strictEqual(stderr, '');
assert.deepStrictEqual(stdout, [
'running',
`Completed running ${inspect(file)}`,
`Restarting ${inspect(file)}`,
'running',
`Completed running ${inspect(file)}`,
`Restarting ${inspect(file)}`,
'running',
`Completed running ${inspect(file)}`,
]);
});
it('should pass arguments to file', async () => {
const file = createTmpFile(`
const { parseArgs } = require('node:util');
const { values } = parseArgs({ options: { random: { type: 'string' } } });
console.log(values.random);
`);
const random = Date.now().toString();
const args = [file, '--random', random];
const { stderr, stdout } = await runWriteSucceed({ file, watchedFile: file, args });
assert.strictEqual(stderr, '');
assert.deepStrictEqual(stdout, [
random,
`Completed running ${inspect(`${file} --random ${random}`)}`,
`Restarting ${inspect(`${file} --random ${random}`)}`,
random,
`Completed running ${inspect(`${file} --random ${random}`)}`,
]);
});
it('should load --require modules in the watched process, and not in the orchestrator process', async () => {
const file = createTmpFile();
const required = createTmpFile('process._rawDebug(\'pid\', process.pid);');
const args = ['--require', required, file];
const { stdout, pid, stderr } = await runWriteSucceed({ file, watchedFile: file, args });
const importPid = parseInt(stderr[0].split(' ')[1], 10);
assert.notStrictEqual(pid, importPid);
assert.deepStrictEqual(stdout, [
'running',
`Completed running ${inspect(file)}`,
`Restarting ${inspect(file)}`,
'running',
`Completed running ${inspect(file)}`,
]);
});
it('should load --import modules in the watched process, and not in the orchestrator process', async () => {
const file = createTmpFile();
const imported = "data:text/javascript,process._rawDebug('pid', process.pid);";
const args = ['--import', imported, file];
const { stdout, pid, stderr } = await runWriteSucceed({ file, watchedFile: file, args });
const importPid = parseInt(stderr.split('\n', 1)[0].split(' ', 2)[1], 10);
assert.notStrictEqual(importPid, NaN);
assert.notStrictEqual(pid, importPid);
assert.deepStrictEqual(stdout, [
'running',
`Completed running ${inspect(file)}`,
`Restarting ${inspect(file)}`,
'running',
`Completed running ${inspect(file)}`,
]);
});
// TODO: Remove skip after https://github.com/nodejs/node/pull/45271 lands
it('should not watch when running an missing file', {
skip: !supportsRecursive
}, async () => {
const nonExistingfile = tmpdir.resolve(`${tmpFiles++}.js`);
await failWriteSucceed({ file: nonExistingfile, watchedFile: nonExistingfile });
});
it('should not watch when running an missing mjs file', {
skip: !supportsRecursive
}, async () => {
const nonExistingfile = tmpdir.resolve(`${tmpFiles++}.mjs`);
await failWriteSucceed({ file: nonExistingfile, watchedFile: nonExistingfile });
});
it('should watch changes to previously missing dependency', {
skip: !supportsRecursive
}, async () => {
const dependency = tmpdir.resolve(`${tmpFiles++}.js`);
const relativeDependencyPath = `./${path.basename(dependency)}`;
const dependant = createTmpFile(`console.log(require('${relativeDependencyPath}'))`);
await failWriteSucceed({ file: dependant, watchedFile: dependency });
});
it('should watch changes to previously missing ESM dependency', {
skip: !supportsRecursive
}, async () => {
const relativeDependencyPath = `./${tmpFiles++}.mjs`;
const dependency = tmpdir.resolve(relativeDependencyPath);
const dependant = createTmpFile(`import ${JSON.stringify(relativeDependencyPath)}`, '.mjs');
await failWriteSucceed({ file: dependant, watchedFile: dependency });
});
it('should clear output between runs', async () => {
const file = createTmpFile();
const { stderr, stdout } = await runWriteSucceed({ file, watchedFile: file });
assert.strictEqual(stderr, '');
assert.deepStrictEqual(stdout, [
'running',
`Completed running ${inspect(file)}`,
`Restarting ${inspect(file)}`,
'running',
`Completed running ${inspect(file)}`,
]);
});
it('should preserve output when --watch-preserve-output flag is passed', async () => {
const file = createTmpFile();
const args = ['--watch-preserve-output', file];
const { stderr, stdout } = await runWriteSucceed({ file, watchedFile: file, args });
assert.strictEqual(stderr, '');
assert.deepStrictEqual(stdout, [
'running',
`Completed running ${inspect(file)}`,
`Restarting ${inspect(file)}`,
'running',
`Completed running ${inspect(file)}`,
]);
});
it('should run when `--watch-path=./foo --require ./bar.js`', {
skip: !supportsRecursive,
}, async () => {
const projectDir = tmpdir.resolve('project2');
mkdirSync(projectDir);
const dir = path.join(projectDir, 'watched-dir');
mkdirSync(dir);
writeFileSync(path.join(projectDir, 'some.js'), 'console.log(\'hello\')');
const file = createTmpFile('console.log(\'running\');', '.js', projectDir);
const watchedFile = createTmpFile('', '.js', dir);
const args = [`--watch-path=${dir}`, '--require', './some.js', file];
const { stdout, stderr } = await runWriteSucceed({
file, watchedFile, args, options: {
cwd: projectDir
}
});
assert.strictEqual(stderr, '');
assert.deepStrictEqual(stdout, [
'hello',
'running',
`Completed running ${inspect(file)}`,
`Restarting ${inspect(file)}`,
'hello',
'running',
`Completed running ${inspect(file)}`,
]);
});
it('should run when `--watch-path=./foo --require=./bar.js`', {
skip: !supportsRecursive,
}, async () => {
const projectDir = tmpdir.resolve('project3');
mkdirSync(projectDir);
const dir = path.join(projectDir, 'watched-dir');
mkdirSync(dir);
writeFileSync(path.join(projectDir, 'some.js'), "console.log('hello')");
const file = createTmpFile("console.log('running');", '.js', projectDir);
const watchedFile = createTmpFile('', '.js', dir);
const args = [`--watch-path=${dir}`, '--require=./some.js', file];
const { stdout, stderr } = await runWriteSucceed({
file, watchedFile, args, options: {
cwd: projectDir
}
});
assert.strictEqual(stderr, '');
assert.deepStrictEqual(stdout, [
'hello',
'running',
`Completed running ${inspect(file)}`,
`Restarting ${inspect(file)}`,
'hello',
'running',
`Completed running ${inspect(file)}`,
]);
});
it('should run when `--watch-path ./foo --require ./bar.js`', {
skip: !supportsRecursive,
}, async () => {
const projectDir = tmpdir.resolve('project5');
mkdirSync(projectDir);
const dir = path.join(projectDir, 'watched-dir');
mkdirSync(dir);
writeFileSync(path.join(projectDir, 'some.js'), 'console.log(\'hello\')');
const file = createTmpFile('console.log(\'running\');', '.js', projectDir);
const watchedFile = createTmpFile('', '.js', dir);
const args = ['--watch-path', `${dir}`, '--require', './some.js', file];
const { stdout, stderr } = await runWriteSucceed({
file, watchedFile, args, options: {
cwd: projectDir
}
});
assert.strictEqual(stderr, '');
assert.deepStrictEqual(stdout, [
'hello',
'running',
`Completed running ${inspect(file)}`,
`Restarting ${inspect(file)}`,
'hello',
'running',
`Completed running ${inspect(file)}`,
]);
});
it('should run when `--watch-path=./foo --require=./bar.js`', {
skip: !supportsRecursive,
}, async () => {
const projectDir = tmpdir.resolve('project6');
mkdirSync(projectDir);
const dir = path.join(projectDir, 'watched-dir');
mkdirSync(dir);
writeFileSync(path.join(projectDir, 'some.js'), "console.log('hello')");
const file = createTmpFile("console.log('running');", '.js', projectDir);
const watchedFile = createTmpFile('', '.js', dir);
const args = ['--watch-path', `${dir}`, '--require=./some.js', file];
const { stdout, stderr } = await runWriteSucceed({
file, watchedFile, args, options: {
cwd: projectDir
}
});
assert.strictEqual(stderr, '');
assert.deepStrictEqual(stdout, [
'hello',
'running',
`Completed running ${inspect(file)}`,
`Restarting ${inspect(file)}`,
'hello',
'running',
`Completed running ${inspect(file)}`,
]);
});
it('should run when `--watch --inspect`', async () => {
const file = createTmpFile();
const args = ['--watch', '--inspect', file];
const { stdout, stderr } = await runWriteSucceed({ file, watchedFile: file, watchFlag: null, args });
assert.match(stderr, /listening on ws:\/\//);
assert.deepStrictEqual(stdout, [
'running',
`Completed running ${inspect(file)}`,
`Restarting ${inspect(file)}`,
'running',
`Completed running ${inspect(file)}`,
]);
});
it('should run when `--watch -r ./foo.js`', async () => {
const projectDir = tmpdir.resolve('project7');
mkdirSync(projectDir);
const dir = path.join(projectDir, 'watched-dir');
mkdirSync(dir);
writeFileSync(path.join(projectDir, 'some.js'), "console.log('hello')");
const file = createTmpFile("console.log('running');", '.js', projectDir);
const args = ['--watch', '-r', './some.js', file];
const { stdout, stderr } = await runWriteSucceed({
file, watchedFile: file, watchFlag: null, args, options: { cwd: projectDir }
});
assert.strictEqual(stderr, '');
assert.deepStrictEqual(stdout, [
'hello',
'running',
`Completed running ${inspect(file)}`,
`Restarting ${inspect(file)}`,
'hello',
'running',
`Completed running ${inspect(file)}`,
]);
});
it('should pass IPC messages from a spawning parent to the child and back', async () => {
const file = createTmpFile(`console.log('running');
process.on('message', (message) => {
if (message === 'exit') {
process.exit(0);
} else {
console.log('Received:', message);
process.send(message);
}
})`);
const child = spawn(
execPath,
[
'--watch',
'--no-warnings',
file,
],
{
encoding: 'utf8',
stdio: ['pipe', 'pipe', 'pipe', 'ipc'],
},
);
let stderr = '';
let stdout = '';
child.stdout.on('data', (data) => stdout += data);
child.stderr.on('data', (data) => stderr += data);
async function waitForEcho(msg) {
const receivedPromise = new Promise((resolve) => {
const fn = (message) => {
if (message === msg) {
child.off('message', fn);
resolve();
}
};
child.on('message', fn);
});
child.send(msg);
await receivedPromise;
}
async function waitForText(text) {
const seenPromise = new Promise((resolve) => {
const fn = (data) => {
if (data.toString().includes(text)) {
resolve();
child.stdout.off('data', fn);
}
};
child.stdout.on('data', fn);
});
await seenPromise;
}
await waitForText('running');
await waitForEcho('first message');
const stopRestarts = restart(file);
await waitForText('running');
stopRestarts();
await waitForEcho('second message');
const exitedPromise = once(child, 'exit');
child.send('exit');
await waitForText('Completed');
child.disconnect();
child.kill();
await exitedPromise;
assert.strictEqual(stderr, '');
const lines = stdout.split(/\r?\n/).filter(Boolean);
assert.deepStrictEqual(lines, [
'running',
'Received: first message',
`Restarting ${inspect(file)}`,
'running',
'Received: second message',
`Completed running ${inspect(file)}`,
]);
});
});