From 8be0c8b43a56ee690463efb3e68686f0fefa868b Mon Sep 17 00:00:00 2001 From: David DeSimone Date: Mon, 22 Feb 2021 04:26:17 -0800 Subject: [PATCH] fix(tests): fix fetchConnectionError test if port is in use (#9465) Fixes #9379 --- cli/tests/unit/fetch_test.ts | 28 +++++++++++++++++++++++++++- cli/tests/unit/test_util.ts | 1 + 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/cli/tests/unit/fetch_test.ts b/cli/tests/unit/fetch_test.ts index 9776baa2fb..71307cd69d 100644 --- a/cli/tests/unit/fetch_test.ts +++ b/cli/tests/unit/fetch_test.ts @@ -5,6 +5,7 @@ import { assertThrows, assertThrowsAsync, fail, + unimplemented, unitTest, } from "./test_util.ts"; @@ -20,12 +21,37 @@ unitTest({ perms: { net: true } }, async function fetchProtocolError(): Promise< ); }); +function findClosedPortInRange( + minPort: number, + maxPort: number, +): number | never { + let port = minPort; + + // If we hit the return statement of this loop + // that means that we did not throw an + // AddrInUse error when we executed Deno.listen. + while (port < maxPort) { + try { + const listener = Deno.listen({ port }); + listener.close(); + return port; + } catch (e) { + port++; + } + } + + unimplemented( + `No available ports between ${minPort} and ${maxPort} to test fetch`, + ); +} + unitTest( { perms: { net: true } }, async function fetchConnectionError(): Promise { + const port = findClosedPortInRange(4000, 9999); await assertThrowsAsync( async (): Promise => { - await fetch("http://localhost:4000"); + await fetch(`http://localhost:${port}`); }, TypeError, "error trying to connect", diff --git a/cli/tests/unit/test_util.ts b/cli/tests/unit/test_util.ts index 6c3c0c6a06..e6adc6583c 100644 --- a/cli/tests/unit/test_util.ts +++ b/cli/tests/unit/test_util.ts @@ -17,6 +17,7 @@ export { assertThrows, assertThrowsAsync, fail, + unimplemented, unreachable, } from "../../../test_util/std/testing/asserts.ts"; export { deferred } from "../../../test_util/std/async/deferred.ts";