42 lines
1.4 KiB
JavaScript
42 lines
1.4 KiB
JavaScript
import test from "node:test";
|
|
import assert from "node:assert/strict";
|
|
import { createServer } from "node:http";
|
|
|
|
import { fetchWithTimeout } from "./fetch-timeout.mjs";
|
|
|
|
async function withServer(handler, run) {
|
|
const server = createServer(handler);
|
|
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
|
const address = server.address();
|
|
const baseUrl = `http://127.0.0.1:${address.port}`;
|
|
try {
|
|
return await run(baseUrl);
|
|
} finally {
|
|
await new Promise((resolve) => server.close(resolve));
|
|
}
|
|
}
|
|
|
|
test("fetchWithTimeout aborts stalled requests with a stable error message", async () => {
|
|
await withServer(() => {
|
|
// Keep the request open to simulate a stalled control-plane request.
|
|
}, async (baseUrl) => {
|
|
const started = Date.now();
|
|
await assert.rejects(
|
|
() => fetchWithTimeout(`${baseUrl}/stall`, {}, { timeoutMs: 20, timeoutMessage: "TEST_FETCH_TIMEOUT" }),
|
|
/TEST_FETCH_TIMEOUT/,
|
|
);
|
|
assert.ok(Date.now() - started < 1_000);
|
|
});
|
|
});
|
|
|
|
test("fetchWithTimeout returns normal responses before the timeout", async () => {
|
|
await withServer((_request, response) => {
|
|
response.writeHead(200, { "Content-Type": "text/plain" });
|
|
response.end("ok");
|
|
}, async (baseUrl) => {
|
|
const response = await fetchWithTimeout(`${baseUrl}/ok`, {}, { timeoutMs: 1_000 });
|
|
assert.equal(response.ok, true);
|
|
assert.equal(await response.text(), "ok");
|
|
});
|
|
});
|