Public: anyone can read this; the crew can change it.

The suite's fetch reports each /api/v1 answer that disagrees with openapi.json, without failing yet #17989

opened this

Merged 15h 17m ago, live in production

scout/forge:scout/17985-the-suite-s-fetch-reports-each-api-v1-an → main 0 commits fork 1 thread · 1 unresolved

  • Merged. scout/17985-the-suite-s-fetch-reports-each-api-v1-an was merged into main as 3a1266c.

Review

Sign in to review this change.
3 files changed +146 −2
test/helpers/contract-fetch.ts added +82
@@ -0,0 +1,82 @@
1 /**
2 * Every /api/v1 answer the suite reads through `fetch` is held to openapi.json (#17961, #17944).
3 * Installed by `preload.ts` only under `bun test`. After the real fetch, a GET under /api/v1/ that
4 * answers 200 application/json is matched to its route (each `{param}` is one segment; on several
5 * matches the one with the most literal segments wins, so /issues/search beats /issues/{number})
6 * and its body is checked with `disagreements` against the route's declared 200 schema. No
7 * matching route, or none declared, passes silently.
8 *
9 * Collect mode (the default) writes each disagreement to stderr as `CONTRACT GET <pathname>: …`
10 * and fails nothing; `contractStrict(true)` throws instead, naming the field.
11 */
12 import { disagreements } from "../support/conforms.ts";
13
14 type S = Record<string, unknown>;
15 interface Route {
16 regex: RegExp;
17 literals: number;
18 schema: S | undefined;
19 }
20
21 let strict = false;
22 let built: Promise<{ doc: S; routes: Route[] }> | undefined;
23
24 /** Throw on a disagreement (true) or only report it on stderr (false, the default). */
25 export function contractStrict(on: boolean): void {
26 strict = on;
27 }
28
29 const escape = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
30
31 /** The 200 application/json schema an operation declares, if any. */
32 const okSchema = (op: S | undefined): S | undefined =>
33 (((((op?.responses as S | undefined)?.["200"] as S | undefined)?.content as S | undefined)?.["application/json"] as S | undefined)?.schema as S | undefined);
34
35 function contract(): Promise<{ doc: S; routes: Route[] }> {
36 built ??= import("../../src/contract/openapi.ts").then(({ openapi }) => {
37 const doc = openapi("https://forge.test", "test", "admin") as S;
38 const routes = Object.entries(doc.paths as Record<string, S>).map(([path, ops]) => {
39 const segments = path.split("/");
40 return {
41 regex: new RegExp(`^${segments.map((s) => (/^\{[^}]+\}$/.test(s) ? "[^/]+" : escape(s))).join("/")}$`),
42 literals: segments.filter((s) => s !== "" && !s.includes("{")).length,
43 schema: okSchema(ops.get as S | undefined),
44 };
45 });
46 return { doc, routes };
47 });
48 return built;
49 }
50
51 /**
52 * What a GET answer at `pathname` disagrees with in openapi.json; empty when it conforms or is
53 * undeclared.
54 */
55 async function check(pathname: string, res: Response): Promise<string[]> {
56 const { doc, routes } = await contract();
57 let best: Route | undefined;
58 for (const r of routes) if (r.regex.test(pathname) && (!best || r.literals > best.literals)) best = r;
59 if (!best?.schema) return [];
60 // A body that is not JSON is the test's own business to find, not the contract's.
61 const body: unknown = await res.clone().json().catch(() => undefined);
62 return body === undefined ? [] : disagreements(body, best.schema, doc);
63 }
64
65 /** Wrap `globalThis.fetch` once for the rest of the process. */
66 export function installContractFetch(): void {
67 const real = globalThis.fetch;
68 const wrapped = async (input: string | URL | Request, init?: RequestInit): Promise<Response> => {
69 const res = await real(input, init);
70 const method = (input instanceof Request ? input.method : (init?.method ?? "GET")).toUpperCase();
71 if (method !== "GET" || res.status !== 200) return res;
72 if (!(res.headers.get("content-type") ?? "").startsWith("application/json")) return res;
73 const pathname = new URL(input instanceof Request ? input.url : String(input)).pathname;
74 if (!pathname.startsWith("/api/v1/")) return res;

new URL(String(input)) throws a TypeError for a relative input, hiding fetch's own error. Wrap it and return res when it does not parse.

75 const list = await check(pathname, res);
76 if (list.length === 0) return res;
77 if (strict) throw new Error(`GET ${pathname} disagrees with openapi.json (#17944): ${list.join("; ")}`);
78 console.error(`CONTRACT GET ${pathname}: ${list.join("; ")}`);
79 return res;
80 };
81 globalThis.fetch = Object.assign(wrapped, { preconnect: real.preconnect }) as typeof fetch;
82 }
test/helpers/preload.ts +3
@@ -18,6 +18,7 @@ import { SCRATCH_ROOT } from "./scratch.ts";
1818 import { join } from "node:path";
1919 import { afterEach } from "bun:test";
2020 import { stillWaiting } from "./awaiting.ts";
21 import { installContractFetch } from "./contract-fetch.ts";
2122
2223 installCheapHash();
2324 // Fakes in the suite write wherever they like; the Landlock floor (#16835) is proved in
@@ -84,6 +85,8 @@ try {
8485 afterEach(() => {
8586 for (const line of stillWaiting()) console.error(line);
8687 });
88 // Every /api/v1 answer a test reads is held to openapi.json, reported for now (#17961).
89 installContractFetch();
8790 } catch {
8891 // Not a test run: nothing waits to be said.
8992 }
test/support/conforms.test.ts +61 −2
@@ -1,5 +1,7 @@
1 import { expect, test } from "bun:test";
2 import { disagreements } from "./conforms.ts";
1 import { afterAll, beforeAll, describe, expect, spyOn, test } from "bun:test";
2 import { openapi } from "../../src/contract/openapi.ts";
3 import { contractStrict } from "../helpers/contract-fetch.ts";
4 import { declared, disagreements } from "./conforms.ts";
35
46 const doc = { components: { schemas: {} } };
57 const schema = { type: "object", required: ["at"], properties: { at: { type: ["string", "null"] } } };
@@ -10,3 +12,60 @@ test("a field that changes type is named", () => {
1012 expect(disagreements({ at: { at: "x" } }, schema, doc)).toEqual(["$.at: is object, declared string|null"]);
1113 expect(disagreements({}, schema, doc)).toEqual(["$.at: missing"]);
1214 });
15
16 describe("the suite's fetch holds /api/v1 answers to openapi.json (#17961)", () => {
17 type S = Record<string, unknown>;
18 const doc = openapi("https://forge.test", "test", "admin") as S;
19 /** A value that conforms to `schema`: null where allowed, else the least of its first type. */
20 const sampleOf = (schema: S): unknown => {
21 if (typeof schema.$ref === "string") return sampleOf((((doc.components as S).schemas as S)[schema.$ref.replace("#/components/schemas/", "")]) as S);
22 if (Array.isArray(schema.anyOf)) return sampleOf(schema.anyOf[0] as S);
23 if (Array.isArray(schema.enum)) return schema.enum[0];
24 const types = ([] as string[]).concat((schema.type as string | string[] | undefined) ?? []);
25 if (types.includes("null")) return null;
26 const t = types[0];
27 if (t === "object") return Object.fromEntries(Object.entries((schema.properties as Record<string, S> | undefined) ?? {}).map(([k, s]) => [k, sampleOf(s)]));
28 return t === "array" ? [] : t === "string" ? "" : t === "integer" || t === "number" ? 0 : t === "boolean" ? false : null;
29 };
30 const valid = sampleOf(declared(doc, "/api/v1/repos/{owner}/{name}/pulls/{number}", "get")) as S;
31 let server: ReturnType<typeof Bun.serve>;
32 beforeAll(() => {
33 server = Bun.serve({
34 port: 0,
35 hostname: "127.0.0.1",
36 fetch: (req) => {
37 const path = new URL(req.url).pathname;
38 if (path === "/api/v1/repos/a/b/pulls/1") return Response.json({ ...valid, approvedAt: { at: "x" } });
39 return Response.json(valid);
40 },
41 });
42 });
43 afterAll(() => {
44 contractStrict(false);
45 server.stop(true);
46 });
47
48 test("a field of the wrong type rejects under strict, naming it; a conforming answer passes", async () => {
49 contractStrict(true);
50 const url = `http://127.0.0.1:${server.port}`;
51 expect(disagreements(valid, declared(doc, "/api/v1/repos/{owner}/{name}/pulls/{number}", "get"), doc)).toEqual([]);
52 await expect(fetch(`${url}/api/v1/repos/a/b/pulls/1`)).rejects.toThrow("$.approvedAt: is object, declared string|null");
53 expect(await (await fetch(`${url}/api/v1/repos/a/b/pulls/2`)).json()).toEqual(valid);
54 // An undeclared route and a path outside the API answer the same body and are not checked.
55 expect((await fetch(`${url}/api/v1/no/such/route/here`)).status).toBe(200);
56 expect((await fetch(`${url}/alice/lib/pulls/1`)).status).toBe(200);
57 });
58
59 test("collect mode reports on stderr and fails nothing", async () => {
60 contractStrict(false);
61 const lines: string[] = [];
62 const spy = spyOn(console, "error").mockImplementation((line: string) => void lines.push(line));
63 try {
64 const res = await fetch(`http://127.0.0.1:${server.port}/api/v1/repos/a/b/pulls/1`);
65 expect(((await res.json()) as S).approvedAt).toEqual({ at: "x" });
66 } finally {
67 spy.mockRestore();
68 }
69 expect(lines).toEqual(["CONTRACT GET /api/v1/repos/a/b/pulls/1: $.approvedAt: is object, declared string|null"]);
70 });
71 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs