summaryrefslogtreecommitdiff
path: root/test/parallel/test-repl-use-global.js
blob: 00222608deca6f6ee1bd360b922dab2642b61ae1 (plain)
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
'use strict';

// Flags: --expose-internals

const common = require('../common');
const stream = require('stream');
const repl = require('internal/repl');
const assert = require('assert');

// Array of [useGlobal, expectedResult] pairs
const globalTestCases = [
  [false, 'undefined'],
  [true, '\'tacos\''],
  [undefined, 'undefined']
];

const globalTest = (useGlobal, cb, output) => (err, repl) => {
  if (err)
    return cb(err);

  let str = '';
  output.on('data', (data) => (str += data));
  global.lunch = 'tacos';
  repl.write('global.lunch;\n');
  repl.close();
  delete global.lunch;
  cb(null, str.trim());
};

// Test how the global object behaves in each state for useGlobal
for (const [option, expected] of globalTestCases) {
  runRepl(option, globalTest, common.mustCall((err, output) => {
    assert.ifError(err);
    assert.strictEqual(output, expected);
  }));
}

// Test how shadowing the process object via `let`
// behaves in each useGlobal state. Note: we can't
// actually test the state when useGlobal is true,
// because the exception that's generated is caught
// (see below), but errors are printed, and the test
// suite is aware of it, causing a failure to be flagged.
//
const processTestCases = [false, undefined];
const processTest = (useGlobal, cb, output) => (err, repl) => {
  if (err)
    return cb(err);

  let str = '';
  output.on('data', (data) => (str += data));

  // If useGlobal is false, then `let process` should work
  repl.write('let process;\n');
  repl.write('21 * 2;\n');
  repl.close();
  cb(null, str.trim());
};

for (const option of processTestCases) {
  runRepl(option, processTest, common.mustCall((err, output) => {
    assert.ifError(err);
    assert.strictEqual(output, 'undefined\n42');
  }));
}

function runRepl(useGlobal, testFunc, cb) {
  const inputStream = new stream.PassThrough();
  const outputStream = new stream.PassThrough();
  const opts = {
    input: inputStream,
    output: outputStream,
    useGlobal: useGlobal,
    useColors: false,
    terminal: false,
    prompt: ''
  };

  repl.createInternalRepl(
    process.env,
    opts,
    testFunc(useGlobal, cb, opts.output));
}