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.mustCall((err, output) => { 33 assert.ifError(err); 34 assert.strictEqual(output, expected); 35 })); 36} 37 38// Test how shadowing the process object via `let` 39// behaves in each useGlobal state. Note: we can't 40// actually test the state when useGlobal is true, 41// because the exception that's generated is caught 42// (see below), but errors are printed, and the test 43// suite is aware of it, causing a failure to be flagged. 44// 45const processTestCases = [false, undefined]; 46const processTest = (useGlobal, cb, output) => (err, repl) => { 47 if (err) 48 return cb(err); 49 50 let str = ''; 51 output.on('data', (data) => (str += data)); 52 53 // If useGlobal is false, then `let process` should work 54 repl.write('let process;\n'); 55 repl.write('21 * 2;\n'); 56 repl.close(); 57 cb(null, str.trim()); 58}; 59 60for (const option of processTestCases) { 61 runRepl(option, processTest, common.mustCall((err, output) => { 62 assert.ifError(err); 63 assert.strictEqual(output, 'undefined\n42'); 64 })); 65} 66 67function runRepl(useGlobal, testFunc, cb) { 68 const inputStream = new stream.PassThrough(); 69 const outputStream = new stream.PassThrough(); 70 const opts = { 71 input: inputStream, 72 output: outputStream, 73 useGlobal: useGlobal, 74 useColors: false, 75 terminal: false, 76 prompt: '' 77 }; 78 79 repl.createInternalRepl( 80 process.env, 81 opts, 82 testFunc(useGlobal, cb, opts.output)); 83} 84