import { describe, expect, it } from "bun:test"; import { decodePayload, encodeResponse } from "../../../../../src/server/checker/runner/udp/encoding"; describe("decodePayload", () => { it("text: 解码 ASCII 字符串", () => { const bytes = decodePayload("PING", "text"); expect(bytes).toEqual(new Uint8Array([0x50, 0x49, 0x4e, 0x47])); }); it("hex: 解码十六进制字符串", () => { const bytes = decodePayload("50494e47", "hex"); expect(bytes).toEqual(new Uint8Array([0x50, 0x49, 0x4e, 0x47])); }); it("base64: 解码 Base64 字符串", () => { const bytes = decodePayload("UElORw==", "base64"); expect(bytes).toEqual(new Uint8Array([0x50, 0x49, 0x4e, 0x47])); }); it("text: 空字符串返回空 Uint8Array", () => { const bytes = decodePayload("", "text"); expect(bytes).toEqual(new Uint8Array(0)); }); it("hex: 空字符串返回空 Uint8Array", () => { const bytes = decodePayload("", "hex"); expect(bytes).toEqual(new Uint8Array(0)); }); it("base64: 空字符串返回空 Uint8Array", () => { const bytes = decodePayload("", "base64"); expect(bytes).toEqual(new Uint8Array(0)); }); it("text: 多字节 UTF-8 字符", () => { const bytes = decodePayload("你好", "text"); expect(encodeResponse(bytes, "text")).toBe("你好"); }); it("hex: 奇数长度字符串抛出错误", () => { expect(() => decodePayload("abc", "hex")).toThrow(); }); }); describe("encodeResponse", () => { it("text: 编码为 UTF-8 字符串", () => { const bytes = new Uint8Array([0x50, 0x49, 0x4e, 0x47]); expect(encodeResponse(bytes, "text")).toBe("PING"); }); it("hex: 编码为小写十六进制字符串", () => { const bytes = new Uint8Array([0x50, 0x49, 0x4e, 0x47]); expect(encodeResponse(bytes, "hex")).toBe("50494e47"); }); it("base64: 编码为 Base64 字符串", () => { const bytes = new Uint8Array([0x50, 0x49, 0x4e, 0x47]); expect(encodeResponse(bytes, "base64")).toBe("UElORw=="); }); }); describe("roundtrip", () => { it("hex: [0x00, 0xff, 0x0a] 往返一致", () => { const original = new Uint8Array([0x00, 0xff, 0x0a]); const hex = encodeResponse(original, "hex"); expect(hex).toBe("00ff0a"); expect(decodePayload(hex, "hex")).toEqual(original); }); it("base64: 任意字节往返一致", () => { const original = new Uint8Array([0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]); const b64 = encodeResponse(original, "base64"); expect(decodePayload(b64, "base64")).toEqual(original); }); });