1'use strict';
2
3// Flags: --expose-internals
4
5const common = require('../common');
6const stream = require('stream');
7const repl = require('internal/repl');
8const assert = require('assert');
9
10// Array of [useGlobal, expectedResult] pairs
11const globalTestCases = [
12  [false, 'undefined'],
13  [true, '\'tacos\''],
14  [undefined, 'undefined'],
15];
16
17const globalTest = (useGlobal, cb, output) => (err, repl) => {
18  if (err)
19    return cb(err);
20
21  let str = '';
22  output.on('data', (data) => (str += data));
23  global.lunch = 'tacos';
24  repl.write('global.lunch;\n');
25  repl.close();
26  delete global.lunch;
27  cb(null, str.trim());
28};
29
30// Test how the global object behaves in each state for useGlobal
31for (const [option, expected] of globalTestCases) {
32  runRepl(option, globalTest, common.mustSucceed((output) => {
33    assert.strictEqual(output, expected);
34  }));
35}
36
37// Test how shadowing the process object via `let`
38// behaves in each useGlobal state. Note: we can't
39// actually test the state when useGlobal is true,
40// because the exception that's generated is caught
41// (see below), but errors are printed, and the test
42// suite is aware of it, causing a failure to be flagged.
43//
44const processTestCases = [false, undefined];
45const processTest = (useGlobal, cb, output) => (err, repl) => {
46  if (err)
47    return cb(err);
48
49  let str = '';
50  output.on('data', (data) => (str += data));
51
52  // If useGlobal is false, then `let process` should work
53  repl.write('let process;\n');
54  repl.write('21 * 2;\n');
55  repl.close();
56  cb(null, str.trim());
57};
58
59for (const option of processTestCases) {
60  runRepl(option, processTest, common.mustSucceed((output) => {
61    assert.strictEqual(output, 'undefined\n42');
62  }));
63}
64
65function runRepl(useGlobal, testFunc, cb) {
66  const inputStream = new stream.PassThrough();
67  const outputStream = new stream.PassThrough();
68  const opts = {
69    input: inputStream,
70    output: outputStream,
71    useGlobal: useGlobal,
72    useColors: false,
73    terminal: false,
74    prompt: ''
75  };
76
77  repl.createInternalRepl(
78    process.env,
79    opts,
80    testFunc(useGlobal, cb, opts.output));
81}
82