Skip to content

Commit d9e9b57

Browse files
committed
Add subprocess test utility for environment isolation
1 parent f985ecf commit d9e9b57

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

test/utils/subprocess.mts

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/** @fileoverview Test utilities for running code in subprocesses with custom environments. */
2+
3+
import { spawn } from 'node:child_process'
4+
5+
/**
6+
* Run code in a subprocess with custom environment variables.
7+
*/
8+
export function runInSubprocess(
9+
env: Record<string, string>,
10+
testCode: string,
11+
): Promise<{ stdout: string; stderr: string; exitCode: number | null }> {
12+
return new Promise((resolve, reject) => {
13+
const child = spawn(
14+
process.execPath,
15+
['--input-type=module', '--eval', testCode],
16+
{
17+
env: {
18+
...process.env,
19+
...env,
20+
},
21+
stdio: ['pipe', 'pipe', 'pipe'],
22+
},
23+
)
24+
25+
let stdout = ''
26+
let stderr = ''
27+
28+
child.stdout.on('data', data => {
29+
stdout += data.toString()
30+
})
31+
32+
child.stderr.on('data', data => {
33+
stderr += data.toString()
34+
})
35+
36+
child.on('close', exitCode => {
37+
resolve({ exitCode, stderr, stdout })
38+
})
39+
40+
child.on('error', reject)
41+
})
42+
}

0 commit comments

Comments
 (0)