mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-11-30 20:14:01 +01:00
POC: Explore request assertions and CLI testing
This commit is contained in:
1 parent
263a215f7a
commit
c71256d800
65 files changed
+4187
-1983
No files matched your search
@@ -0,0 +1,40 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import { commandSupport, runCommand } from "./commands";
|
||||
import type { WorkerConnection } from "./connection";
|
||||
import { sendHttpRequest } from "./send";
|
||||
|
||||
vi.mock("./send", () => ({ sendHttpRequest: vi.fn() }));
|
||||
afterEach(() => vi.clearAllMocks());
|
||||
|
||||
describe("browser assertion commands", () => {
|
||||
it.each([
|
||||
["cmd_validate_http_assertions", { assertions: { version: 1, checks: [] } }],
|
||||
[
|
||||
"cmd_preview_http_assertions",
|
||||
{ responseId: "rs_pinned_history", assertions: { version: 1, checks: [] } },
|
||||
],
|
||||
["cmd_http_response_json_children", { responseId: "rs_pinned_history", parent: "$.user" }],
|
||||
])("routes %s to the local worker without a send or model write", async (command, payload) => {
|
||||
const report = { from: "local worker" };
|
||||
const rpc = vi.fn().mockResolvedValue(report);
|
||||
const db = { rpc } as unknown as WorkerConnection;
|
||||
expect(commandSupport().implemented).toContain(command);
|
||||
expect(await runCommand(command, payload, db)).toBe(report);
|
||||
expect(rpc).toHaveBeenCalledExactlyOnceWith(command, payload);
|
||||
expect(sendHttpRequest).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not resend when a saved response is no longer available", async () => {
|
||||
const rpc = vi.fn().mockRejectedValue(new Error("Response not found"));
|
||||
const db = { rpc } as unknown as WorkerConnection;
|
||||
await expect(
|
||||
runCommand(
|
||||
"cmd_preview_http_assertions",
|
||||
{ responseId: "rs_removed", assertions: { version: 1, checks: [] } },
|
||||
db,
|
||||
),
|
||||
).rejects.toThrow("Response not found");
|
||||
expect(rpc).toHaveBeenCalledTimes(1);
|
||||
expect(sendHttpRequest).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -68,6 +68,10 @@ const HANDLERS: Partial<Record<AppCmd, Handler>> = {
|
||||
cmd_get_workspace_meta: (payload, db) => db.rpc("cmd_get_workspace_meta", payload),
|
||||
cmd_delete_all_http_responses: (payload, db) => db.rpc("cmd_delete_all_http_responses", payload),
|
||||
cmd_delete_send_history: (payload, db) => db.rpc("cmd_delete_send_history", payload),
|
||||
cmd_validate_http_assertions: (payload, db) => db.rpc("cmd_validate_http_assertions", payload),
|
||||
cmd_preview_http_assertions: (payload, db) => db.rpc("cmd_preview_http_assertions", payload),
|
||||
cmd_http_response_json_children: (payload, db) =>
|
||||
db.rpc("cmd_http_response_json_children", payload),
|
||||
|
||||
/* ------------------------------- sending ------------------------------- */
|
||||
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { HttpAssertions, HttpResponse } from "@yaakapp-internal/models";
|
||||
import type { WorkerConnection } from "./connection";
|
||||
import { sendHttpRequest } from "./send";
|
||||
|
||||
vi.mock("./server", () => ({
|
||||
serverIdentity: async () => "test server",
|
||||
serverSendUrl: () => "https://test.invalid/send",
|
||||
readFrames: async function* () {
|
||||
yield {
|
||||
type: "response",
|
||||
status: 200,
|
||||
headers: [],
|
||||
requestHeaders: [],
|
||||
url: "https://example.com",
|
||||
};
|
||||
yield { type: "body", data: btoa('{"id":123}') };
|
||||
yield { type: "done", contentLength: 10, contentLengthCompressed: 10, elapsed: 1 };
|
||||
},
|
||||
}));
|
||||
|
||||
const definition: HttpAssertions = {
|
||||
version: 1,
|
||||
checks: [
|
||||
{
|
||||
id: "check",
|
||||
enabled: true,
|
||||
target: "json",
|
||||
selector: "$.id",
|
||||
operator: "equals",
|
||||
expected: "SECRET_EXPECTED",
|
||||
expectedType: "text",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
function worker() {
|
||||
let cancel: (() => void) | undefined;
|
||||
let storedBody: Uint8Array | undefined;
|
||||
const evaluations: {
|
||||
definition: HttpAssertions;
|
||||
response: Partial<HttpResponse>;
|
||||
canceled: boolean;
|
||||
}[] = [];
|
||||
const writes: Partial<HttpResponse>[] = [];
|
||||
const request = {
|
||||
id: "rq_test",
|
||||
model: "http_request",
|
||||
workspaceId: "wk_test",
|
||||
assertions: structuredClone(definition),
|
||||
};
|
||||
const db = {
|
||||
rpc: async (cmd: string, payload: Record<string, unknown>) => {
|
||||
if (cmd === "web_get_http_request") return structuredClone(request);
|
||||
if (cmd === "models_upsert") {
|
||||
writes.push(structuredClone(payload.model as Partial<HttpResponse>));
|
||||
return "rs_test";
|
||||
}
|
||||
if (cmd === "evaluate_http_assertions") {
|
||||
const input = payload as (typeof evaluations)[number];
|
||||
if (!input.response.error) expect(new TextDecoder().decode(storedBody)).toBe('{"id":123}');
|
||||
evaluations.push(structuredClone(input));
|
||||
return {
|
||||
definition: input.definition,
|
||||
results: [
|
||||
{
|
||||
assertionId: "check",
|
||||
outcome: input.response.error ? "error" : "passed",
|
||||
reason: "test evaluator",
|
||||
actual: null,
|
||||
},
|
||||
],
|
||||
error: null,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
},
|
||||
prepareHttpSend: async () => ({ request, settings: {}, cookieJar: null, settingEvents: [] }),
|
||||
blobPut: async (_id: string, bytes: Uint8Array) => {
|
||||
storedBody = bytes;
|
||||
},
|
||||
listen: (_event: string, callback: () => void) => {
|
||||
cancel = callback;
|
||||
return () => {
|
||||
cancel = undefined;
|
||||
};
|
||||
},
|
||||
} as unknown as WorkerConnection;
|
||||
return { db, evaluations, writes, cancel: () => cancel?.() };
|
||||
}
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
describe("browser assertion evaluation", () => {
|
||||
it("evaluates locally after saving the body and keeps assertion values out of the proxy request", async () => {
|
||||
const fetch = vi.fn(async (_url: string, init: RequestInit) => {
|
||||
expect(init.body).not.toContain("SECRET_EXPECTED");
|
||||
return new Response("stream");
|
||||
});
|
||||
vi.stubGlobal("fetch", fetch);
|
||||
const { db, evaluations, writes } = worker();
|
||||
const response = await sendHttpRequest(db, "rq_test", null, null);
|
||||
expect(evaluations).toHaveLength(1);
|
||||
expect(evaluations[0]?.definition).toEqual(definition);
|
||||
expect(evaluations[0]?.canceled).toBe(false);
|
||||
expect(response.assertionResults?.results[0]?.outcome).toBe("passed");
|
||||
expect(writes.at(-1)?.state).toBe("closed");
|
||||
expect(writes.at(-1)?.assertionResults).toEqual(response.assertionResults);
|
||||
});
|
||||
|
||||
it("marks a canceled response as incomplete before asking the shared evaluator", async () => {
|
||||
const { db, cancel, evaluations } = worker();
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async () => {
|
||||
cancel();
|
||||
throw new Error("aborted");
|
||||
}),
|
||||
);
|
||||
const response = await sendHttpRequest(db, "rq_test", null, null);
|
||||
expect(evaluations).toHaveLength(1);
|
||||
expect(evaluations[0]?.canceled).toBe(true);
|
||||
expect(evaluations[0]?.response.error).toBe("Request canceled");
|
||||
expect(response.assertionResults?.results[0]?.outcome).toBe("error");
|
||||
});
|
||||
});
|
||||
@@ -24,6 +24,8 @@
|
||||
// Types only: the models package imports this one at runtime, and a type import
|
||||
// is erased, so there is no cycle.
|
||||
import type {
|
||||
AssertionReport,
|
||||
HttpAssertions,
|
||||
Cookie,
|
||||
CookieJar,
|
||||
HttpRequest,
|
||||
@@ -70,8 +72,16 @@ export async function sendHttpRequest(
|
||||
// The response row exists before anything can go wrong, as on the desktop, so
|
||||
// a failure to render or to reach the server lands in the response pane as
|
||||
// that response's error rather than as a toast that names no request.
|
||||
const workspaceId = await workspaceIdOfRequest(db, requestId);
|
||||
const response = new ResponseWriter(db, { model: "http_response", requestId, workspaceId });
|
||||
const request = await db.rpc<HttpRequest>("web_get_http_request", { requestId });
|
||||
const response = new ResponseWriter(
|
||||
db,
|
||||
{
|
||||
model: "http_response",
|
||||
requestId,
|
||||
workspaceId: request.workspaceId,
|
||||
},
|
||||
request.assertions ?? { version: 1, checks: [] },
|
||||
);
|
||||
await response.create();
|
||||
|
||||
const cancel = new AbortController();
|
||||
@@ -81,7 +91,7 @@ export async function sendHttpRequest(
|
||||
await runSend(db, response, requestId, environmentId, cookieJarId, cancel.signal);
|
||||
} catch (err) {
|
||||
const message = cancel.signal.aborted ? "Request canceled" : errorMessage(err);
|
||||
await response.finish({ error: message });
|
||||
await response.finish({ error: message }, cancel.signal.aborted);
|
||||
} finally {
|
||||
unlistenCancel();
|
||||
}
|
||||
@@ -111,7 +121,8 @@ async function runSend(
|
||||
timeline.push(prepared.settingEvents);
|
||||
|
||||
const body: SendRequest = {
|
||||
request: prepared.request,
|
||||
// Assertions run locally against the completed response.
|
||||
request: { ...prepared.request, assertions: { version: 1, checks: [] } },
|
||||
settings: prepared.settings,
|
||||
cookies: prepared.cookieJar?.cookies ?? null,
|
||||
};
|
||||
@@ -234,6 +245,7 @@ class ResponseWriter {
|
||||
constructor(
|
||||
private readonly db: WorkerConnection,
|
||||
initial: ResponseRow,
|
||||
private readonly assertions: HttpAssertions,
|
||||
) {
|
||||
this.state = initial;
|
||||
}
|
||||
@@ -266,8 +278,17 @@ class ResponseWriter {
|
||||
await this.db.rpc("models_upsert", { model: this.state });
|
||||
}
|
||||
|
||||
async finish(patch: ResponsePatch): Promise<void> {
|
||||
await this.patch({ ...patch, state: "closed" });
|
||||
async finish(patch: ResponsePatch, canceled = false): Promise<void> {
|
||||
const response = { ...this.state, ...patch, state: "closed" as const };
|
||||
const assertionResults =
|
||||
this.assertions.version !== 1 || this.assertions.checks.length > 0
|
||||
? await this.db.rpc<AssertionReport>("evaluate_http_assertions", {
|
||||
definition: this.assertions,
|
||||
response,
|
||||
canceled,
|
||||
})
|
||||
: null;
|
||||
await this.patch({ ...patch, state: "closed", assertionResults });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -315,17 +336,16 @@ class TimelineWriter {
|
||||
* yaak-models), so an edit made while the send was in flight survives rather
|
||||
* than being written over by the send's stale snapshot.
|
||||
*/
|
||||
async function persistCookies(db: WorkerConnection, jar: CookieJar, cookies: Cookie[]): Promise<void> {
|
||||
await db.rpc("web_persist_send_cookies", { cookieJarId: jar.id, before: jar.cookies, after: cookies });
|
||||
}
|
||||
|
||||
/**
|
||||
* The request's workspace, needed to create the response row before the worker
|
||||
* has resolved the request (which is where a render refusal would land).
|
||||
*/
|
||||
async function workspaceIdOfRequest(db: WorkerConnection, requestId: string): Promise<string> {
|
||||
const req = await db.rpc<{ workspaceId: string }>("web_get_http_request", { requestId });
|
||||
return req.workspaceId;
|
||||
async function persistCookies(
|
||||
db: WorkerConnection,
|
||||
jar: CookieJar,
|
||||
cookies: Cookie[],
|
||||
): Promise<void> {
|
||||
await db.rpc("web_persist_send_cookies", {
|
||||
cookieJarId: jar.id,
|
||||
before: jar.cookies,
|
||||
after: cookies,
|
||||
});
|
||||
}
|
||||
|
||||
function errorMessage(err: unknown): string {
|
||||
|
||||
Reference in new issue
Block a user