localRuntimeNetworkCapture.test.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { Emitter } from "@zcode/rpc";
  2. import { expect, it, vi } from "vitest";
  3. import { LocalRuntimeNetworkCapture } from "../src/zcode-agent/localRuntimeNetworkCapture.js";
  4. import type { ZCodeProtocolClient } from "../src/zcode-agent/zcodeProtocolClient.js";
  5. import type { ZCodeProtocolNotification } from "@zcode/shared";
  6. it("已有和新本地 CLI 继承启停,旧批次隔离,不注册的 remote 不控制", () => {
  7. const registry = new LocalRuntimeNetworkCapture();
  8. const makeClient = () => {
  9. const events = new Emitter<ZCodeProtocolNotification>();
  10. const notify = vi.fn(async () => {});
  11. return {
  12. events,
  13. notify,
  14. client: {
  15. onNotification: events.event,
  16. notify,
  17. isDisposed: false,
  18. } as unknown as ZCodeProtocolClient,
  19. };
  20. };
  21. const a = makeClient(),
  22. b = makeClient(),
  23. remote = makeClient();
  24. const remove = registry.register(a.client, 41);
  25. expect(a.notify).not.toHaveBeenCalled();
  26. const sink = vi.fn();
  27. registry.setCaptureId("one", sink);
  28. registry.register(b.client, 42);
  29. expect(a.notify).toHaveBeenCalledWith("process/networkCapture", { captureId: "one" });
  30. expect(b.notify).toHaveBeenCalledWith("process/networkCapture", { captureId: "one" });
  31. expect(remote.notify).not.toHaveBeenCalled();
  32. const batch = {
  33. captureId: "one",
  34. dropped: 0,
  35. records: [
  36. { timestamp: 1, pid: 999, processType: "main", method: "GET", url: "https://example.test/" },
  37. ],
  38. };
  39. a.events.fire({ method: "process/networkRequests", params: batch });
  40. expect(sink.mock.lastCall![0].records[0]).toMatchObject({ pid: 41, processType: "cli" });
  41. registry.setCaptureId(null);
  42. expect(a.notify).toHaveBeenLastCalledWith("process/networkCapture", { captureId: null });
  43. registry.setCaptureId("two", sink);
  44. a.events.fire({ method: "process/networkRequests", params: batch });
  45. expect(sink).toHaveBeenCalledTimes(1);
  46. remove();
  47. a.events.fire({ method: "process/networkRequests", params: { ...batch, captureId: "two" } });
  48. expect(sink).toHaveBeenCalledTimes(1);
  49. registry.setCaptureId(null);
  50. });