@fougere/testing 0.3.0-alpha.0 → 0.4.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app.js +3 -3
- package/dist/app.js.map +1 -1
- package/dist/comparison.d.ts.map +1 -1
- package/dist/comparison.js +3 -3
- package/dist/comparison.js.map +1 -1
- package/dist/derive.d.ts +2 -2
- package/dist/derive.d.ts.map +1 -1
- package/dist/derive.js +3 -3
- package/dist/derive.js.map +1 -1
- package/dist/doors.d.ts +1 -1
- package/dist/doors.d.ts.map +1 -1
- package/dist/doors.js +6 -6
- package/dist/doors.js.map +1 -1
- package/dist/gql.d.ts.map +1 -1
- package/dist/gql.js +2 -2
- package/dist/gql.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/remotes.d.ts +1 -1
- package/dist/remotes.js +5 -5
- package/dist/remotes.js.map +1 -1
- package/dist/sample.d.ts +1 -1
- package/dist/sample.d.ts.map +1 -1
- package/dist/sample.js +2 -2
- package/dist/sample.js.map +1 -1
- package/dist/sync.d.ts +3 -3
- package/dist/sync.d.ts.map +1 -1
- package/dist/sync.js +3 -3
- package/dist/sync.js.map +1 -1
- package/dist/vitest.d.ts.map +1 -1
- package/dist/vitest.js +1 -3
- package/dist/vitest.js.map +1 -1
- package/package.json +11 -10
- package/src/all.ts +57 -0
- package/src/app.ts +125 -0
- package/src/comparison.ts +237 -0
- package/src/derive.ts +18 -0
- package/src/doors.ts +103 -0
- package/src/gql.ts +136 -0
- package/src/index.ts +20 -0
- package/src/load.ts +107 -0
- package/src/remotes.ts +125 -0
- package/src/sample.ts +86 -0
- package/src/scope.ts +81 -0
- package/src/stub.ts +80 -0
- package/src/sync.ts +98 -0
- package/src/vitest.ts +48 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fougere/testing",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0-alpha.0",
|
|
4
4
|
"description": "Tests derived from the declaration — cases, stubs and a gradient of realities.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"fougere",
|
|
@@ -29,23 +29,24 @@
|
|
|
29
29
|
}
|
|
30
30
|
},
|
|
31
31
|
"files": [
|
|
32
|
-
"dist"
|
|
32
|
+
"dist",
|
|
33
|
+
"src"
|
|
33
34
|
],
|
|
34
35
|
"dependencies": {
|
|
35
36
|
"json-schema-faker": "^0.6.3",
|
|
36
|
-
"@fougere/
|
|
37
|
-
"@fougere/
|
|
38
|
-
"@fougere/schema": "0.
|
|
39
|
-
"@fougere/
|
|
40
|
-
"@fougere/transport-http": "0.
|
|
41
|
-
"@fougere/app": "0.
|
|
37
|
+
"@fougere/core": "0.4.0-alpha.0",
|
|
38
|
+
"@fougere/container": "0.4.0-alpha.0",
|
|
39
|
+
"@fougere/schema": "0.4.0-alpha.0",
|
|
40
|
+
"@fougere/defaults": "0.4.0-alpha.0",
|
|
41
|
+
"@fougere/transport-http": "0.4.0-alpha.0",
|
|
42
|
+
"@fougere/app": "0.4.0-alpha.0"
|
|
42
43
|
},
|
|
43
44
|
"publishConfig": {
|
|
44
45
|
"access": "public"
|
|
45
46
|
},
|
|
46
47
|
"peerDependencies": {
|
|
47
48
|
"vitest": ">=2",
|
|
48
|
-
"@fougere/adapter-graphql": "0.
|
|
49
|
+
"@fougere/adapter-graphql": "0.4.0-alpha.0"
|
|
49
50
|
},
|
|
50
51
|
"peerDependenciesMeta": {
|
|
51
52
|
"vitest": {
|
|
@@ -57,7 +58,7 @@
|
|
|
57
58
|
},
|
|
58
59
|
"devDependencies": {
|
|
59
60
|
"vitest": "^4.1.0",
|
|
60
|
-
"@fougere/adapter-graphql": "0.
|
|
61
|
+
"@fougere/adapter-graphql": "0.4.0-alpha.0"
|
|
61
62
|
},
|
|
62
63
|
"scripts": {
|
|
63
64
|
"build": "rm -rf dist && tsc",
|
package/src/all.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import type { App } from '@fougere/core';
|
|
3
|
+
import type { SchemaView } from '@fougere/schema';
|
|
4
|
+
import { checkContract, checkOutput, type CheckOptions } from './doors.js';
|
|
5
|
+
import { checkDoors, type DoorOptions } from './comparison.js';
|
|
6
|
+
|
|
7
|
+
export interface CheckAllOptions extends DoorOptions, CheckOptions {
|
|
8
|
+
/** Entities to leave out, by name — one whose rows a test cannot seed, typically. */
|
|
9
|
+
except?: string[];
|
|
10
|
+
/** Skip the four-door comparison. The contract and the leak are still checked. */
|
|
11
|
+
doors?: boolean;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Every entity the app SERVES, with its handler.
|
|
16
|
+
*
|
|
17
|
+
* Not every entity it scanned: one with no handler has no façade, so there is no door to
|
|
18
|
+
* ask — the distinction the NOT_FOUND message used to miss. A relation is not followed
|
|
19
|
+
* either; the entity it points at is checked on its own turn if it has a door.
|
|
20
|
+
*/
|
|
21
|
+
export function servedEntities(app: App): { name: string; entity: SchemaView }[] {
|
|
22
|
+
const served: { name: string; entity: SchemaView }[] = [];
|
|
23
|
+
for (const frond of app.fronds) {
|
|
24
|
+
const addresses = new Set(frond.handlers.filter((handler) => !handler.surface).map((handler) => handler.address));
|
|
25
|
+
for (const entity of frond.entities) {
|
|
26
|
+
if (addresses.has(entity.name)) served.push({ name: entity.name, entity: entity.entityClass });
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return served;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The whole suite, for every entity, from a file that names none of them.
|
|
34
|
+
*
|
|
35
|
+
* The list comes from the scan rather than from imports, and that is the point: a list of
|
|
36
|
+
* imports is a second copy of what the project already declares, and it goes stale the day
|
|
37
|
+
* an entity is added — silently, because a missing test cannot fail.
|
|
38
|
+
*
|
|
39
|
+
* An entity whose frond is declared in `remotes:` is not here at all: it is not this app's
|
|
40
|
+
* to serve, and `testApp` does not follow the topology in the first place.
|
|
41
|
+
*/
|
|
42
|
+
export function checkAll(app: App, options: CheckAllOptions = {}): void {
|
|
43
|
+
const except = new Set(options.except ?? []);
|
|
44
|
+
const served = servedEntities(app).filter((one) => !except.has(one.name));
|
|
45
|
+
|
|
46
|
+
describe('what this app serves', () => {
|
|
47
|
+
it('is not empty — an empty suite proves nothing and still passes', () => {
|
|
48
|
+
expect(served.length).toBeGreaterThan(0);
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
for (const { entity } of served) {
|
|
53
|
+
checkContract(app, entity, options);
|
|
54
|
+
checkOutput(app, entity, options);
|
|
55
|
+
if (options.doors !== false) checkDoors(app, entity, options);
|
|
56
|
+
}
|
|
57
|
+
}
|
package/src/app.ts
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { type App } from '@fougere/core';
|
|
2
|
+
import { boot } from '@fougere/core/node';
|
|
3
|
+
import { createContainer } from '@fougere/container';
|
|
4
|
+
import { resolveStorage, type DbConfig } from '@fougere/defaults';
|
|
5
|
+
import { installStubs, type Port, type Stub } from './stub.js';
|
|
6
|
+
import { scopeOfRun } from './scope.js';
|
|
7
|
+
import { lowerFirst } from '@fougere/schema';
|
|
8
|
+
|
|
9
|
+
export interface TestAppOptions {
|
|
10
|
+
/**
|
|
11
|
+
* The project to scan. Read from the test file's own position when absent — a file
|
|
12
|
+
* under `fronds/blog/tests/` states that its subject is `blog` and that the project
|
|
13
|
+
* starts above `fronds/`.
|
|
14
|
+
*/
|
|
15
|
+
root?: string;
|
|
16
|
+
/** Boot only these fronds, by name. Deduced from the position when absent. */
|
|
17
|
+
fronds?: string[];
|
|
18
|
+
/**
|
|
19
|
+
* The running test file, for hosts other than vitest. Vitest is read automatically
|
|
20
|
+
* through `expect.getState()`; anything else hands its own path in.
|
|
21
|
+
*/
|
|
22
|
+
testPath?: string;
|
|
23
|
+
/**
|
|
24
|
+
* Where the rows go. `':memory:'` by default — a real SQLite engine, so the DDL, the
|
|
25
|
+
* `CHECK` constraints, `unique` and real transactions are all exercised, and nothing is
|
|
26
|
+
* written to disk.
|
|
27
|
+
*
|
|
28
|
+
* Not an in-memory ORM: `createMemoryOrm` realizes the axes but is not the engine
|
|
29
|
+
* production runs, and a tool whose thesis is *the realizations must agree* cannot pick
|
|
30
|
+
* the one that does not ship.
|
|
31
|
+
*/
|
|
32
|
+
db?: string;
|
|
33
|
+
/**
|
|
34
|
+
* Follow `remotes:` from the config. False by default — a test that meant to exercise
|
|
35
|
+
* one frond should not silently reach for a process that is not running.
|
|
36
|
+
*/
|
|
37
|
+
topology?: boolean;
|
|
38
|
+
/**
|
|
39
|
+
* Ports answered by a double instead of their realization. A double carries every
|
|
40
|
+
* method the port declares and returns nothing until the test says what it returns.
|
|
41
|
+
*/
|
|
42
|
+
stub?: Port[];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** An app, plus the doubles standing in front of its ports and the facts it announced. */
|
|
46
|
+
export interface TestApp extends App {
|
|
47
|
+
/** The double installed for a port, to state a return or read what was called. */
|
|
48
|
+
stub<T>(port: abstract new (...args: never[]) => T): Stub<T>;
|
|
49
|
+
/**
|
|
50
|
+
* What was announced under a fact's name, in order.
|
|
51
|
+
*
|
|
52
|
+
* Read from the carrier's own seat: `Emissions.announce` hands EVERY announced fact to
|
|
53
|
+
* `onEmit`, whether or not anything in this process listens. So watching costs nothing
|
|
54
|
+
* and adds no second dispatcher — the one thing `Emissions` refuses to become.
|
|
55
|
+
*
|
|
56
|
+
* Its dual needs no help at all: `app.deliver(fact, payload)` is already the carrier's
|
|
57
|
+
* door, and it rejects when a subscriber refuses.
|
|
58
|
+
*/
|
|
59
|
+
announced(fact: { name: string } | string): unknown[];
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* An app to ask questions of, wired the conventional way.
|
|
64
|
+
*
|
|
65
|
+
* Wraps `boot()`, which already loads the config, creates the container, sets the storage
|
|
66
|
+
* up and seeds — its own comment names tests among the surfaces it serves. What this adds
|
|
67
|
+
* is the two decisions a test makes differently: the rows live in memory, and the
|
|
68
|
+
* topology is not followed.
|
|
69
|
+
*
|
|
70
|
+
* Storage still goes through `resolveStorage`, the single place that knows a storage
|
|
71
|
+
* package; calling `setupSqlite` here would be a second one.
|
|
72
|
+
*/
|
|
73
|
+
export async function testApp(options: TestAppOptions = {}): Promise<TestApp> {
|
|
74
|
+
const db: DbConfig = { dialect: 'sqlite', path: options.db ?? ':memory:' };
|
|
75
|
+
// The position is consulted only for what the caller did not state: an explicit `root`
|
|
76
|
+
// or `fronds` wins, the way a config key wins over a convention everywhere else.
|
|
77
|
+
const scope = (options.root && options.fronds) ? undefined
|
|
78
|
+
: await scopeOfRun(options.testPath ?? currentTestPath());
|
|
79
|
+
|
|
80
|
+
// One entry per announcement, in order. `Emissions.announce` calls the carrier for
|
|
81
|
+
// every fact, so this sees them all — including those nobody in this process listens to.
|
|
82
|
+
const heard: { fact: string; payload: unknown }[] = [];
|
|
83
|
+
|
|
84
|
+
const app = await boot({
|
|
85
|
+
onEmit: (fact, payload) => { heard.push({ fact, payload }); },
|
|
86
|
+
root: options.root ?? scope?.root,
|
|
87
|
+
createContainer,
|
|
88
|
+
fronds: options.fronds ?? (scope?.frond ? [scope.frond] : undefined),
|
|
89
|
+
// `boot` merges this over the file, so a project declaring a real database still
|
|
90
|
+
// gets the in-memory one here.
|
|
91
|
+
config: options.topology ? undefined : { remotes: {} },
|
|
92
|
+
db: () => resolveStorage(db),
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
const doubles = installStubs(app, options.stub ?? []);
|
|
96
|
+
return Object.assign(app, {
|
|
97
|
+
announced(fact: { name: string } | string): unknown[] {
|
|
98
|
+
// A fact travels under its REGISTRATION key — `postPublished`, not `PostPublished`
|
|
99
|
+
// — the same lowering every entity gets. Both spellings are accepted here and
|
|
100
|
+
// lowered before comparing, so a caller may hand in the class or the name.
|
|
101
|
+
const wanted = lowerFirst(typeof fact === 'string' ? fact : fact.name);
|
|
102
|
+
return heard.filter((one) => lowerFirst(one.fact) === wanted).map((one) => one.payload);
|
|
103
|
+
},
|
|
104
|
+
stub<T>(port: abstract new (...args: never[]) => T): Stub<T> {
|
|
105
|
+
const found = doubles.get(port as Port);
|
|
106
|
+
if (!found) {
|
|
107
|
+
throw new Error(
|
|
108
|
+
`[stub] ${(port as Port).name} was not stubbed — name it: testApp({ stub: [${(port as Port).name}] }).`,
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
return found as Stub<T>;
|
|
112
|
+
},
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Vitest's own answer to "which file is running", or nothing.
|
|
118
|
+
*
|
|
119
|
+
* Imported dynamically: a package that imports vitest at the top level stops being
|
|
120
|
+
* loadable outside a test run, and `testApp` is meant to work under any host.
|
|
121
|
+
*/
|
|
122
|
+
function currentTestPath(): string | undefined {
|
|
123
|
+
const globals = globalThis as { __vitest_worker__?: { filepath?: string } };
|
|
124
|
+
return globals.__vitest_worker__?.filepath;
|
|
125
|
+
}
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import { createLocalRunner, type App } from '@fougere/core';
|
|
3
|
+
import { EMPTY_INVOCATION } from '@fougere/core/contract';
|
|
4
|
+
import { serveRest, serveRpc, tableOf } from '@fougere/app';
|
|
5
|
+
import { lowerFirst, type SchemaView } from '@fougere/schema';
|
|
6
|
+
import { listQuery, findQuery, mutationFor, at } from './gql.js';
|
|
7
|
+
import { sampleInput, type SampleOptions } from './sample.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The rows a door hands back, with its own envelope taken off.
|
|
11
|
+
*
|
|
12
|
+
* Each door wraps differently by construction — REST answers a page, GraphQL nests under
|
|
13
|
+
* its field, RPC returns the value — and comparing the wrappers would compare the
|
|
14
|
+
* protocols. What must agree is what is inside.
|
|
15
|
+
*/
|
|
16
|
+
function rowsOf(value: unknown): unknown {
|
|
17
|
+
if (Array.isArray(value)) return [...value];
|
|
18
|
+
const page = value as { items?: unknown } | null;
|
|
19
|
+
return page && typeof page === 'object' && 'items' in page ? page.items : value;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Through the wire and back, so a `Date` and its ISO string are not read as a divergence. */
|
|
23
|
+
const wire = (value: unknown): unknown => JSON.parse(JSON.stringify(value ?? null));
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* What is the SAME row seen twice, and what is merely a second row.
|
|
27
|
+
*
|
|
28
|
+
* A write creates a different row at each door — different id, different `createdAt` —
|
|
29
|
+
* so comparing values would compare clocks. The generated fields are dropped and what the
|
|
30
|
+
* caller sent is what remains, which is the part the doors must agree on.
|
|
31
|
+
*/
|
|
32
|
+
function written(value: unknown, sent: Record<string, unknown>): unknown {
|
|
33
|
+
const row = value as Record<string, unknown> | null;
|
|
34
|
+
if (!row || typeof row !== 'object') return wire(row);
|
|
35
|
+
return wire(Object.fromEntries(Object.keys(sent).map((key) => [key, row[key]])));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface DoorOptions extends SampleOptions {
|
|
39
|
+
given?: Record<string, unknown>;
|
|
40
|
+
/** The audience, when the app serves named surfaces. */
|
|
41
|
+
surface?: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
interface Doors {
|
|
45
|
+
local: (op: string, input?: DoorInput) => Promise<unknown>;
|
|
46
|
+
rpc: (op: string, input?: DoorInput) => Promise<unknown>;
|
|
47
|
+
rest: (op: string, input?: DoorInput) => Promise<unknown>;
|
|
48
|
+
graphql: (op: string, input?: DoorInput) => Promise<unknown>;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface DoorInput { id?: string; body?: Record<string, unknown> }
|
|
52
|
+
|
|
53
|
+
export interface DoorContractCase {
|
|
54
|
+
/** What this case proves — becomes the test name. */
|
|
55
|
+
name: string;
|
|
56
|
+
/** Any declared operation, CRUD or custom. */
|
|
57
|
+
operation: string;
|
|
58
|
+
input?: DoorInput;
|
|
59
|
+
/** The protocol envelopes are removed before this value is compared. */
|
|
60
|
+
expected: unknown;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* One entity, four doors, the same answers.
|
|
65
|
+
*
|
|
66
|
+
* The claim runs through the whole repo — a frond runs in-process or behind JSON-RPC with
|
|
67
|
+
* identical user code, and REST, GraphQL and RPC are three projections of one contract —
|
|
68
|
+
* and nothing compared REST to GraphQL until now. `transport-swap.test.ts` compares three
|
|
69
|
+
* TRANSPORTS, which is a different sentence.
|
|
70
|
+
*
|
|
71
|
+
* The five CRUD operations, reads and writes. A CUSTOM op is not compared: REST addresses
|
|
72
|
+
* it by a path the table states, GraphQL by a mutation whose input type is its own, and
|
|
73
|
+
* matching the two means guessing which is which — a guess this file exists to avoid.
|
|
74
|
+
*/
|
|
75
|
+
export function checkDoors(app: App, entity: SchemaView, options: DoorOptions = {}): void {
|
|
76
|
+
const name = lowerFirst(entity.name ?? '');
|
|
77
|
+
const doors = doorsOf(app, entity, name, options.surface);
|
|
78
|
+
const bodyOf = () => sampleInput(entity, options.given ?? {}, options);
|
|
79
|
+
|
|
80
|
+
describe(`${entity.name} — the doors agree`, () => {
|
|
81
|
+
it('on create, over what the caller sent', async () => {
|
|
82
|
+
const sent = bodyOf();
|
|
83
|
+
const answers = await Promise.all(
|
|
84
|
+
(['local', 'rpc', 'rest', 'graphql'] as const).map((door) => doors[door]('create', { body: sent })),
|
|
85
|
+
);
|
|
86
|
+
|
|
87
|
+
const [local, ...others] = answers.map((answer) => written(answer, sent));
|
|
88
|
+
for (const [index, other] of others.entries()) {
|
|
89
|
+
expect(other, `${(['rpc', 'rest', 'graphql'] as const)[index]} ≠ local`).toEqual(local);
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it('on list', async () => {
|
|
94
|
+
await doors.local('create', { body: bodyOf() });
|
|
95
|
+
|
|
96
|
+
const local = wire(rowsOf(await doors.local('list')));
|
|
97
|
+
expect(Array.isArray(local) && local.length > 0, 'nothing to compare').toBe(true);
|
|
98
|
+
|
|
99
|
+
expect(wire(rowsOf(await doors.rpc('list'))), 'rpc ≠ local').toEqual(local);
|
|
100
|
+
expect(wire(rowsOf(await doors.rest('list'))), 'rest ≠ local').toEqual(local);
|
|
101
|
+
expect(wire(rowsOf(await doors.graphql('list'))), 'graphql ≠ local').toEqual(local);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it('on findById', async () => {
|
|
105
|
+
const row = await doors.local('create', { body: bodyOf() }) as { id: string };
|
|
106
|
+
|
|
107
|
+
const local = wire(await doors.local('findById', { id: row.id }));
|
|
108
|
+
|
|
109
|
+
expect(wire(await doors.rpc('findById', { id: row.id })), 'rpc ≠ local').toEqual(local);
|
|
110
|
+
expect(wire(await doors.rest('findById', { id: row.id })), 'rest ≠ local').toEqual(local);
|
|
111
|
+
expect(wire(await doors.graphql('findById', { id: row.id })), 'graphql ≠ local').toEqual(local);
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
it('on update, over what the caller sent', async () => {
|
|
115
|
+
const rows = await Promise.all([1, 2, 3, 4].map(() => doors.local('create', { body: bodyOf() }))) as { id: string }[];
|
|
116
|
+
const patch = bodyOf();
|
|
117
|
+
|
|
118
|
+
const answers = await Promise.all(
|
|
119
|
+
(['local', 'rpc', 'rest', 'graphql'] as const)
|
|
120
|
+
.map((door, index) => doors[door]('update', { id: rows[index].id, body: patch })),
|
|
121
|
+
);
|
|
122
|
+
|
|
123
|
+
const [local, ...others] = answers.map((answer) => written(answer, patch));
|
|
124
|
+
for (const [index, other] of others.entries()) {
|
|
125
|
+
expect(other, `${(['rpc', 'rest', 'graphql'] as const)[index]} ≠ local`).toEqual(local);
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
it('on delete', async () => {
|
|
130
|
+
const rows = await Promise.all([1, 2, 3, 4].map(() => doors.local('create', { body: bodyOf() }))) as { id: string }[];
|
|
131
|
+
|
|
132
|
+
const answers = await Promise.all(
|
|
133
|
+
(['local', 'rpc', 'rest', 'graphql'] as const).map((door, index) => doors[door]('delete', { id: rows[index].id })),
|
|
134
|
+
);
|
|
135
|
+
|
|
136
|
+
// REST answers a deletion with no content at all, which is the protocol saying yes.
|
|
137
|
+
const said = answers.map((answer) => (answer === undefined || answer === null ? true : wire(answer)));
|
|
138
|
+
expect(new Set(said).size, `the doors disagree: ${JSON.stringify(said)}`).toBe(1);
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
it('on a refusal', async () => {
|
|
142
|
+
// A refusal is where the doors diverge most, and where each is most tempted to
|
|
143
|
+
// answer in its own words. What must match is that it WAS refused.
|
|
144
|
+
const bad = { ...bodyOf(), __unknown__: 'x' };
|
|
145
|
+
const refusals = await Promise.all(
|
|
146
|
+
(['local', 'rpc', 'rest', 'graphql'] as const).map((door) => refused(() => doors[door]('create', { body: bad }))),
|
|
147
|
+
);
|
|
148
|
+
|
|
149
|
+
expect(refusals[0], 'local accepted a body outside the contract').toBe(true);
|
|
150
|
+
expect(refusals, `the doors disagree: ${JSON.stringify(refusals)}`).toEqual([true, true, true, true]);
|
|
151
|
+
});
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Run one hand-written invocation contract through every door.
|
|
157
|
+
*
|
|
158
|
+
* `checkDoors` derives the generic CRUD gradient. This is its small explicit companion
|
|
159
|
+
* for semantics only the handler can observe — notably omitted versus null input. A new
|
|
160
|
+
* adapter joins the same harness instead of inventing its own interpretation.
|
|
161
|
+
*/
|
|
162
|
+
export function checkDoorContract(
|
|
163
|
+
app: App,
|
|
164
|
+
entity: SchemaView,
|
|
165
|
+
cases: readonly DoorContractCase[],
|
|
166
|
+
options: Pick<DoorOptions, 'surface'> = {},
|
|
167
|
+
): void {
|
|
168
|
+
const name = lowerFirst(entity.name ?? '');
|
|
169
|
+
const doors = doorsOf(app, entity, name, options.surface);
|
|
170
|
+
const names = ['local', 'rpc', 'rest', 'graphql'] as const;
|
|
171
|
+
|
|
172
|
+
describe(`${entity.name} — its invocation contract crosses every door`, () => {
|
|
173
|
+
for (const one of cases) {
|
|
174
|
+
it(one.name, async () => {
|
|
175
|
+
const answers = await Promise.all(names.map((door) => doors[door](one.operation, one.input)));
|
|
176
|
+
for (const [index, answer] of answers.entries()) {
|
|
177
|
+
expect(wire(answer), `${names[index]} disagrees with the canonical invocation`).toEqual(wire(one.expected));
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
async function refused(call: () => Promise<unknown>): Promise<boolean> {
|
|
185
|
+
try { await call(); return false; } catch { return true; }
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** The four doors, each reduced to `(op, input) => answer` so the tests above read alike. */
|
|
189
|
+
function doorsOf(app: App, entity: SchemaView, name: string, surface?: string): Doors {
|
|
190
|
+
const run = createLocalRunner(app, surface);
|
|
191
|
+
const state: Record<string, unknown> = {};
|
|
192
|
+
|
|
193
|
+
const invocation = (input: DoorInput = {}) => ({
|
|
194
|
+
...EMPTY_INVOCATION,
|
|
195
|
+
...(input.id !== undefined ? { params: { id: input.id } } : {}),
|
|
196
|
+
...(input.body !== undefined ? { body: input.body } : {}),
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
return {
|
|
200
|
+
local: (op, input) => run({ entity: name, op }, invocation(input)),
|
|
201
|
+
|
|
202
|
+
rpc: async (op, input) => {
|
|
203
|
+
const answer = await serveRpc(app, {
|
|
204
|
+
path: '',
|
|
205
|
+
body: { jsonrpc: '2.0', id: 1, method: `${name}.${op}`, params: invocation(input) },
|
|
206
|
+
state,
|
|
207
|
+
}) as { result?: unknown; error?: { message: string } };
|
|
208
|
+
if (answer.error) throw new Error(answer.error.message);
|
|
209
|
+
return answer.result;
|
|
210
|
+
},
|
|
211
|
+
|
|
212
|
+
rest: async (op, input) => {
|
|
213
|
+
// The route the REST door itself would match, read from its own table — rebuilding
|
|
214
|
+
// the path here would be a second opinion on where an entity lives.
|
|
215
|
+
const route = tableOf(app).find((one) => one.entityName === name && one.operationName === op);
|
|
216
|
+
if (!route) throw new Error(`[checkDoors] REST serves no ${name}.${op}`);
|
|
217
|
+
const path = route.segments.map((segment) => (segment.startsWith(':') ? input?.id ?? '' : segment)).join('/');
|
|
218
|
+
|
|
219
|
+
const answer = await serveRest(app, { method: route.method, path, query: {}, body: input?.body, state });
|
|
220
|
+
if (answer.kind !== 'ok') throw new Error(`[checkDoors] REST answered ${answer.kind} on ${name}.${op}`);
|
|
221
|
+
return answer.body;
|
|
222
|
+
},
|
|
223
|
+
|
|
224
|
+
graphql: async (op, input) => {
|
|
225
|
+
const { executeOn, schemaOf } = await import('@fougere/adapter-graphql');
|
|
226
|
+
const schema = schemaOf(app as never) as never;
|
|
227
|
+
const built = op === 'list' ? listQuery(schema, entity)
|
|
228
|
+
: op === 'findById' ? findQuery(schema, entity, input?.id ?? '')
|
|
229
|
+
: mutationFor(schema, entity, op, { id: input?.id, body: input?.body });
|
|
230
|
+
if (!built) throw new Error(`[checkDoors] GraphQL serves no ${entity.name} ${op}`);
|
|
231
|
+
|
|
232
|
+
const answer = await executeOn(app as never, { query: built.query, state });
|
|
233
|
+
if (answer.errors?.length) throw new Error(`[checkDoors] GraphQL: ${answer.errors[0].message}`);
|
|
234
|
+
return at(answer.data, built.at);
|
|
235
|
+
},
|
|
236
|
+
};
|
|
237
|
+
}
|
package/src/derive.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { Cases, type Case } from '@fougere/schema';
|
|
2
|
+
import type { SchemaView } from '@fougere/schema';
|
|
3
|
+
import { sampleInput, type SampleOptions } from './sample.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The cases, with the valid body generated rather than handed in.
|
|
7
|
+
*
|
|
8
|
+
* `Cases` lives in `@fougere/schema` because deriving them reads the four axes and
|
|
9
|
+
* nothing else. This is the half that needs a generator, which is why it is here: a
|
|
10
|
+
* 426 KB faker has no business in the package a browser loads.
|
|
11
|
+
*/
|
|
12
|
+
export function derivedCases(
|
|
13
|
+
entity: SchemaView,
|
|
14
|
+
given: Record<string, unknown> = {},
|
|
15
|
+
options: SampleOptions = {},
|
|
16
|
+
): readonly Case[] {
|
|
17
|
+
return Cases.of(entity, sampleInput(entity, given, options)).all;
|
|
18
|
+
}
|
package/src/doors.ts
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import { createLocalRunner, validationErrorsOf, type App } from '@fougere/core';
|
|
3
|
+
import { EMPTY_INVOCATION } from '@fougere/core/contract';
|
|
4
|
+
import { lowerFirst, Visibility, type SchemaView, type ValidationError } from '@fougere/schema';
|
|
5
|
+
import { Cases } from '@fougere/schema';
|
|
6
|
+
import { derivedCases } from './derive.js';
|
|
7
|
+
import { sampleInput, replaySeed, type SampleOptions } from './sample.js';
|
|
8
|
+
|
|
9
|
+
/** The one shape both the local judge and a door already speak. */
|
|
10
|
+
export interface Verdict {
|
|
11
|
+
success: boolean;
|
|
12
|
+
errors?: ValidationError[];
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* What a door answers, in the shape a verdict is compared in.
|
|
17
|
+
*
|
|
18
|
+
* A refusal reaches a caller as a thrown `FougereError` carrying `details`, not as a
|
|
19
|
+
* returned value — so the translation happens once, here, and every reader below compares
|
|
20
|
+
* the same thing.
|
|
21
|
+
*/
|
|
22
|
+
export async function verdictOf(call: () => Promise<unknown>): Promise<Verdict> {
|
|
23
|
+
try {
|
|
24
|
+
await call();
|
|
25
|
+
return { success: true };
|
|
26
|
+
} catch (error) {
|
|
27
|
+
const refusals = validationErrorsOf(error);
|
|
28
|
+
if (!refusals) throw error;
|
|
29
|
+
return { success: false, errors: refusals };
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function opsFor(entity: SchemaView): { create: string; update: string; name: string } {
|
|
34
|
+
const name = lowerFirst(entity.name ?? '');
|
|
35
|
+
return { name, create: 'create', update: 'update' };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface CheckOptions extends SampleOptions {
|
|
39
|
+
/** Values the generator cannot invent — the id of a row a `ref()` points at. */
|
|
40
|
+
given?: Record<string, unknown>;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The declared contract, posed to the façade that will receive it.
|
|
45
|
+
*
|
|
46
|
+
* Declares one `it` per case rather than looping inside a single one: a failure names the
|
|
47
|
+
* case, and a suite that lists what it checked is the point — the list comes from the
|
|
48
|
+
* entity, not from what the author remembered.
|
|
49
|
+
*/
|
|
50
|
+
export function checkContract(app: App, entity: SchemaView, options: CheckOptions = {}): void {
|
|
51
|
+
const { name, create, update } = opsFor(entity);
|
|
52
|
+
const run = createLocalRunner(app);
|
|
53
|
+
const table = derivedCases(entity, options.given ?? {}, options);
|
|
54
|
+
|
|
55
|
+
describe(`${entity.name} — the contract it declares`, () => {
|
|
56
|
+
for (const one of table) {
|
|
57
|
+
it(one.why, async () => {
|
|
58
|
+
const verdict = await verdictOf(() => run(
|
|
59
|
+
{ entity: name, op: one.patch ? update : create },
|
|
60
|
+
{ ...EMPTY_INVOCATION, params: one.patch ? { id: '__absent__' } : {}, body: one.body },
|
|
61
|
+
));
|
|
62
|
+
|
|
63
|
+
expect(Cases.holds(one.expect, verdict), `${JSON.stringify(verdict)} — replay: ${replaySeed()}`).toBe(true);
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* What may leave, checked against what the entity says may leave.
|
|
71
|
+
*
|
|
72
|
+
* Costs nothing to state: `Visibility.output` already answers it, and a field the boundary
|
|
73
|
+
* closes has no business in any response. A `password: text({ boundary: 'writeOnly' })`
|
|
74
|
+
* that reaches a caller is the one leak no reviewer catches by reading a handler.
|
|
75
|
+
*/
|
|
76
|
+
export function checkOutput(app: App, entity: SchemaView, options: CheckOptions = {}): void {
|
|
77
|
+
const { name, create } = opsFor(entity);
|
|
78
|
+
const run = createLocalRunner(app);
|
|
79
|
+
const allowed = new Set(Object.keys(Visibility.of(entity.getFields()).output));
|
|
80
|
+
const closed = Object.keys(entity.getFields()).filter((field) => !allowed.has(field));
|
|
81
|
+
|
|
82
|
+
describe(`${entity.name} — what leaves it`, () => {
|
|
83
|
+
it(closed.length > 0 ? `keeps ${closed.join(', ')} in` : 'closes no field, and says so', async () => {
|
|
84
|
+
const row = await run(
|
|
85
|
+
{ entity: name, op: create },
|
|
86
|
+
{ ...EMPTY_INVOCATION, body: sampleInput(entity, options.given ?? {}, options) },
|
|
87
|
+
) as Record<string, unknown>;
|
|
88
|
+
|
|
89
|
+
expect(Object.keys(row).filter((field) => closed.includes(field))).toEqual([]);
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it('answers with fields the entity declares, and no others', async () => {
|
|
93
|
+
const row = await run(
|
|
94
|
+
{ entity: name, op: create },
|
|
95
|
+
{ ...EMPTY_INVOCATION, body: sampleInput(entity, options.given ?? {}, options) },
|
|
96
|
+
) as Record<string, unknown>;
|
|
97
|
+
|
|
98
|
+
// A computed field from a presenter is declared by the presenter, not the entity,
|
|
99
|
+
// so this reads the entity's own names as a floor rather than a ceiling.
|
|
100
|
+
expect(Object.keys(row).every((field) => field in entity.getFields())).toBe(true);
|
|
101
|
+
});
|
|
102
|
+
});
|
|
103
|
+
}
|