From 1fb0e70ab8c8ea5aa753b84a8805fec7d6aaabd2 Mon Sep 17 00:00:00 2001 From: Jonah Snider Date: Thu, 24 Feb 2022 07:31:15 -0800 Subject: [PATCH] Fix `portNumbers` argument validation and number generation (#64) --- index.js | 6 +++--- test.js | 26 +++++++++++--------------- 2 files changed, 14 insertions(+), 18 deletions(-) diff --git a/index.js b/index.js index 9ee3cd8..06e993a 100644 --- a/index.js +++ b/index.js @@ -160,11 +160,11 @@ export function portNumbers(from, to) { throw new RangeError(`'from' must be between ${minPort} and ${maxPort}`); } - if (to < minPort || to > maxPort + 1) { - throw new RangeError(`'to' must be between ${minPort} and ${maxPort + 1}`); + if (to < minPort || to > maxPort) { + throw new RangeError(`'to' must be between ${minPort} and ${maxPort}`); } - if (to < from) { + if (from > to) { throw new RangeError('`to` must be greater than or equal to `from`'); } diff --git a/test.js b/test.js index 6226f73..9ff8b63 100644 --- a/test.js +++ b/test.js @@ -116,24 +116,20 @@ test('non-array iterables work', async t => { t.is(port, 9920); }); -test('makeRange throws on invalid ranges', t => { - t.throws(() => { - portNumbers(1025, 1024); - }); +test('portNumbers throws on invalid ranges', t => { + t.throws(() => portNumbers('abc', 3000), {instanceOf: TypeError}, '`from` is not an integer number'); + t.throws(() => portNumbers(3000, 'abc'), {instanceOf: TypeError}, '`to` is not an integer number'); - // Invalid port values - t.throws(() => { - portNumbers(0, 0); - }); - t.throws(() => { - portNumbers(1023, 1023); - }); - t.throws(() => { - portNumbers(65_536, 65_536); - }); + t.throws(() => portNumbers(1023, 1024), {instanceOf: RangeError}, '`from` is less than the minimum port'); + t.throws(() => portNumbers(65_536, 65_536), {instanceOf: RangeError}, '`from` is greater than the maximum port'); + + t.throws(() => portNumbers(1024, 1023), {instanceOf: RangeError}, '`to` is less than the minimum port'); + t.throws(() => portNumbers(65_535, 65_537), {instanceOf: RangeError}, '`to` is greater than the maximum port'); + + t.throws(() => portNumbers(1025, 1024), {instanceOf: RangeError}, '`from` is less than `to`'); }); -test('makeRange produces valid ranges', t => { +test('portNumbers produces valid ranges', t => { t.deepEqual([...portNumbers(1024, 1024)], [1024]); t.deepEqual([...portNumbers(1024, 1025)], [1024, 1025]); t.deepEqual([...portNumbers(1024, 1027)], [1024, 1025, 1026, 1027]);