/
child-process-proxy.spec.ts
278 lines (240 loc) · 8.78 KB
/
child-process-proxy.spec.ts
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
import * as childProcess from 'child_process';
import { EventEmitter } from 'events';
import * as os from 'os';
import { LogLevel, StrykerOptions } from '@stryker-mutator/api/core';
import { Logger } from '@stryker-mutator/api/logging';
import { factory } from '@stryker-mutator/test-helpers';
import { expect } from 'chai';
import * as sinon from 'sinon';
import ChildProcessProxy from '../../../src/child-proxy/child-process-proxy';
import {
autoStart,
DisposeMessage,
InitMessage,
ParentMessage,
ParentMessageKind,
WorkerMessage,
WorkerMessageKind,
} from '../../../src/child-proxy/message-protocol';
import { LoggingClientContext } from '../../../src/logging';
import { serialize } from '../../../src/utils/object-utils';
import * as objectUtils from '../../../src/utils/object-utils';
import currentLogMock from '../../helpers/log-mock';
import { Mock } from '../../helpers/producers';
import { HelloClass } from './hello-class';
const LOGGING_CONTEXT: LoggingClientContext = Object.freeze({
level: LogLevel.Fatal,
port: 4200,
});
class ChildProcessMock extends EventEmitter {
public send = sinon.stub();
public stderr = new EventEmitter();
public stdout = new EventEmitter();
public pid = 4648;
}
describe(ChildProcessProxy.name, () => {
let sut: ChildProcessProxy<HelloClass>;
let forkStub: sinon.SinonStub;
let childProcessMock: ChildProcessMock;
let killStub: sinon.SinonStub;
let logMock: Mock<Logger>;
let clock: sinon.SinonFakeTimers;
beforeEach(() => {
clock = sinon.useFakeTimers();
childProcessMock = new ChildProcessMock();
forkStub = sinon.stub(childProcess, 'fork');
killStub = sinon.stub(objectUtils, 'kill');
forkStub.returns(childProcessMock);
logMock = currentLogMock();
});
afterEach(() => {
childProcessMock.removeAllListeners();
childProcessMock.stderr.removeAllListeners();
childProcessMock.stdout.removeAllListeners();
});
describe('constructor', () => {
it('should create child process', () => {
sut = createSut();
expect(forkStub).calledWith(require.resolve('../../../src/child-proxy/child-process-proxy-worker'), [autoStart], {
silent: true,
execArgv: [],
});
});
it('should send init message to child process', () => {
const expectedMessage: InitMessage = {
additionalInjectableValues: { name: 'fooTest' },
kind: WorkerMessageKind.Init,
loggingContext: LOGGING_CONTEXT,
options: factory.strykerOptions(),
requireName: 'HelloClass',
requirePath: 'foobar',
workingDirectory: 'workingDirectory',
};
// Act
createSut({
loggingContext: LOGGING_CONTEXT,
name: (expectedMessage.additionalInjectableValues as { name: string }).name,
options: expectedMessage.options,
requirePath: expectedMessage.requirePath,
workingDir: expectedMessage.workingDirectory,
});
// Assert
expect(childProcessMock.send).calledWith(serialize(expectedMessage));
});
it('should log the exec arguments and require name', () => {
// Act
createSut({
loggingContext: LOGGING_CONTEXT,
execArgv: ['--cpu-prof', '--inspect'],
});
// Assert
expect(logMock.debug).calledWith('Started %s in child process %s%s', 'HelloClass', childProcessMock.pid, ' (using args --cpu-prof --inspect)');
});
it('should listen to worker process', () => {
createSut();
expect(childProcessMock.listeners('message')).lengthOf(1);
});
it('should listen for close calls', () => {
createSut();
expect(childProcessMock.listeners('close')).lengthOf(1);
});
it('should set `execArgv`', () => {
createSut({ execArgv: ['--inspect-brk'] });
expect(forkStub).calledWithMatch(sinon.match.string, sinon.match.array, sinon.match({ execArgv: ['--inspect-brk'] }));
});
});
describe('on close', () => {
beforeEach(() => {
sut = createSut();
});
it('should log stdout and stderr on warning', () => {
childProcessMock.stdout.emit('data', 'bar');
childProcessMock.stderr.emit('data', 'foo');
actClose(23, 'SIGTERM');
expect(logMock.warn).calledWithMatch(
`Child process [pid ${childProcessMock.pid}] exited unexpectedly with exit code 23 (SIGTERM). Last part of stdout and stderr was:${os.EOL}\tfoo${os.EOL}\tbar`
);
});
it('should log that no stdout was available when stdout and stderr are empty', () => {
actClose(23, 'SIGTERM');
expect(logMock.warn).calledWith(
`Child process [pid ${childProcessMock.pid}] exited unexpectedly with exit code 23 (SIGTERM). Stdout and stderr were empty.`
);
});
it('should log stdout and stderr in correct order', () => {
childProcessMock.stdout.emit('data', 'foo');
childProcessMock.stderr.emit('data', 'baz');
childProcessMock.stdout.emit('data', 'bar');
actClose(23, 'SIGTERM');
expect(logMock.warn).calledWith(
`Child process [pid ${childProcessMock.pid}] exited unexpectedly with exit code 23 (SIGTERM). Last part of stdout and stderr was:${os.EOL}\tbaz${os.EOL}\tfoobar`
);
});
it('should reject any outstanding worker promises with the error', () => {
const expectedError = 'Child process [pid 4648] exited unexpectedly with exit code 646 (SIGINT).';
const actualPromise = sut.proxy.say('test');
actClose(646);
return expect(actualPromise).rejectedWith(expectedError);
});
it('should reject any new calls immediately', () => {
actClose(646);
return expect(sut.proxy.say('')).rejected;
});
function actClose(code = 1, signal = 'SIGINT') {
childProcessMock.emit('close', code, signal);
}
});
describe('when calling methods', () => {
beforeEach(() => {
sut = createSut();
receiveMessage({ kind: ParentMessageKind.Initialized });
});
it('should proxy the message', async () => {
// Arrange
const workerResponse: ParentMessage = {
correlationId: 0,
kind: ParentMessageKind.Result,
result: 'ack',
};
const expectedWorkerMessage: WorkerMessage = {
args: ['echo'],
correlationId: 0,
kind: WorkerMessageKind.Call,
methodName: 'say',
};
// Act
const delayedEcho = sut.proxy.say('echo');
clock.tick(0);
receiveMessage(workerResponse);
const result: string = await delayedEcho;
// Assert
expect(result).eq('ack');
expect(childProcessMock.send).calledWith(serialize(expectedWorkerMessage));
});
});
describe('dispose', () => {
beforeEach(() => {
sut = createSut();
});
it('should send a dispose message', async () => {
await actDispose();
const expectedWorkerMessage: DisposeMessage = { kind: WorkerMessageKind.Dispose };
expect(childProcessMock.send).calledWith(serialize(expectedWorkerMessage));
});
it('should kill the child process', async () => {
await actDispose();
expect(killStub).calledWith(childProcessMock.pid);
});
it('should not do anything if already disposed', async () => {
await actDispose();
await actDispose();
expect(killStub).calledOnce;
expect(childProcessMock.send).calledTwice; // 1 init, 1 dispose
});
it('should not do anything if the process already exited', async () => {
childProcessMock.emit('close', 1);
await actDispose();
expect(killStub).not.called;
expect(childProcessMock.send).calledOnce; // init
});
it('should only wait for max 2 seconds before going ahead and killing the child process anyway', async () => {
const disposePromise = sut.dispose();
clock.tick(2000);
await disposePromise;
expect(killStub).called;
});
it('should remove "close" listener', async () => {
expect(childProcessMock.listenerCount('close')).eq(1);
await actDispose();
expect(childProcessMock.listenerCount('close')).eq(0);
});
async function actDispose() {
const disposePromise = sut.dispose();
receiveMessage({ kind: ParentMessageKind.DisposeCompleted });
await disposePromise;
}
});
function receiveMessage(workerResponse: ParentMessage) {
childProcessMock.emit('message', serialize(workerResponse));
}
});
function createSut(
overrides: {
requirePath?: string;
loggingContext?: LoggingClientContext;
options?: Partial<StrykerOptions>;
workingDir?: string;
name?: string;
execArgv?: string[];
} = {}
): ChildProcessProxy<HelloClass> {
return ChildProcessProxy.create(
overrides.requirePath || 'foobar',
overrides.loggingContext || LOGGING_CONTEXT,
factory.strykerOptions(overrides.options),
{ name: overrides.name || 'someArg' },
overrides.workingDir || 'workingDir',
HelloClass,
overrides.execArgv ?? []
);
}