Files
UHD_Media_Tool/apps/server/test/system/bun-runtime.test.ts
T

66 lines
2.2 KiB
TypeScript

import { serve, upgradeWebSocket } from "@umt/runtime";
import { Hono } from "hono";
import { expect, it } from "vitest";
it("Bun HTTP 适配通过 Hono 中间件升级 WebSocket,保留协议、文本与二进制消息", async () => {
const app = new Hono();
app.use("*", async (c, next) => {
await next();
c.header("x-test", "middleware");
});
app.get("/ws", (c) => {
const { socket, response } = upgradeWebSocket(c.req.raw, { protocol: "umt-test" });
socket.onmessage = (event) => socket.send(event.data);
return response;
});
const server = serve({ hostname: "127.0.0.1", port: 0 }, app.fetch);
const client = new WebSocket(`ws://127.0.0.1:${server.addr.port}/ws`, ["umt-test"]);
client.binaryType = "arraybuffer";
try {
await new Promise<void>((resolve, reject) => {
client.onopen = () => resolve();
client.onerror = () => reject(new Error("upgrade failed"));
});
expect(client.protocol).toBe("umt-test");
const echo = (data: string | ArrayBuffer) =>
new Promise<unknown>((resolve) => {
client.onmessage = (event) => resolve(event.data);
client.send(data);
});
expect(await echo("hello")).toBe("hello");
expect(new Uint8Array((await echo(new Uint8Array([1, 2, 3]).buffer)) as ArrayBuffer)).toEqual(
new Uint8Array([1, 2, 3]),
);
} finally {
client.close();
await server.shutdown();
}
});
it("Bun WebSocket 上游连接发送自定义认证头", async () => {
let authorization: string | null = null;
const server = Bun.serve({
hostname: "127.0.0.1",
port: 0,
fetch(req, server) {
authorization = req.headers.get("authorization");
if (server.upgrade(req)) return undefined;
return new Response(null, { status: 400 });
},
websocket: { message() {} },
});
const client = new WebSocket(`ws://127.0.0.1:${server.port}`, {
headers: { authorization: "Basic test" },
} as unknown as string[]);
try {
await new Promise<void>((resolve, reject) => {
client.onopen = () => resolve();
client.onerror = () => reject(new Error("connect failed"));
});
expect(authorization).toBe("Basic test");
} finally {
client.close();
await server.stop(true);
}
});