2024-01-01 21:11:32 +00:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2023-12-04 04:50:40 +00:00
|
|
|
|
|
|
|
import { getAvailablePort } from "./get_available_port.ts";
|
2024-05-12 22:17:22 +00:00
|
|
|
import { assertEquals, assertNotEquals, assertThrows } from "@std/assert";
|
|
|
|
import { stub } from "@std/testing/mock";
|
2023-12-04 04:50:40 +00:00
|
|
|
|
2024-01-11 06:12:47 +00:00
|
|
|
/** Helper function to see if a port is indeed available for listening (race-y) */
|
|
|
|
async function testWithPort(port: number) {
|
2023-12-04 04:50:40 +00:00
|
|
|
const server = Deno.serve({
|
|
|
|
port,
|
|
|
|
async onListen() {
|
|
|
|
const resp = await fetch(`http://localhost:${port}`);
|
|
|
|
const text = await resp.text();
|
|
|
|
assertEquals(text, "hello");
|
|
|
|
server.shutdown();
|
|
|
|
},
|
|
|
|
}, () => new Response("hello"));
|
|
|
|
|
|
|
|
await server.finished;
|
2024-01-11 06:12:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
Deno.test("getAvailablePort() gets an available port", async () => {
|
|
|
|
const port = getAvailablePort();
|
2024-05-12 22:17:22 +00:00
|
|
|
assertEquals(typeof port, "number");
|
2024-01-11 06:12:47 +00:00
|
|
|
await testWithPort(port);
|
|
|
|
});
|
|
|
|
|
|
|
|
Deno.test("getAvailablePort() gets an available port with a preferred port", async () => {
|
2024-05-12 22:17:22 +00:00
|
|
|
const preferredPort = 9563;
|
|
|
|
const port = getAvailablePort({ preferredPort });
|
|
|
|
assertEquals(port, preferredPort);
|
2024-01-11 06:12:47 +00:00
|
|
|
await testWithPort(port);
|
2023-12-04 04:50:40 +00:00
|
|
|
});
|
2024-05-12 22:17:22 +00:00
|
|
|
|
|
|
|
Deno.test("getAvailablePort() falls back to another port if preferred port is in use", async () => {
|
|
|
|
const preferredPort = 9563;
|
|
|
|
const server = Deno.serve(
|
|
|
|
{ port: preferredPort, onListen: () => {} },
|
|
|
|
() => new Response("hello"),
|
|
|
|
);
|
|
|
|
const port = getAvailablePort({ preferredPort });
|
|
|
|
assertEquals(typeof port, "number");
|
|
|
|
assertNotEquals(port, preferredPort);
|
|
|
|
server.shutdown();
|
|
|
|
await server.finished;
|
|
|
|
});
|
|
|
|
|
|
|
|
Deno.test("getAvailablePort() throws if error is not AddrInUse", () => {
|
|
|
|
using _ = stub(Deno, "listen", () => {
|
|
|
|
throw new Error();
|
|
|
|
});
|
|
|
|
const preferredPort = 9563;
|
|
|
|
assertThrows(() => getAvailablePort({ preferredPort }), Error);
|
|
|
|
});
|