Files

219 lines
8.1 KiB
TypeScript

import { readdirSync, readFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import { parse as parseYaml } from "yaml";
import {
buildPatternBoundsIndex,
moduleSpecifier,
rewriteMockSource,
type PatternBoundsIndex,
} from "./mock-patterns";
const frontendRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const document = {
components: {
schemas: {
Token: { type: "string", minLength: 32, maxLength: 128, pattern: "^[A-Za-z0-9_-]+$" },
Tag: { type: "string", minLength: 1, maxLength: 50, pattern: "^\\S(?:.*\\S)?$" },
Session: {
type: "object",
properties: {
token: { $ref: "#/components/schemas/Token" },
next_cursor: {
oneOf: [
{ type: "string", minLength: 1, maxLength: 512, pattern: "^[A-Za-z0-9_-]+$" },
{ type: "null" },
],
},
tags: { type: "array", items: { $ref: "#/components/schemas/Tag" } },
nested: {
type: "object",
properties: { code: { type: "string", pattern: "^[a-z]+$" } },
},
},
examples: [{ properties: { ignored: { type: "string", pattern: "x" } } }],
},
},
},
};
const header = `/**
* Generated by orval 🍺
* Do not edit manually.
*/
import {
faker
} from '@faker-js/faker';
import {
HttpResponse
} from 'msw';
`;
const generated = `${header}
export const getSessionMock = (): Session => ({token: faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), next_cursor: faker.helpers.arrayElement([faker.helpers.fromRegExp("^[A-Za-z0-9_-]+$"), null]), tags: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (faker.helpers.fromRegExp("^\\\\S(?:.*\\\\S)?$"))), nested: {code: faker.helpers.fromRegExp("^[a-z]+$")}})
`;
const rewritten = `/**
* Generated by orval 🍺
* Do not edit manually.
*/
import {
faker
} from '@faker-js/faker';
import {
fakeFromPattern
} from '../../mock-pattern';
import {
HttpResponse
} from 'msw';
export const getSessionMock = (): Session => ({token: fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 32, maxLength: 128}), next_cursor: faker.helpers.arrayElement([fakeFromPattern("^[A-Za-z0-9_-]+$", {minLength: 1, maxLength: 512}), null]), tags: Array.from({ length: faker.number.int({min: 1, max: 20}) }, (_, i) => i + 1).map(() => (fakeFromPattern("^\\\\S(?:.*\\\\S)?$", {minLength: 1, maxLength: 50}))), nested: {code: fakeFromPattern("^[a-z]+$")}})
`;
const index = buildPatternBoundsIndex(document);
function rewrite(source: string, bounds: PatternBoundsIndex = index) {
return rewriteMockSource(source, "tag.msw.ts", bounds, "../../mock-pattern");
}
describe("buildPatternBoundsIndex", () => {
it("indexes patterned strings by the property that holds them", () => {
expect(index.get("token")?.get("^[A-Za-z0-9_-]+$")).toEqual([
{ minLength: 32, maxLength: 128 },
]);
expect(index.get("next_cursor")?.get("^[A-Za-z0-9_-]+$")).toEqual([
{ minLength: 1, maxLength: 512 },
]);
expect(index.get("tags")?.get("^\\S(?:.*\\S)?$")).toEqual([{ minLength: 1, maxLength: 50 }]);
expect(index.get("code")?.get("^[a-z]+$")).toEqual([{}]);
// A nested object property belongs to its own name, and examples hold
// data, not schemas.
expect(index.has("nested")).toBe(false);
expect(index.has("ignored")).toBe(false);
});
it("keeps every distinct bound of a property and pattern", () => {
const ambiguous = buildPatternBoundsIndex({
components: {
schemas: {
A: { properties: { id: { type: "string", maxLength: 8, pattern: "^a+$" } } },
B: { properties: { id: { type: "string", maxLength: 9, pattern: "^a+$" } } },
C: { properties: { id: { type: "string", maxLength: 8, pattern: "^a+$" } } },
},
},
});
expect(ambiguous.get("id")?.get("^a+$")).toEqual([{ maxLength: 8 }, { maxLength: 9 }]);
});
it("rejects references outside the document", () => {
expect(() =>
buildPatternBoundsIndex({ properties: { id: { $ref: "other.yml#/Id" } } }),
).toThrow("Only local references are supported");
});
});
describe("rewriteMockSource", () => {
it("replaces each faker pattern call with the helper and the schema bounds", () => {
expect(rewrite(generated)).toEqual({ text: rewritten, rewrittenCalls: 4 });
});
it("leaves its own output unchanged", () => {
expect(rewrite(rewritten)).toEqual({ text: rewritten, rewrittenCalls: 0 });
});
it("leaves a file without pattern calls unchanged", () => {
const source = `${header}\nexport const getHealthMock = () => ({status: 'ok'})\n`;
expect(rewrite(source)).toEqual({ text: source, rewrittenCalls: 0 });
});
it("fails when no schema property has the pattern", () => {
const source = `${header}\nexport const m = () => ({token: faker.helpers.fromRegExp("^b+$")})\n`;
expect(() => rewrite(source)).toThrow(
'tag.msw.ts:13: no schema property "token" with pattern "^b+$"',
);
});
it("uses the common bounds when schemas share a property name and a pattern", () => {
const shared = buildPatternBoundsIndex({
components: {
schemas: {
A: {
properties: { id: { type: "string", minLength: 1, maxLength: 8, pattern: "^a+$" } },
},
B: { properties: { id: { type: "string", maxLength: 9, pattern: "^a+$" } } },
},
},
});
const source = `${header}\nexport const m = () => ({id: faker.helpers.fromRegExp("^a+$")})\n`;
expect(rewrite(source, shared).text).toContain(
'fakeFromPattern("^a+$", {minLength: 1, maxLength: 8})',
);
});
it("fails when the bounds of schemas have no common value", () => {
const disjoint = buildPatternBoundsIndex({
components: {
schemas: {
A: { properties: { id: { type: "string", maxLength: 3, pattern: "^a+$" } } },
B: { properties: { id: { type: "string", minLength: 5, pattern: "^a+$" } } },
},
},
});
const source = `${header}\nexport const m = () => ({id: faker.helpers.fromRegExp("^a+$")})\n`;
expect(() => rewrite(source, disjoint)).toThrow("so the mock bounds are ambiguous");
});
it("fails on a call that it cannot attribute to a property", () => {
const topLevel = `${header}\nexport const m = (): string => faker.helpers.fromRegExp("^a+$")\n`;
expect(() => rewrite(topLevel)).toThrow("is not the value of a named property");
const dynamic = `${header}\nconst p = "^a+$";\nexport const m = () => ({id: faker.helpers.fromRegExp(p)})\n`;
expect(() => rewrite(dynamic)).toThrow("must take one string literal");
});
});
describe("moduleSpecifier", () => {
it("returns an extensionless relative specifier", () => {
expect(
moduleSpecifier(
"/repo/src/shared/api/endpoints/need/need.msw.ts",
"/repo/src/shared/api/mock-pattern.ts",
),
).toBe("../../mock-pattern");
expect(moduleSpecifier("/repo/a/b.msw.ts", "/repo/a/mock-pattern.ts")).toBe("./mock-pattern");
});
});
describe("generated mocks", () => {
// The committed mocks must be a fixed point of the rewrite: generation
// followed by this step reproduces them byte for byte.
it("are already rewritten against the current contract", () => {
const contract: unknown = parseYaml(
readFileSync(join(frontendRoot, "../api/core/openapi.bundle.yml"), "utf8"),
);
const contractIndex = buildPatternBoundsIndex(contract);
const endpoints = join(frontendRoot, "src/shared/api/endpoints");
const files = readdirSync(endpoints, { recursive: true, encoding: "utf8" }).filter((name) =>
name.endsWith(".msw.ts"),
);
expect(files.length).toBeGreaterThan(0);
for (const name of files) {
const file = join(endpoints, name);
const source = readFileSync(file, "utf8");
const result = rewriteMockSource(
source,
name,
contractIndex,
moduleSpecifier(file, join(frontendRoot, "src/shared/api/mock-pattern.ts")),
);
expect(result.rewrittenCalls, name).toBe(0);
expect(result.text === source, name).toBe(true);
}
});
});