|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +// Tests that calling rl.close() while a question() promise is pending rejects |
| 4 | +// the promise with AbortError instead of leaving it permanently unresolved. |
| 5 | + |
| 6 | +const common = require('../common'); |
| 7 | +const assert = require('node:assert'); |
| 8 | +const readline = require('node:readline/promises'); |
| 9 | +const { Readable } = require('node:stream'); |
| 10 | +const { EventEmitter } = require('node:events'); |
| 11 | +const { Writable } = require('node:stream'); |
| 12 | + |
| 13 | +class FakeInput extends EventEmitter { |
| 14 | + resume() {} |
| 15 | + pause() {} |
| 16 | + write() {} |
| 17 | + end() {} |
| 18 | +} |
| 19 | + |
| 20 | +// Programmatic close() rejects the pending question |
| 21 | +{ |
| 22 | + const input = new Readable({ read() {} }); |
| 23 | + const rl = readline.createInterface({ input, terminal: false }); |
| 24 | + assert.rejects(rl.question('prompt: '), { name: 'AbortError' }).then(common.mustCall()); |
| 25 | + rl.close(); |
| 26 | +} |
| 27 | + |
| 28 | +// close() rejects only once when called multiple times |
| 29 | +{ |
| 30 | + const input = new Readable({ read() {} }); |
| 31 | + const rl = readline.createInterface({ input, terminal: false }); |
| 32 | + assert.rejects(rl.question('prompt: '), { name: 'AbortError' }).then(common.mustCall()); |
| 33 | + rl.close(); |
| 34 | + rl.close(); // second close() should be a no-op |
| 35 | +} |
| 36 | + |
| 37 | +// close() does not throw if there is no pending question |
| 38 | +{ |
| 39 | + const input = new Readable({ read() {} }); |
| 40 | + const rl = readline.createInterface({ input, terminal: false }); |
| 41 | + assert.doesNotThrow(() => rl.close()); |
| 42 | +} |
| 43 | + |
| 44 | +// Terminal interface: close() rejects a pending question |
| 45 | +{ |
| 46 | + const fi = new FakeInput(); |
| 47 | + const output = new Writable({ write(chunk, enc, cb) { cb(); } }); |
| 48 | + const rl = readline.createInterface({ terminal: true, input: fi, output }); |
| 49 | + assert.rejects(rl.question('prompt: '), { name: 'AbortError' }).then(common.mustCall()); |
| 50 | + rl.close(); |
| 51 | +} |
| 52 | + |
| 53 | +// Answering before close() resolves normally; subsequent close() is no-op |
| 54 | +{ |
| 55 | + const fi = new FakeInput(); |
| 56 | + const output = new Writable({ write(chunk, enc, cb) { cb(); } }); |
| 57 | + const rl = readline.createInterface({ terminal: true, input: fi, output }); |
| 58 | + rl.question('prompt: ').then(common.mustCall((answer) => { |
| 59 | + assert.strictEqual(answer, 'hello'); |
| 60 | + })); |
| 61 | + fi.emit('data', 'hello\n'); |
| 62 | + // close() with no pending question should not throw |
| 63 | + setImmediate(common.mustCall(() => rl.close())); |
| 64 | +} |
0 commit comments