Newer
Older
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
import { exec as _exec } from 'child_process';
import { ExecOptions } from '../lib/util/exec';
type CallOptions = ExecOptions | null | undefined;
export type ExecResult = { stdout: string; stderr: string } | Error;
interface ExecSnapshot {
cmd: string;
options?: ExecOptions | null | undefined;
}
export type ExecSnapshots = ExecSnapshot[];
export function execSnapshot(cmd: string, options?: CallOptions): ExecSnapshot {
const snapshot = {
cmd,
options,
};
const str = JSON.stringify(snapshot, (k, v) => (v === undefined ? null : v));
const cwd = process.cwd().replace(/\\(\w)/g, '/$1');
return JSON.parse(
str
.replace(/\\(\w)/g, '/$1')
.split(cwd)
.join('/root/project')
);
}
const defaultExecResult = { stdout: '', stderr: '' };
export function mockExecAll(
execFn: jest.Mock<typeof _exec>,
execResult: ExecResult = defaultExecResult
): ExecSnapshots {
const snapshots = [];
execFn.mockImplementation((cmd, options, callback) => {
snapshots.push(execSnapshot(cmd, options));
if (execResult instanceof Error) {
throw execResult;
}
callback(null, execResult);
return undefined;
});
return snapshots;
}
export function mockExecSequence(
execFn: jest.Mock<typeof _exec>,
execResults: ExecResult[]
): ExecSnapshots {
const snapshots = [];
execResults.forEach(execResult => {
execFn.mockImplementationOnce((cmd, options, callback) => {
snapshots.push(execSnapshot(cmd, options));
if (execResult instanceof Error) {
throw execResult;
}
callback(null, execResult);
return undefined;
});
});
return snapshots;
}
const basicEnvMock = {
HTTP_PROXY: 'http://example.com',
HTTPS_PROXY: 'https://example.com',
NO_PROXY: 'localhost',
HOME: '/home/user',
PATH: '/tmp/path',
LANG: 'en_US.UTF-8',
LC_ALL: 'en_US',
};
const fullEnvMock = {
...basicEnvMock,
SELECTED_ENV_VAR: 'Can be selected',
FILTERED_ENV_VAR: 'Should be filtered',
};
const filteredEnvMock = {
...basicEnvMock,
SELECTED_ENV_VAR: fullEnvMock.SELECTED_ENV_VAR,
};
export const envMock = {
basic: basicEnvMock,
full: fullEnvMock,
filtered: filteredEnvMock,
};