Initial Commit
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
// Universal test fixture: a tiny node:http server. Tests are
|
||||
// run-only (not shipped); importing node:http here is permitted in the
|
||||
// `tests/` directory which is excluded from tier-purity checks in
|
||||
// `src/`. The src tree stays universal.
|
||||
import {
|
||||
createServer,
|
||||
type IncomingMessage,
|
||||
type Server,
|
||||
type ServerResponse,
|
||||
} from "node:http";
|
||||
|
||||
export type RouteHandler = (
|
||||
req: IncomingMessage,
|
||||
res: ServerResponse
|
||||
) => void | Promise<void>;
|
||||
|
||||
export interface FixtureServer {
|
||||
readonly url: string;
|
||||
readonly port: number;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stand up a localhost `node:http` server with the given route handler.
|
||||
* The returned `url` ends with `/` so it can be used as a `rootUrl`.
|
||||
*/
|
||||
export async function startFixtureServer(
|
||||
handler: RouteHandler
|
||||
): Promise<FixtureServer> {
|
||||
const server: Server = createServer((req, res) => {
|
||||
try {
|
||||
const out = handler(req, res);
|
||||
if (out !== undefined) {
|
||||
void Promise.resolve(out).catch((err) => {
|
||||
res.statusCode = 500;
|
||||
res.end(String(err));
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
res.statusCode = 500;
|
||||
res.end(String(err));
|
||||
}
|
||||
});
|
||||
await new Promise<void>((resolve) =>
|
||||
server.listen(0, "127.0.0.1", () => resolve())
|
||||
);
|
||||
const addr = server.address();
|
||||
if (addr === null || typeof addr === "string") {
|
||||
throw new Error("fixture server did not bind to a TCP port");
|
||||
}
|
||||
const port = addr.port;
|
||||
return {
|
||||
url: `http://127.0.0.1:${port}/`,
|
||||
port,
|
||||
close: () =>
|
||||
new Promise<void>((resolve, reject) =>
|
||||
server.close((err) => (err ? reject(err) : resolve()))
|
||||
),
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user