基于 Bun connected UDP socket 实现通用 UDP 拨测能力: - 支持 text/hex/base64 payload 编码与独立 responseEncoding 响应视图 - 支持 responded、response、responseSize、sourceHost、sourcePort、maxDurationMs 专属 expect - 单 datagram 发送,仅断言首个 UDP 响应 datagram - 通过 maxResponseBytes 和 flags.truncated 进行响应大小限制与截断保护 - payload 可选,省略时发送空 datagram - 自包含模块结构(types/schema/validate/expect/encoding/execute) - 新增 741 tests(含 unit、execute 集成、expect 和编码 roundtrip),全部通过
77 lines
2.5 KiB
TypeScript
77 lines
2.5 KiB
TypeScript
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);
|
|
});
|
|
});
|