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