forked from tinylibs/tinyexec
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_test.ts
More file actions
451 lines (389 loc) · 13.8 KB
/
main_test.ts
File metadata and controls
451 lines (389 loc) · 13.8 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
import {x, xSync, ExecProcess, NonZeroExitError} from '../main.js';
import {describe, test, expect} from 'vitest';
import os from 'node:os';
import fs from 'node:fs';
import path from 'node:path';
import {spawnSync} from 'node:child_process';
const isWindows = os.platform() === 'win32';
const variants = [
{name: 'async', x, isAsync: true},
{name: 'sync', x: xSync, isAsync: false}
];
describe.each(variants)('exec ($name)', ({x, isAsync}) => {
test('pid is number', async () => {
const proc = x('echo', ['foo']);
await proc;
expect(typeof proc.pid === 'number').ok;
});
test('exitCode is set correctly', async () => {
const proc = x('echo', ['foo']);
// only async API will have its exitCode undefined before awaiting;
// for sync API the process has already exited by the time we reach here
if (isAsync) {
expect(proc.exitCode).toBe(undefined);
}
const result = await proc;
expect(proc.exitCode).toBe(0);
expect(result.exitCode).toBe(0);
});
test('async iterator gets correct output', async () => {
const proc = x('node', ['-e', "console.log('foo'); console.log('bar');"]);
const lines = [];
for await (const line of proc) {
lines.push(line);
}
expect(lines).toEqual(['foo', 'bar']);
});
test('resolves to stdout', async () => {
const result = await x('node', ['-e', "console.log('foo')"]);
expect(result.stdout).toBe('foo\n');
expect(result.stderr).toBe('');
});
test('captures stderr', async () => {
const result = await x('node', ['-e', "console.error('some error')"]);
expect(result.stderr).toBe('some error\n');
expect(result.stdout).toBe('');
});
});
describe('exec (async)', () => {
test('non-zero exitCode throws when throwOnError=true', async () => {
const proc = x('node', ['-e', 'process.exit(1);'], {throwOnError: true});
await expect(async () => {
await proc;
}).rejects.toThrow(NonZeroExitError);
expect(proc.exitCode).toBe(1);
});
test('async iterator throws when throwOnError=true and exit non-zero', async () => {
const proc = x('node', ['-e', "console.log('foo'); process.exit(1);"], {
throwOnError: true
});
const lines: string[] = [];
await expect(async () => {
for await (const line of proc) {
lines.push(line);
}
}).rejects.toThrow(NonZeroExitError);
expect(lines).toEqual(['foo']);
expect(proc.exitCode).toBe(1);
});
test('supports stdin passed as a string', async () => {
let result = await x('node', ['-e', 'process.stdin.pipe(process.stdout)'], {
stdin: 'foo\nbar'
});
expect(result.stdout).toBe('foo\nbar');
expect(result.stderr).toBe('');
expect(result.exitCode).toBe(0);
// Ensuring that empty string doesn’t cause issues
result = await x(
'node',
['-e', "process.stdout.write(String(fs.readFileSync(0,'utf8').length))"],
{stdin: ''}
);
expect(result.stdout).toBe('0');
expect(result.stderr).toBe('');
expect(result.exitCode).toBe(0);
});
test('supports stdin passed as another process (Result)', async () => {
const proc = x('node', ['-e', "process.stdout.write('foo\\nbar')"]);
const result = await x(
'node',
['-e', 'process.stdin.pipe(process.stdout)'],
{stdin: proc}
);
expect(result.stdout).toBe('foo\nbar');
expect(result.stderr).toBe('');
expect(result.exitCode).toBe(0);
});
test('supports stdin passed as another process (ExecProcess)', async () => {
const proc = new ExecProcess('node', [
'-e',
"process.stdout.write('foo\\nbar')"
]);
proc.spawn();
const result = await x(
'node',
['-e', 'process.stdin.pipe(process.stdout)'],
{stdin: proc}
);
expect(result.stdout).toBe('foo\nbar');
expect(result.stderr).toBe('');
expect(result.exitCode).toBe(0);
});
});
describe('exec (sync)', () => {
test('non-zero exitCode throws when throwOnError=true', () => {
expect(() => {
xSync('node', ['-e', 'process.exit(1);'], {throwOnError: true});
}).toThrow(NonZeroExitError);
});
});
if (isWindows) {
describe.each(variants)('exec (windows) ($name)', ({x}) => {
test('does not throw spawn errors', async () => {
const result = await x('definitelyNonExistent');
expect(result.stderr).toBe(
"'definitelyNonExistent' is not recognized as an internal" +
' or external command,\r\noperable program or batch file.\r\n'
);
expect(result.stdout).toBe('');
});
});
describe('exec (windows) (async)', () => {
test('times out after defined timeout (ms)', async () => {
// Somewhat filthy way of waiting for 2 seconds across cmd/ps
const proc = x('ping', ['127.0.0.1', '-n', '2'], {timeout: 100});
await expect(async () => {
await proc;
}).rejects.toThrow();
expect(proc.killed).toBe(true);
expect(proc.process!.signalCode).toBe('SIGTERM');
});
test('throws spawn errors when throwOnError=true', async () => {
const proc = x('definitelyNonExistent', [], {throwOnError: true});
try {
await proc;
expect.fail('Expected to throw');
} catch (err) {
expect(err instanceof NonZeroExitError).ok;
expect((err as NonZeroExitError).output?.stderr).toBe(
"'definitelyNonExistent' is not recognized as an internal" +
' or external command,\r\noperable program or batch file.\r\n'
);
expect((err as NonZeroExitError).output?.stdout).toBe('');
}
});
test('kill terminates the process', async () => {
// Somewhat filthy way of waiting for 2 seconds across cmd/ps
const proc = x('ping', ['127.0.0.1', '-n', '2']);
const result = proc.kill();
expect(result).ok;
expect(proc.killed).ok;
expect(proc.aborted).toBe(false);
});
test('pipe correctly pipes output', async () => {
const echoProc = x('node', ['-e', "console.log('foo')"]);
const grepProc = echoProc.pipe('findstr', ['f']);
const result = await grepProc;
expect(result.stderr).toBe('');
expect(result.stdout).toBe('foo\n');
expect(result.exitCode).toBe(0);
expect(echoProc.exitCode).toBe(0);
expect(grepProc.exitCode).toBe(0);
});
test('signal can be used to abort execution', async () => {
const controller = new AbortController();
// Somewhat filthy way of waiting for 2 seconds across cmd/ps
const proc = x('ping', ['127.0.0.1', '-n', '2'], {
signal: controller.signal
});
controller.abort();
const result = await proc;
expect(proc.aborted).ok;
expect(proc.killed).ok;
expect(result.stderr).toBe('');
expect(result.stdout).toBe('');
});
test('iterator receives errors as lines', async () => {
const proc = x('nonexistentforsure');
const lines: string[] = [];
for await (const line of proc) {
lines.push(line);
}
expect(lines).toEqual([
"'nonexistentforsure' is not recognized as an internal or " +
'external command,',
'operable program or batch file.'
]);
});
test('preserves leading ./ so cwd-local binary is run, not PATH lookup', async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tinyexec-relpath-'));
try {
const scriptPath = path.join(dir, 'mytool.cmd');
fs.writeFileSync(scriptPath, '@echo local\r\n');
const result = await x('./mytool.cmd', [], {
nodeOptions: {cwd: dir}
});
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('local\r\n');
} finally {
fs.rmSync(dir, {recursive: true, force: true});
}
});
});
describe('exec (windows) (sync)', () => {
test('times out after defined timeout (ms)', () => {
expect(() => {
xSync('ping', ['127.0.0.1', '-n', '2'], {timeout: 100});
}).toThrow();
});
test('iterator receives errors as lines', () => {
const proc = xSync('nonexistentforsure');
const lines: string[] = [];
for (const line of proc) {
lines.push(line);
}
expect(lines).toEqual([
"'nonexistentforsure' is not recognized as an internal or " +
'external command,',
'operable program or batch file.'
]);
});
test('preserves leading ./ so cwd-local binary is run, not PATH lookup', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tinyexec-relpath-'));
try {
const scriptPath = path.join(dir, 'mytool.cmd');
fs.writeFileSync(scriptPath, '@echo local\r\n');
const result = xSync('./mytool.cmd', [], {
nodeOptions: {cwd: dir}
});
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('local\r\n');
} finally {
fs.rmSync(dir, {recursive: true, force: true});
}
});
});
}
if (!isWindows) {
describe('exec (unix-like) (async)', () => {
test('times out after defined timeout (ms)', async () => {
const proc = x('sleep', ['0.2'], {timeout: 100});
await expect(async () => {
await proc;
}).rejects.toThrow('The operation was aborted');
expect(proc.killed).toBe(true);
expect(proc.process!.signalCode).toBe('SIGTERM');
});
test('throws spawn errors', async () => {
const proc = x('definitelyNonExistent');
await expect(async () => {
await proc;
}).rejects.toThrow(
process.versions.bun
? 'Executable not found in $PATH: "definitelyNonExistent"'
: 'spawn definitelyNonExistent ENOENT'
);
});
test('kill terminates the process', async () => {
const proc = x('sleep', ['5']);
const result = proc.kill();
expect(result).ok;
expect(proc.killed).ok;
expect(proc.aborted).toBe(false);
});
test('pipe correctly pipes output', async () => {
const echoProc = x('echo', ['foo\nbar']);
const grepProc = echoProc.pipe('grep', ['foo']);
const result = await grepProc;
expect(result.stderr).toBe('');
expect(result.stdout).toBe('foo\n');
expect(result.exitCode).toBe(0);
expect(echoProc.exitCode).toBe(0);
expect(grepProc.exitCode).toBe(0);
});
test('signal can be used to abort execution', async () => {
const controller = new AbortController();
const proc = x('sleep', ['4'], {signal: controller.signal});
controller.abort();
const result = await proc;
expect(proc.aborted).ok;
expect(proc.killed).ok;
expect(result.stderr).toBe('');
expect(result.stdout).toBe('');
});
test('iterator receives errors', async () => {
const proc = x('nonexistentforsure');
await expect(async () => {
for await (const line of proc) {
line;
}
}).rejects.toThrow();
});
test('preserves leading ./ so cwd-local binary is run, not PATH lookup', async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tinyexec-relpath-'));
try {
const scriptPath = path.join(dir, 'mytool');
fs.writeFileSync(scriptPath, '#!/bin/sh\necho local\n');
fs.chmodSync(scriptPath, 0o755);
const result = await x('./mytool', [], {
nodeOptions: {cwd: dir, env: {PATH: '/usr/bin:/bin'}}
});
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('local\n');
} finally {
fs.rmSync(dir, {recursive: true, force: true});
}
});
test('resolves when grandchild holds piped stdout open', async () => {
const proc = spawnSync(
'node',
['test/fixtures/spawn_grandchild.mjs', 'grandchild.mjs'],
{
timeout: 3_000,
encoding: 'utf8',
killSignal: 'SIGKILL',
stdio: ['pipe', 'pipe', 'pipe']
}
);
expect(proc.signal).not.toBe('SIGKILL');
expect(proc.status).toBe(0);
const parsed = JSON.parse(proc.stdout.trim());
expect(parsed.exitCode).toBe(0);
expect(parsed.stdout).toBe('line1\nline2\n');
spawnSync('pkill', ['-f', 'grandchild.mjs']);
});
test('iterator completes when grandchild holds piped stdout open', async () => {
const proc = spawnSync(
'node',
['test/fixtures/spawn_grandchild_iterator.mjs'],
{
timeout: 3_000,
encoding: 'utf8',
killSignal: 'SIGKILL',
stdio: ['pipe', 'pipe', 'pipe']
}
);
expect(proc.signal).not.toBe('SIGKILL');
expect(proc.status).toBe(0);
const parsed = JSON.parse(proc.stdout.trim());
expect(parsed).toEqual(['line1', 'line2']);
spawnSync('pkill', ['-f', 'grandchild.mjs']);
});
});
describe('exec (unix-like) (sync)', () => {
test('times out after defined timeout (ms)', () => {
expect(() => {
xSync('sleep', ['0.2'], {timeout: 100});
}).toThrow('spawnSync sleep ETIMEDOUT');
});
test('throws spawn errors', () => {
expect(() => {
xSync('definitelyNonExistent');
}).toThrow(
process.versions.bun
? 'Executable not found in $PATH: "definitelyNonExistent"'
: 'spawnSync definitelyNonExistent ENOENT'
);
});
test('iterator receives errors', () => {
expect(() => {
xSync('nonexistentforsure');
}).toThrow();
});
test('preserves leading ./ so cwd-local binary is run, not PATH lookup', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tinyexec-relpath-'));
try {
const scriptPath = path.join(dir, 'mytool');
fs.writeFileSync(scriptPath, '#!/bin/sh\necho local\n');
fs.chmodSync(scriptPath, 0o755);
const result = xSync('./mytool', [], {
nodeOptions: {cwd: dir, env: {PATH: '/usr/bin:/bin'}}
});
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('local\n');
} finally {
fs.rmSync(dir, {recursive: true, force: true});
}
});
});
}