test(web): consolidate passive CDP event fact proofs (#13093)

This commit is contained in:
morluto authored and GitHub committed 2026-11-21 07:44:03 -05:00
1 parent 750120a4ce
commit 47a108e64e
3 files changed
+128 -224

No files matched your search

@@ -5,9 +5,8 @@ import { inspectWebPageInputSchema } from "../domain/browserObservation.js";
import { webPageInspectionSchema } from "../domain/browserObservationSchemas.js";
import { receiveCdpEvent } from "./CdpConnection.js";
const origin = "http://127.0.0.1:43127";
const captureWithConsoleTimestamp = (timestamp: unknown): CdpCaptureEvents => {
it("preserves finite console timestamps and reports missing or malformed values by event", () => {
const origin = "http://127.0.0.1:43127";
const capture = new CdpCaptureEvents(
inspectWebPageInputSchema.parse({
cdp_endpoint: origin,
@@ -16,56 +15,47 @@ const captureWithConsoleTimestamp = (timestamp: unknown): CdpCaptureEvents => {
}),
new Set([origin]),
);
const params: Record<string, unknown> = {
type: "log",
args: [],
stackTrace: {
callFrames: [{ url: `${origin}/app.js`, lineNumber: 0, columnNumber: 0 }],
},
};
if (timestamp !== undefined) params.timestamp = timestamp;
capture.ingest(
receiveCdpEvent({ method: "Runtime.consoleAPICalled", params }),
);
return capture;
};
it.each([
["an omitted timestamp", undefined],
["a non-finite timestamp", Number.NaN],
["a string timestamp", "123"],
["an explicit null timestamp", null],
])(
"retains %s as unknown and marks console coverage invalid",
(_label, timestamp) => {
const capture = captureWithConsoleTimestamp(timestamp);
const event = capture.console[0];
expect(event?.timestamp).toBeNull();
expect(capture.completeness.snapshot().excluded).toContainEqual({
section: "console_events",
reason: "invalid_protocol_value",
count: 1,
const cases = [
["omitted", {}, null],
["epoch", { timestamp: 0 }, 0],
["non-finite", { timestamp: Number.NaN }, null],
["string", { timestamp: "123" }, null],
["before-epoch", { timestamp: -1 }, -1],
["null", { timestamp: null }, null],
] as const;
let invalidCount = 0;
for (const [index, [label, reported, expected]] of cases.entries()) {
const url = `${origin}/${label}.js`;
capture.ingest(
receiveCdpEvent({
method: "Runtime.consoleAPICalled",
params: {
type: "log",
args: [],
stackTrace: {
callFrames: [{ url, lineNumber: 0, columnNumber: 0 }],
},
...reported,
},
}),
);
expect(capture.console, label).toHaveLength(index + 1);
expect(capture.console[index], label).toMatchObject({
url,
timestamp: expected,
});
expect(
webPageInspectionSchema.shape.console.shape.events.element.safeParse(
event,
).success,
).toBe(true);
},
);
it.each([
["Unix epoch", 0],
["pre-epoch", -1],
])("preserves a finite %s console timestamp", (_label, timestamp) => {
const capture = captureWithConsoleTimestamp(timestamp);
expect(capture.console[0]?.timestamp).toBe(timestamp);
expect(capture.completeness.snapshot().excluded).not.toContainEqual(
expect.objectContaining({
section: "console_events",
reason: "invalid_protocol_value",
}),
);
invalidCount += expected === null ? 1 : 0;
expect(capture.completeness.snapshot().excluded, label).toEqual([
{
section: "console_events",
reason: "invalid_protocol_value",
count: invalidCount,
},
]);
}
expect(
webPageInspectionSchema.shape.console.shape.events.safeParse(
capture.console,
).success,
).toBe(true);
});
@@ -17,17 +17,30 @@ it("starts each domain at its first event or enable acknowledgment, preserving e
}),
new Set(["https://example.test"]),
);
const networkEvent = receiveCdpEvent({
method: "Network.loadingFinished",
params: { requestId: "unobserved", encodedDataLength: 0 },
});
events.ingest(networkEvent);
expect(() => events.coverageStartedAt("Network")).toThrow();
events.beginAuthorizedFrame(new CdpTargetDocument({ frameId: "main" }));
vi.setSystemTime(new Date("2026-10-24T00:00:01.000Z"));
events.ingest(
receiveCdpEvent({
method: "Network.loadingFinished",
params: { requestId: "unobserved", encodedDataLength: 0 },
}),
);
events.ingest(networkEvent);
vi.setSystemTime(new Date("2026-10-24T00:00:02.000Z"));
events.markDomainEnabled("Network");
events.markDomainEnabled("Runtime");
expect(events.coverageStartedAt("Network")).toBe("2026-10-24T00:00:01.000Z");
expect(events.coverageStartedAt("Runtime")).toBe("2026-10-24T00:00:02.000Z");
vi.setSystemTime(new Date("2026-10-24T00:00:03.000Z"));
events.ingest(
receiveCdpEvent({ method: "Runtime.executionContextsCleared", params: {} }),
);
expect(events.coverageStartedAt("Runtime")).toBe("2026-10-24T00:00:02.000Z");
events.beginAuthorizedFrame(new CdpTargetDocument({ frameId: "next" }));
expect(() => events.coverageStartedAt("Runtime")).toThrow();
events.ingest(networkEvent);
expect(events.coverageStartedAt("Network")).toBe("2026-10-24T00:00:03.000Z");
});
@@ -5,183 +5,84 @@ import { webPageInspectionSchema } from "../domain/browserObservationSchemas.js"
import { CdpCaptureEvents } from "./CdpCaptureEvents.js";
import { receiveCdpEvent } from "./CdpConnection.js";
const origin = "https://example.test";
const createEvents = (): CdpCaptureEvents =>
new CdpCaptureEvents(
it("preserves observed WebSocket frames and tracks unknown opcode and payload facts", () => {
const events = new CdpCaptureEvents(
inspectWebPageInputSchema.parse({
cdp_endpoint: "http://127.0.0.1:9222",
allowed_origins: [origin],
allowed_origins: ["https://example.test"],
target_id: "page",
include_websocket_shapes: true,
}),
new Set([origin]),
new Set(["https://example.test"]),
);
const captureFrame = (
opcode: unknown,
payloadData: unknown,
includeOpcode = true,
includePayload = true,
) => {
const events = createEvents();
events.ingest(
receiveCdpEvent({
method: "Network.webSocketCreated",
params: { requestId: "socket", url: "wss://example.test/live" },
}),
);
events.ingest(
receiveCdpEvent({
method: "Network.webSocketFrameReceived",
params: {
requestId: "socket",
response: {
...(includeOpcode ? { opcode } : {}),
...(includePayload ? { payloadData } : {}),
},
},
}),
);
return {
events,
frame: events.webSocketConnectionsById.get("socket")?.events[0],
};
};
it.each([
{
label: "missing",
opcode: undefined,
payload: "",
hasOpcode: false,
hasPayload: true,
},
{
label: "wrong type",
opcode: "1",
payload: "text",
hasOpcode: true,
hasPayload: true,
},
{
label: "explicit null",
opcode: null,
payload: "",
hasOpcode: true,
hasPayload: true,
},
{
label: "negative",
opcode: -1,
payload: "",
hasOpcode: true,
hasPayload: true,
},
{
label: "fractional",
opcode: 1.5,
payload: "text",
hasOpcode: true,
hasPayload: true,
},
{
label: "above opcode width",
opcode: 16,
payload: "",
hasOpcode: true,
hasPayload: true,
},
{
label: "non-finite",
opcode: Number.NaN,
payload: "",
hasOpcode: true,
hasPayload: true,
},
] as const)(
"keeps $label WebSocket opcode unknown",
({ opcode, payload, hasOpcode, hasPayload }) => {
const { events, frame } = captureFrame(
opcode,
payload,
hasOpcode,
hasPayload,
);
expect(frame).toEqual({
direction: "received",
opcode: null,
payload_bytes: null,
payload_shape: null,
});
expect(events.completeness.snapshot().excluded).toContainEqual({
section: "websocket_frames",
reason: "invalid_protocol_value",
count: 1,
});
expect(
webPageInspectionSchema.shape.network.shape.websocket_connections.element.safeParse(
{
request_id: "socket",
url: "wss://example.test/live",
events: [frame],
},
).success,
).toBe(true);
},
);
it.each([
{ label: "continuation", opcode: 0, payload: "", bytes: 0, format: "binary" },
{ label: "empty text", opcode: 1, payload: "", bytes: 0, format: "text" },
{
label: "reserved four-bit opcode",
opcode: 15,
payload: "",
bytes: 0,
format: "binary",
},
] as const)(
"preserves observed $label data",
({ opcode, payload, bytes, format }) => {
const { events, frame } = captureFrame(opcode, payload);
expect(frame).toEqual({
direction: "received",
opcode,
payload_bytes: bytes,
payload_shape: { format, json_shape: null },
});
expect(events.completeness.snapshot().excluded).not.toContainEqual(
expect.objectContaining({
section: "websocket_frames",
reason: "invalid_protocol_value",
const socket = events.webSocketConnectionsById.get("socket");
if (socket === undefined) throw new Error("Expected the approved WebSocket");
// Each row states the retained opcode, size and shape after the raw fields.
const cases = [
["continuation", { opcode: 0, payloadData: "" }, 0, 0, "binary"],
["missing opcode", { payloadData: "" }, null, null, null],
["string opcode", { opcode: "1", payloadData: "x" }, null, null, null],
["null opcode", { opcode: null, payloadData: "" }, null, null, null],
["negative opcode", { opcode: -1, payloadData: "" }, null, null, null],
["fractional opcode", { opcode: 1.5, payloadData: "x" }, null, null, null],
["above four bits", { opcode: 16, payloadData: "" }, null, null, null],
[
"non-finite opcode",
{ opcode: Number.NaN, payloadData: "" },
null,
null,
null,
],
["reserved opcode", { opcode: 15, payloadData: "" }, 15, 0, "binary"],
["missing payload", { opcode: 1 }, 1, null, null],
["numeric payload", { opcode: 1, payloadData: 42 }, 1, null, null],
["invalid base64", { opcode: 2, payloadData: "AA" }, 2, null, "binary"],
["empty text", { opcode: 1, payloadData: "" }, 1, 0, "text", "sent"],
["UTF-8 text", { opcode: 1, payloadData: "é" }, 1, 2, "text", "sent"],
] as const;
let invalidCount = 0;
for (const [
index,
[label, response, opcode, bytes, format, direction = "received"],
] of cases.entries()) {
events.ingest(
receiveCdpEvent({
method:
direction === "received"
? "Network.webSocketFrameReceived"
: "Network.webSocketFrameSent",
params: { requestId: "socket", response },
}),
);
},
);
it.each([
{
label: "missing payload",
opcode: 1,
payload: undefined,
hasPayload: false,
},
{ label: "wrong-type payload", opcode: 1, payload: 42, hasPayload: true },
] as const)(
"does not fabricate an empty payload for $label",
({ opcode, payload, hasPayload }) => {
const { events, frame } = captureFrame(opcode, payload, true, hasPayload);
expect(frame).toEqual({
direction: "received",
expect(socket.events, label).toHaveLength(index + 1);
expect(socket.events[index], label).toEqual({
direction,
opcode,
payload_bytes: null,
payload_shape: null,
payload_bytes: bytes,
payload_shape: format === null ? null : { format, json_shape: null },
});
expect(events.completeness.snapshot().excluded).toContainEqual({
section: "websocket_frames",
reason: "invalid_protocol_value",
count: 1,
});
},
);
invalidCount += bytes === null ? 1 : 0;
expect(events.completeness.snapshot().excluded, label).toEqual(
invalidCount === 0
? []
: [
{
section: "websocket_frames",
reason: "invalid_protocol_value",
count: invalidCount,
},
],
);
}
expect(
webPageInspectionSchema.shape.network.shape.websocket_connections.element.safeParse(
socket,
).success,
).toBe(true);
});