File: child.js

package info (click to toggle)
node-yarnpkg 1.13.0-1%2Bdeb10u1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 93,036 kB
  • sloc: sh: 323; makefile: 19
file content (74 lines) | stat: -rw-r--r-- 1,836 bytes parent folder | download | duplicates (3)
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
/* @flow */
import {spawn, forwardSignalToSpawnedProcesses} from '../../src/util/child.js';

let mockSpawnedChildren = [];

jest.mock('child_process', () => {
  class MockedChildProcess {
    stdout: Object;
    stderr: Object;
    receivedSignal: string;
    exitWithCode: number => void;

    constructor() {
      this.stdout = {
        on: () => {},
      };
      this.stderr = {
        on: () => {},
      };
    }

    kill(signal) {
      this.receivedSignal = signal;
    }

    on(event, handler) {
      if (event === 'close') {
        this.exitWithCode = handler;
      }
    }
  }

  const realChildProcess = (require: any).requireActual('child_process');

  realChildProcess.spawn = cmd => {
    const newChild = new MockedChildProcess();
    mockSpawnedChildren.push(newChild);
    return newChild;
  };

  return realChildProcess;
});

const expectChildReceivedSignal = (child, signal) => {
  expect(child.receivedSignal).toEqual(signal);
};

beforeEach(() => {
  mockSpawnedChildren = [];
});

it('should forward signals to all spawned child processes', () => {
  spawn('foo', []).then(() => {}, () => {});
  spawn('bar', []).then(() => {}, () => {});

  expect(mockSpawnedChildren.length).toEqual(2);

  forwardSignalToSpawnedProcesses('SIGTERM');

  expectChildReceivedSignal(mockSpawnedChildren[0], 'SIGTERM');
  expectChildReceivedSignal(mockSpawnedChildren[1], 'SIGTERM');
});

it('should not attempt to forward signals to children that already terminated', () => {
  spawn('foo', []).then(() => {}, () => {});
  spawn('bar', []).then(() => {}, () => {});

  const fooProcess = mockSpawnedChildren[0];
  fooProcess.exitWithCode(0);
  forwardSignalToSpawnedProcesses('SIGTERM');

  expectChildReceivedSignal(mockSpawnedChildren[0], undefined);
  expectChildReceivedSignal(mockSpawnedChildren[1], 'SIGTERM');
});