index.test.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. const tap = require('tap');
  2. const test = tap.test;
  3. const readFile = require('fs').readFileSync;
  4. const spawn = require('child_process').spawn;
  5. const pstree = require('../');
  6. const { tree, pidsForTree, getStat } = require('../lib/utils');
  7. if (process.platform !== 'darwin') {
  8. test('reads from /proc', async (t) => {
  9. const ps = await getStat();
  10. t.ok(ps.split('\n').length > 1);
  11. });
  12. }
  13. test('tree for live env', async (t) => {
  14. const pid = 4079;
  15. const fixture = readFile(__dirname + '/fixtures/out2', 'utf8');
  16. const ps = await tree(fixture);
  17. t.deepEqual(
  18. pidsForTree(ps, pid).map((_) => _.PID),
  19. ['4080']
  20. );
  21. });
  22. function testTree(t, runCallCount) {
  23. const sub = spawn('node', [`${__dirname}/fixtures/index.js`, runCallCount], {
  24. stdio: 'pipe',
  25. });
  26. setTimeout(() => {
  27. const pid = sub.pid;
  28. pstree(pid, (error, pids) => {
  29. pids.concat([pid]).forEach((p) => {
  30. spawn('kill', ['-s', 'SIGTERM', p]);
  31. });
  32. // the fixture launches `sh` which launches node which is why we
  33. // are looking for two processes.
  34. // Important: IDKW but MacOS seems to skip the `sh` process. no idea.
  35. t.equal(pids.length, runCallCount * 2);
  36. t.end();
  37. });
  38. }, 1000);
  39. }
  40. test('can read full process tree', (t) => {
  41. testTree(t, 1);
  42. });
  43. test('can read full process tree with multiple processes', (t) => {
  44. testTree(t, 2);
  45. });