@ultimat3/testing 30.9.0 → 31.1.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/CLAUDE.md +46 -55
- package/README.md +179 -39
- package/package.json +23 -17
- package/src/ai-conformance-answer.ts +67 -0
- package/src/ai-gateway-conformance.ts +105 -0
- package/src/ai-provider-conformance.ts +69 -0
- package/src/ai-provider-transport-conformance.ts +170 -0
- package/src/audit-sink-conformance.ts +204 -0
- package/src/auth-adapter-conformance-credentials.ts +124 -0
- package/src/auth-adapter-conformance-mfa.ts +70 -0
- package/src/auth-adapter-conformance-passkeys.ts +133 -0
- package/src/auth-adapter-conformance-sessions.ts +115 -0
- package/src/auth-adapter-conformance-support.ts +71 -0
- package/src/auth-adapter-conformance-users.ts +128 -0
- package/src/auth-adapter-conformance.ts +34 -0
- package/src/auth-limiter-factory-conformance.ts +224 -0
- package/src/auth-server-store-conformance-records.ts +69 -0
- package/src/auth-server-store-conformance.ts +208 -0
- package/src/cache-tier-conformance-checks.ts +142 -0
- package/src/cache-tier-conformance.ts +24 -0
- package/src/cassette-format.ts +8 -13
- package/src/cassette-record.ts +1 -1
- package/src/cdp-browser.ts +10 -11
- package/src/cdp-e2e-page.ts +2 -2
- package/src/cdp-e2e-session.ts +2 -2
- package/src/cdp-network-probe.ts +1 -1
- package/src/cdp-offline-script.ts +2 -2
- package/src/clock-conformance.ts +126 -0
- package/src/conformance.ts +239 -0
- package/src/e2e-browser-handle.ts +1 -2
- package/src/e2e-error-codes.ts +17 -16
- package/src/e2e-run.ts +4 -3
- package/src/embedder-conformance.ts +101 -0
- package/src/entity-conformance-aggregates.ts +210 -0
- package/src/entity-conformance-batches.ts +216 -0
- package/src/entity-conformance-bulk.ts +379 -0
- package/src/entity-conformance-checks.ts +27 -0
- package/src/entity-conformance-entities.ts +52 -0
- package/src/entity-conformance-locks.ts +286 -0
- package/src/entity-conformance-matrix.ts +397 -0
- package/src/entity-conformance-reads.ts +241 -0
- package/src/entity-conformance-support.ts +56 -0
- package/src/entity-conformance-tenancy.ts +296 -0
- package/src/entity-conformance-values.ts +305 -0
- package/src/entity-conformance-versions.ts +60 -0
- package/src/entity-conformance-writes.ts +348 -0
- package/src/entity-driver-conformance.ts +103 -0
- package/src/error-groups-store-conformance.ts +198 -0
- package/src/error-reporter-conformance.ts +119 -0
- package/src/errors.ts +20 -2
- package/src/event-bus-conformance.ts +161 -0
- package/src/exercise-drift-hint.ts +4 -1
- package/src/exercise-judge.ts +5 -3
- package/src/exercise-override-line.ts +98 -0
- package/src/exercise-report.ts +138 -115
- package/src/exercise-room-mail.ts +40 -0
- package/src/exercise.ts +33 -29
- package/src/factories.ts +192 -179
- package/src/factory-api.ts +131 -0
- package/src/factory-associations.ts +67 -0
- package/src/factory-errors.ts +38 -0
- package/src/factory-lint.ts +92 -0
- package/src/factory-persist.ts +74 -16
- package/src/factory-pipeline.ts +191 -0
- package/src/factory-registry.ts +2 -1
- package/src/factory-types.ts +131 -0
- package/src/failure-store-conformance.ts +137 -0
- package/src/fixture-jobs.ts +27 -11
- package/src/fixture-mail.ts +7 -7
- package/src/fixture-seed.ts +111 -0
- package/src/fixture-statements.ts +68 -52
- package/src/framework-fixtures.ts +1 -1
- package/src/idempotency-store-conformance.ts +186 -0
- package/src/idempotency-store-replay-conformance.ts +140 -0
- package/src/idempotency-store-tx-conformance.ts +132 -0
- package/src/idempotency-store-world-conformance.ts +82 -0
- package/src/identity-provider-conformance.ts +144 -0
- package/src/image-transform-conformance.ts +89 -0
- package/src/index.ts +68 -157
- package/src/isr-store-conformance.ts +113 -0
- package/src/job-sim-effects.ts +19 -31
- package/src/job-sim-world.ts +6 -15
- package/src/lease-store-conformance.ts +195 -0
- package/src/mail-driver-conformance.ts +108 -0
- package/src/matcher-doubles.ts +104 -0
- package/src/matcher-stub.ts +78 -0
- package/src/matcher-surface.ts +21 -0
- package/src/matchers.ts +19 -1
- package/src/mcp-confirmation-store-conformance.ts +262 -0
- package/src/meter-store-conformance.ts +135 -0
- package/src/notify-digest-conformance.ts +133 -0
- package/src/notify-inbox-conformance.ts +130 -0
- package/src/notify-ledger-conformance.ts +134 -0
- package/src/notify-preference-conformance.ts +49 -0
- package/src/notify-stores-conformance.ts +73 -0
- package/src/outbox-store-conformance-claims.ts +112 -0
- package/src/outbox-store-conformance-subject.ts +65 -0
- package/src/outbox-store-conformance.ts +71 -0
- package/src/per-test-reset.ts +55 -20
- package/src/preload.ts +4 -2
- package/src/purge-conformance.ts +79 -0
- package/src/push-device-conformance.ts +124 -0
- package/src/push-subscription-conformance.ts +123 -0
- package/src/quiet-logs.ts +4 -4
- package/src/rate-limit-store-conformance.ts +178 -0
- package/src/registry-leak-error.ts +8 -1
- package/src/scale-sweep-run.ts +6 -9
- package/src/scrape-driver-conformance-frame-checks.ts +97 -0
- package/src/scrape-driver-conformance-page-checks.ts +114 -0
- package/src/scrape-driver-conformance-site.ts +84 -0
- package/src/scrape-driver-conformance.ts +34 -0
- package/src/sealed-network.ts +20 -2
- package/src/search-index-conformance-list.ts +76 -0
- package/src/search-index-conformance-support.ts +69 -0
- package/src/search-index-conformance-versions.ts +66 -0
- package/src/search-index-conformance.ts +126 -0
- package/src/secret-source-conformance.ts +91 -0
- package/src/seed-factories.ts +57 -0
- package/src/seed-writer.ts +8 -19
- package/src/semantic-cache-factory-conformance.ts +86 -0
- package/src/sms-transport-conformance.ts +102 -0
- package/src/step-store-conformance.ts +171 -0
- package/src/storage-conformance-read-checks.ts +132 -0
- package/src/storage-conformance-shape.ts +121 -0
- package/src/storage-conformance-stream-checks.ts +226 -0
- package/src/storage-conformance.ts +34 -0
- package/src/stub-action.ts +24 -0
- package/src/stub-errors.ts +86 -0
- package/src/stub-job.ts +30 -0
- package/src/stub-query.ts +25 -0
- package/src/stub-script.ts +76 -0
- package/src/stub-stack.ts +29 -0
- package/src/stub.ts +73 -0
- package/src/swap-adapter.ts +135 -0
- package/src/test-scope.ts +96 -0
- package/src/test-types.ts +1 -1
- package/src/totp-replay-guard-conformance.ts +76 -0
- package/src/transport-conformance.ts +179 -0
- package/src/upload-scanner-conformance.ts +112 -0
- package/src/vector-store-conformance-checks.ts +174 -0
- package/src/vector-store-conformance.ts +21 -0
- package/src/cdp-connection.ts +0 -291
- package/src/cdp-errors.ts +0 -179
- package/src/cdp-launch-attempt.ts +0 -224
- package/src/cdp-launch-candidates.ts +0 -62
- package/src/cdp-launch-profile.ts +0 -106
- package/src/cdp-launch-reap.ts +0 -68
- package/src/cdp-launch-wire.ts +0 -171
- package/src/cdp-launch.ts +0 -175
- package/src/cdp-pipe.ts +0 -77
- package/src/cdp-wire-watch.ts +0 -113
package/src/factories.ts
CHANGED
|
@@ -1,208 +1,221 @@
|
|
|
1
|
-
// Typed factories
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
// Traits and associations are FactoryBot's two, and only its two: a trait is a named partial the
|
|
6
|
-
// caller composes, an association is a column whose value comes from another factory built with
|
|
7
|
-
// the SAME strategy — `build()` leaves the parent in memory, `create()` writes it.
|
|
1
|
+
// Typed factories over an entity: FactoryBot's strategies, traits, transients, callbacks,
|
|
2
|
+
// inheritance and associations, with seeded values so two runs of a suite produce byte-identical
|
|
3
|
+
// rows. The row pipeline is `factory-pipeline.ts`; this file holds the sequence and the strategies.
|
|
8
4
|
|
|
9
5
|
import { fnv1a } from '@ultimat3/core';
|
|
10
6
|
import { seededRandom, seededUuid } from './determinism';
|
|
11
7
|
import { FactoryTraitUnknownError } from './errors';
|
|
8
|
+
import type { Factory, FactoryExtension, FactoryOptions } from './factory-api';
|
|
12
9
|
import { persistRow } from './factory-persist';
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
/** The seeded generators a `defaults` or trait body draws from. Never `Math.random` directly. */
|
|
24
|
-
export interface FactoryIds {
|
|
25
|
-
uuid(): string;
|
|
26
|
-
number(): number;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
/** A named partial. A function form gets the row's index and the same seeded generators. */
|
|
30
|
-
export type Trait<TRow> = Partial<TRow> | ((index: number, ids: FactoryIds) => Partial<TRow>);
|
|
31
|
-
|
|
32
|
-
export type TraitMap<TRow> = Readonly<Record<string, Trait<TRow>>>;
|
|
33
|
-
|
|
34
|
-
/**
|
|
35
|
-
* A column filled from another factory. Opaque on purpose: `associate()` captures the parent
|
|
36
|
-
* factory and the column to lift off it, so the map below stays exactly typed per column with no
|
|
37
|
-
* variance escape hatch.
|
|
38
|
-
*/
|
|
39
|
-
export interface Association<TValue> {
|
|
40
|
-
build(): TValue;
|
|
41
|
-
create(): Promise<TValue>;
|
|
42
|
-
/** Cascades from the child's `reset()`: a half-reset row is not the row the first block saw. */
|
|
43
|
-
reset(): void;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
export type AssociationMap<TRow> = { readonly [K in keyof TRow]?: Association<TRow[K]> };
|
|
47
|
-
|
|
48
|
-
/**
|
|
49
|
-
* `associate(orgs, (org) => org.id)` — the parent is built with the strategy the child is built
|
|
50
|
-
* with, which is the whole reason associations are not just another default: `create()` on a post
|
|
51
|
-
* has to leave an org row behind it, and `build()` must not touch a database at all.
|
|
52
|
-
*/
|
|
53
|
-
export function associate<TParent extends object, TValue>(
|
|
54
|
-
parent: Factory<TParent>,
|
|
55
|
-
pick: (row: TParent) => TValue,
|
|
56
|
-
): Association<TValue> {
|
|
57
|
-
return {
|
|
58
|
-
build: () => pick(parent.build()),
|
|
59
|
-
create: async () => pick(await parent.create()),
|
|
60
|
-
reset: () => parent.reset(),
|
|
61
|
-
};
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
export interface FactoryOptions<TRow, TTraits extends TraitMap<TRow> = TraitMap<TRow>> {
|
|
65
|
-
/** Omitted means "derived from the table name" — see `seedFor`. */
|
|
66
|
-
readonly seed?: number;
|
|
67
|
-
/** Values for every column the entity requires; called once per built row. */
|
|
68
|
-
defaults(index: number, ids: FactoryIds): TRow;
|
|
69
|
-
readonly traits?: TTraits;
|
|
70
|
-
/**
|
|
71
|
-
* `NoInfer`, because `AssociationMap<TRow>` is homomorphic over `keyof TRow` and TypeScript
|
|
72
|
-
* reverse-maps it into an inference candidate: a factory declaring `associations: { orgId }`
|
|
73
|
-
* inferred `TRow = { orgId: string }` and silently dropped every other column from `build()`,
|
|
74
|
-
* `Partial<TRow>` overrides and `Trait<TRow>`. Associations are a SUBSET of the columns by
|
|
75
|
-
* construction, so they can never be a correct source for the row type — `defaults` is, and it
|
|
76
|
-
* is the one member required to name every column.
|
|
77
|
-
*/
|
|
78
|
-
readonly associations?: AssociationMap<NoInfer<TRow>>;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
export interface Factory<TRow, TTrait extends string = string> {
|
|
82
|
-
readonly table: string;
|
|
83
|
-
/** The declared trait names, sorted — what a failure lists and what a test can assert on. */
|
|
84
|
-
readonly traits: readonly TTrait[];
|
|
85
|
-
build(over?: Partial<TRow>): TRow;
|
|
86
|
-
buildMany(count: number, over?: Partial<TRow>): readonly TRow[];
|
|
87
|
-
/** Build, resolve associations by creating their parents, and write through the persister. */
|
|
88
|
-
create(over?: Partial<TRow>): Promise<TRow>;
|
|
89
|
-
createMany(count: number, over?: Partial<TRow>): Promise<readonly TRow[]>;
|
|
90
|
-
/** A view with those traits applied, sharing this factory's sequence so ids never repeat. */
|
|
91
|
-
with(...traits: readonly TTrait[]): Factory<TRow, TTrait>;
|
|
92
|
-
/** Restart the sequence so a second describe block sees the same ids as the first. */
|
|
93
|
-
reset(): void;
|
|
94
|
-
}
|
|
10
|
+
import { attributesOf, type FactorySpec, rowSteps, type Step } from './factory-pipeline';
|
|
11
|
+
import type {
|
|
12
|
+
BelongsToMap,
|
|
13
|
+
EntityLike,
|
|
14
|
+
FactoryIds,
|
|
15
|
+
HasManyMap,
|
|
16
|
+
None,
|
|
17
|
+
StoredOf,
|
|
18
|
+
TraitMap,
|
|
19
|
+
} from './factory-types';
|
|
95
20
|
|
|
96
21
|
/**
|
|
97
22
|
* Two factories with the same seed emit the same uuids, so a default of `1` everywhere gave a user
|
|
98
23
|
* and a post the same id — rows that only look related. Core's FNV-1a over the table name keeps
|
|
99
|
-
* every table on its own stream while staying a pure function of the schema
|
|
100
|
-
* identical run to run and machine to machine.
|
|
24
|
+
* every table on its own stream while staying a pure function of the schema.
|
|
101
25
|
*/
|
|
102
26
|
export function seedFor(table: string): number {
|
|
103
27
|
const hash = fnv1a(table);
|
|
104
28
|
return hash === 0 ? 1 : hash;
|
|
105
29
|
}
|
|
106
30
|
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
// Erased to one shape for iteration; the public `AssociationMap` already held each entry to its
|
|
116
|
-
// own column's type, so the value at key K is an `Association<TRow[K]>` by construction.
|
|
117
|
-
const links = Object.entries(
|
|
118
|
-
(options.associations ?? {}) as Readonly<Record<string, Association<unknown>>>,
|
|
119
|
-
);
|
|
31
|
+
/** One factory's sequence, shared by every `with()` view and `extend()` child of it. */
|
|
32
|
+
interface Sequence {
|
|
33
|
+
index: number;
|
|
34
|
+
uuid: () => string;
|
|
35
|
+
random: () => number;
|
|
36
|
+
readonly ids: FactoryIds;
|
|
37
|
+
resetting: boolean;
|
|
38
|
+
}
|
|
120
39
|
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
};
|
|
40
|
+
/** Every sequence ever declared: `factorySeed` restarts them all so a replay draws the same ids. */
|
|
41
|
+
const sequences = new Set<{ readonly sequence: Sequence; readonly seed: number }>();
|
|
42
|
+
|
|
43
|
+
export function resetFactorySequences(): void {
|
|
44
|
+
for (const { sequence, seed } of sequences) restart(sequence, seed);
|
|
45
|
+
}
|
|
128
46
|
|
|
47
|
+
const restart = (sequence: Sequence, seed: number): void => {
|
|
48
|
+
sequence.uuid = seededUuid(seed);
|
|
49
|
+
sequence.random = seededRandom(seed);
|
|
50
|
+
sequence.index = 0;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
const drive = (steps: Generator<Step, object, unknown>): object => {
|
|
54
|
+
let next = steps.next();
|
|
55
|
+
while (next.done !== true) {
|
|
56
|
+
const step = next.value;
|
|
57
|
+
// `build()` yields only parents and children: no write and no `afterCreate` is ever asked for.
|
|
58
|
+
next = steps.next(
|
|
59
|
+
step.kind === 'parent' || step.kind === 'child' ? step.factory.build(step.over) : undefined,
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
return next.value;
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
const driveAsync = async (
|
|
66
|
+
entity: EntityLike,
|
|
67
|
+
steps: Generator<Step, object, unknown>,
|
|
68
|
+
): Promise<object> => {
|
|
69
|
+
let next = steps.next();
|
|
70
|
+
while (next.done !== true) {
|
|
71
|
+
const step = next.value;
|
|
72
|
+
// Sequential, never `Promise.all`: two parents made at once would interleave their draws from
|
|
73
|
+
// the seeded generators and the run would stop being reproducible.
|
|
74
|
+
const answer =
|
|
75
|
+
step.kind === 'persist'
|
|
76
|
+
? await persistRow(entity, step.row)
|
|
77
|
+
: step.kind === 'callback'
|
|
78
|
+
? await step.run()
|
|
79
|
+
: await step.factory.create(step.over);
|
|
80
|
+
next = steps.next(answer);
|
|
81
|
+
}
|
|
82
|
+
return next.value;
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
type RuntimeFactory = Factory<object, string, object, object, unknown, unknown>;
|
|
86
|
+
|
|
87
|
+
function view(
|
|
88
|
+
spec: FactorySpec,
|
|
89
|
+
sequence: Sequence,
|
|
90
|
+
seed: number,
|
|
91
|
+
applied: readonly string[],
|
|
92
|
+
): RuntimeFactory {
|
|
93
|
+
const declared = Object.keys(spec.traits).sort();
|
|
94
|
+
const next = (): { index: number; ids: FactoryIds } => {
|
|
95
|
+
sequence.index += 1;
|
|
96
|
+
return { index: sequence.index, ids: sequence.ids };
|
|
97
|
+
};
|
|
129
98
|
// `Object.hasOwn`, not `traits[name] === undefined`: the plain read walked the prototype chain,
|
|
130
|
-
// so `
|
|
131
|
-
// called it with no receiver, got `"[object Undefined]"` and spread a string, producing a row
|
|
132
|
-
// with 18 numeric columns that `create()` then handed to `persistRow`. `f.with('constructor')`
|
|
133
|
-
// was accepted the same way and applied nothing at all.
|
|
99
|
+
// so `with('toString')` applied `Object.prototype.toString` and spread its string into a row.
|
|
134
100
|
const assertTrait = (name: string): string => {
|
|
135
|
-
if (!Object.hasOwn(traits, name)) {
|
|
136
|
-
throw new FactoryTraitUnknownError({ table: entity.$table, trait: name, declared });
|
|
101
|
+
if (!Object.hasOwn(spec.traits, name)) {
|
|
102
|
+
throw new FactoryTraitUnknownError({ table: spec.entity.$table, trait: name, declared });
|
|
137
103
|
}
|
|
138
104
|
return name;
|
|
139
105
|
};
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
over: Partial<TRow>,
|
|
148
|
-
i: number,
|
|
149
|
-
): Partial<TRow> => {
|
|
150
|
-
let patch: Partial<TRow> = {};
|
|
151
|
-
for (const name of applied) {
|
|
152
|
-
const trait = traits[name];
|
|
153
|
-
patch = { ...patch, ...(typeof trait === 'function' ? trait(i, ids) : trait) };
|
|
154
|
-
}
|
|
155
|
-
return { ...patch, ...over };
|
|
156
|
-
};
|
|
157
|
-
|
|
158
|
-
const buildRow = (applied: readonly string[], over: Partial<TRow>): TRow => {
|
|
159
|
-
index += 1;
|
|
160
|
-
const base = options.defaults(index, ids);
|
|
161
|
-
const overrides = overridesOf(applied, over, index);
|
|
162
|
-
const linked: Record<string, unknown> = {};
|
|
163
|
-
for (const [column, link] of links) if (!(column in overrides)) linked[column] = link.build();
|
|
164
|
-
return { ...base, ...(linked as Partial<TRow>), ...overrides };
|
|
165
|
-
};
|
|
166
|
-
|
|
167
|
-
const createRow = async (applied: readonly string[], over: Partial<TRow>): Promise<TRow> => {
|
|
168
|
-
index += 1;
|
|
169
|
-
const base = options.defaults(index, ids);
|
|
170
|
-
const overrides = overridesOf(applied, over, index);
|
|
171
|
-
const linked: Record<string, unknown> = {};
|
|
172
|
-
// Sequential, not `Promise.all`: two parents built concurrently would interleave their draws
|
|
173
|
-
// from the shared seeded generators and the run would stop being reproducible.
|
|
174
|
-
for (const [column, link] of links) {
|
|
175
|
-
if (!(column in overrides)) linked[column] = await link.create();
|
|
176
|
-
}
|
|
177
|
-
const row = { ...base, ...(linked as Partial<TRow>), ...overrides };
|
|
178
|
-
await persistRow(entity.$table, row);
|
|
179
|
-
return row;
|
|
180
|
-
};
|
|
181
|
-
|
|
182
|
-
const view = (applied: readonly string[]): Factory<TRow, Name> => ({
|
|
183
|
-
table: entity.$table,
|
|
106
|
+
const build = (over: object = {}): object =>
|
|
107
|
+
drive(rowSteps(spec, applied, over, 'build', next()));
|
|
108
|
+
const create = (over: object = {}): Promise<object> =>
|
|
109
|
+
driveAsync(spec.entity, rowSteps(spec, applied, over, 'create', next()));
|
|
110
|
+
return {
|
|
111
|
+
entity: spec.entity,
|
|
112
|
+
table: spec.entity.$table,
|
|
184
113
|
traits: declared,
|
|
185
|
-
build
|
|
186
|
-
|
|
187
|
-
create
|
|
188
|
-
|
|
189
|
-
const rows:
|
|
190
|
-
for (let i = 0; i < count; i += 1) rows.push(await
|
|
114
|
+
build,
|
|
115
|
+
buildList: (count, over = {}) => Array.from({ length: count }, () => build(over)),
|
|
116
|
+
create,
|
|
117
|
+
createList: async (count, over = {}) => {
|
|
118
|
+
const rows: object[] = [];
|
|
119
|
+
for (let i = 0; i < count; i += 1) rows.push(await create(over));
|
|
191
120
|
return rows;
|
|
192
121
|
},
|
|
193
|
-
|
|
194
|
-
//
|
|
195
|
-
with: (...names) => view([...applied, ...names.map(assertTrait)]),
|
|
122
|
+
attributesFor: (over = {}) => attributesOf(spec, applied, over, next()),
|
|
123
|
+
// Checked here rather than at build time: `with()` is the line that named the trait.
|
|
124
|
+
with: (...names) => view(spec, sequence, seed, [...applied, ...names.map(assertTrait)]),
|
|
125
|
+
// Erased like every view, and `extend` is generic in what it adds: no erased value names
|
|
126
|
+
// `TMoreTraits`/`TMoreMany`, so the cast is to `never` — `Factory.extend`'s signature states them.
|
|
127
|
+
extend: (extension) => view(extended(spec, extension), sequence, seed, applied) as never,
|
|
196
128
|
reset: () => {
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
129
|
+
// A cycle (post hasMany comments, comment belongsTo post) would reset forever.
|
|
130
|
+
if (sequence.resetting) return;
|
|
131
|
+
sequence.resetting = true;
|
|
132
|
+
try {
|
|
133
|
+
restart(sequence, seed);
|
|
134
|
+
// A half-reset row — own columns replayed, a fresh parent id — is worse than no reset.
|
|
135
|
+
for (const [, link] of spec.belongsTo) link.parent.reset();
|
|
136
|
+
for (const [, link] of spec.hasMany) link.child.reset();
|
|
137
|
+
} finally {
|
|
138
|
+
sequence.resetting = false;
|
|
139
|
+
}
|
|
204
140
|
},
|
|
205
|
-
}
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** The child spec: defaults over the parent's, traits and transients merged, callbacks chained. */
|
|
145
|
+
function extended(
|
|
146
|
+
spec: FactorySpec,
|
|
147
|
+
extension: FactoryExtension<object, unknown, object, object, unknown, unknown>,
|
|
148
|
+
): FactorySpec {
|
|
149
|
+
const { defaults, afterBuild, afterCreate } = extension;
|
|
150
|
+
return {
|
|
151
|
+
...spec,
|
|
152
|
+
defaults: (index, ids, transient) => ({
|
|
153
|
+
...spec.defaults(index, ids, transient),
|
|
154
|
+
...defaults?.(index, ids, transient),
|
|
155
|
+
}),
|
|
156
|
+
traits: { ...spec.traits, ...(extension.traits as FactorySpec['traits'] | undefined) },
|
|
157
|
+
transient: { ...spec.transient, ...extension.transient },
|
|
158
|
+
hasMany: [...spec.hasMany, ...Object.entries((extension.hasMany ?? {}) as HasManyMap)],
|
|
159
|
+
afterBuild: afterBuild === undefined ? spec.afterBuild : [...spec.afterBuild, afterBuild],
|
|
160
|
+
afterCreate: afterCreate === undefined ? spec.afterCreate : [...spec.afterCreate, afterCreate],
|
|
161
|
+
};
|
|
162
|
+
}
|
|
206
163
|
|
|
207
|
-
|
|
164
|
+
export function defineFactory<
|
|
165
|
+
TAttrs extends object,
|
|
166
|
+
E extends EntityLike = EntityLike,
|
|
167
|
+
TTransient extends object = None,
|
|
168
|
+
TTraits extends TraitMap<TAttrs & StoredOf<E, TAttrs>, TTransient> = TraitMap<
|
|
169
|
+
TAttrs & StoredOf<E, TAttrs>,
|
|
170
|
+
TTransient
|
|
171
|
+
>,
|
|
172
|
+
TBelongs extends BelongsToMap = None,
|
|
173
|
+
TMany extends HasManyMap = None,
|
|
174
|
+
>(
|
|
175
|
+
entity: E,
|
|
176
|
+
options: FactoryOptions<TAttrs, TTraits, TTransient, TBelongs, TMany, StoredOf<E, TAttrs>, E>,
|
|
177
|
+
): Factory<
|
|
178
|
+
TAttrs,
|
|
179
|
+
Extract<keyof TTraits, string>,
|
|
180
|
+
StoredOf<E, TAttrs>,
|
|
181
|
+
TTransient,
|
|
182
|
+
TBelongs,
|
|
183
|
+
TMany
|
|
184
|
+
> {
|
|
185
|
+
const seed = options.seed ?? seedFor(entity.$table);
|
|
186
|
+
const sequence: Sequence = {
|
|
187
|
+
index: 0,
|
|
188
|
+
uuid: seededUuid(seed),
|
|
189
|
+
random: seededRandom(seed),
|
|
190
|
+
ids: { uuid: () => sequence.uuid(), number: () => Math.floor(sequence.random() * 1_000_000) },
|
|
191
|
+
resetting: false,
|
|
192
|
+
};
|
|
193
|
+
sequences.add({ sequence, seed });
|
|
194
|
+
// Erased once, here: the public options held each member to its own column's type already.
|
|
195
|
+
const erased = options as unknown as FactoryOptions<
|
|
196
|
+
object,
|
|
197
|
+
unknown,
|
|
198
|
+
object,
|
|
199
|
+
unknown,
|
|
200
|
+
unknown,
|
|
201
|
+
object
|
|
202
|
+
>;
|
|
203
|
+
const spec: FactorySpec = {
|
|
204
|
+
entity,
|
|
205
|
+
defaults: (index, ids, transient) => erased.defaults(index, ids, transient),
|
|
206
|
+
traits: (options.traits ?? {}) as FactorySpec['traits'],
|
|
207
|
+
transient: (options.transient ?? {}) as FactorySpec['transient'],
|
|
208
|
+
belongsTo: Object.entries((options.belongsTo ?? {}) as BelongsToMap),
|
|
209
|
+
hasMany: Object.entries((options.hasMany ?? {}) as HasManyMap),
|
|
210
|
+
afterBuild: erased.afterBuild === undefined ? [] : [erased.afterBuild.bind(options)],
|
|
211
|
+
afterCreate: erased.afterCreate === undefined ? [] : [erased.afterCreate.bind(options)],
|
|
212
|
+
};
|
|
213
|
+
return view(spec, sequence, seed, []) as unknown as Factory<
|
|
214
|
+
TAttrs,
|
|
215
|
+
Extract<keyof TTraits, string>,
|
|
216
|
+
StoredOf<E, TAttrs>,
|
|
217
|
+
TTransient,
|
|
218
|
+
TBelongs,
|
|
219
|
+
TMany
|
|
220
|
+
>;
|
|
208
221
|
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// What `defineFactory` takes and what it returns, as types. The four strategies are FactoryBot's —
|
|
2
|
+
// `build`, `create`, `attributesFor` and the `…List` forms — and nothing else: one name per job.
|
|
3
|
+
|
|
4
|
+
import type {
|
|
5
|
+
AttributesFor,
|
|
6
|
+
Built,
|
|
7
|
+
Created,
|
|
8
|
+
EntityLike,
|
|
9
|
+
FactoryContext,
|
|
10
|
+
FactoryIds,
|
|
11
|
+
FactoryOverrides,
|
|
12
|
+
ForeignKeysOf,
|
|
13
|
+
HasManyMap,
|
|
14
|
+
None,
|
|
15
|
+
TraitMap,
|
|
16
|
+
WriteBound,
|
|
17
|
+
} from './factory-types';
|
|
18
|
+
|
|
19
|
+
export interface FactoryOptions<
|
|
20
|
+
TAttrs extends object,
|
|
21
|
+
TTraits,
|
|
22
|
+
TTransient extends object,
|
|
23
|
+
TBelongs,
|
|
24
|
+
TMany,
|
|
25
|
+
TRow extends object,
|
|
26
|
+
E = EntityLike,
|
|
27
|
+
> {
|
|
28
|
+
/** Omitted means "derived from the table name" — see `seedFor`. */
|
|
29
|
+
readonly seed?: number;
|
|
30
|
+
/**
|
|
31
|
+
* Every column the factory owns; called once per row. `index` is the sequence. It must name each
|
|
32
|
+
* `belongsTo` key, so a key that is not a column is a compile error HERE: a check written as a
|
|
33
|
+
* constraint on `belongsTo` fixed the row type before this was read, and every row became `object`.
|
|
34
|
+
*/
|
|
35
|
+
defaults(
|
|
36
|
+
index: number,
|
|
37
|
+
ids: FactoryIds,
|
|
38
|
+
transient: TTransient,
|
|
39
|
+
): TAttrs & WriteBound<E> & Readonly<Record<ForeignKeysOf<TBelongs>, unknown>>;
|
|
40
|
+
readonly traits?: TTraits;
|
|
41
|
+
/** Attributes a call may pass that are never written: read by `defaults`, traits and callbacks. */
|
|
42
|
+
readonly transient?: TTransient;
|
|
43
|
+
readonly belongsTo?: TBelongs;
|
|
44
|
+
readonly hasMany?: TMany;
|
|
45
|
+
/** After the row is assembled, before any write — both strategies. */
|
|
46
|
+
afterBuild?(row: NoInfer<TAttrs>, context: FactoryContext<TTransient>): void;
|
|
47
|
+
/** After the row and its `hasMany` children are stored — `create()` only. */
|
|
48
|
+
afterCreate?(
|
|
49
|
+
row: NoInfer<Created<TRow, TMany>>,
|
|
50
|
+
context: FactoryContext<TTransient>,
|
|
51
|
+
): void | Promise<void>;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* What `extend()` adds: more defaults, traits, transients, callbacks — and `hasMany`, which is
|
|
56
|
+
* where a two-way association closes its cycle: `posts` is declared, `comments` belongs to it, and
|
|
57
|
+
* `posts.extend({ hasMany: { comments: hasMany(commentFactory, 'postId') } })` comes after both.
|
|
58
|
+
*/
|
|
59
|
+
export interface FactoryExtension<
|
|
60
|
+
TAttrs extends object,
|
|
61
|
+
TTraits,
|
|
62
|
+
TTransient extends object,
|
|
63
|
+
TRow extends object,
|
|
64
|
+
TMany,
|
|
65
|
+
TMoreMany = None,
|
|
66
|
+
> {
|
|
67
|
+
defaults?(index: number, ids: FactoryIds, transient: TTransient): Partial<TAttrs & TRow>;
|
|
68
|
+
readonly traits?: TTraits;
|
|
69
|
+
readonly transient?: Partial<TTransient>;
|
|
70
|
+
readonly hasMany?: TMoreMany;
|
|
71
|
+
afterBuild?(row: TAttrs, context: FactoryContext<TTransient>): void;
|
|
72
|
+
afterCreate?(
|
|
73
|
+
row: Created<TRow, TMany & TMoreMany>,
|
|
74
|
+
context: FactoryContext<TTransient>,
|
|
75
|
+
): void | Promise<void>;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface Factory<
|
|
79
|
+
TAttrs extends object,
|
|
80
|
+
TTrait extends string = string,
|
|
81
|
+
TRow extends object = TAttrs,
|
|
82
|
+
TTransient extends object = None,
|
|
83
|
+
TBelongs = None,
|
|
84
|
+
TMany = None,
|
|
85
|
+
> {
|
|
86
|
+
readonly entity: EntityLike;
|
|
87
|
+
readonly table: string;
|
|
88
|
+
/** The declared trait names, sorted — what a failure lists and what a test can assert on. */
|
|
89
|
+
readonly traits: readonly TTrait[];
|
|
90
|
+
/** In memory: parents built, never written. No database is reached. */
|
|
91
|
+
build(
|
|
92
|
+
over?: FactoryOverrides<TAttrs & TRow, TTransient, TBelongs, TMany>,
|
|
93
|
+
): Built<TAttrs & Partial<TRow>, TMany>;
|
|
94
|
+
buildList(
|
|
95
|
+
count: number,
|
|
96
|
+
over?: FactoryOverrides<TAttrs & TRow, TTransient, TBelongs, TMany>,
|
|
97
|
+
): readonly Built<TAttrs & Partial<TRow>, TMany>[];
|
|
98
|
+
/** Parents created first, the row written through the persister, children after it: STORED rows. */
|
|
99
|
+
create(
|
|
100
|
+
over?: FactoryOverrides<TAttrs & TRow, TTransient, TBelongs, TMany>,
|
|
101
|
+
): Promise<Created<TRow, TMany>>;
|
|
102
|
+
createList(
|
|
103
|
+
count: number,
|
|
104
|
+
over?: FactoryOverrides<TAttrs & TRow, TTransient, TBelongs, TMany>,
|
|
105
|
+
): Promise<readonly Created<TRow, TMany>[]>;
|
|
106
|
+
/** An action's input: no primary key, no parent key, no transient, nothing built or written. */
|
|
107
|
+
attributesFor(
|
|
108
|
+
over?: Partial<TAttrs & TRow> & Partial<TTransient>,
|
|
109
|
+
): AttributesFor<TAttrs, TBelongs>;
|
|
110
|
+
/** A view with those traits applied, sharing this factory's sequence so ids never repeat. */
|
|
111
|
+
with(...traits: readonly TTrait[]): Factory<TAttrs, TTrait, TRow, TTransient, TBelongs, TMany>;
|
|
112
|
+
/** A child factory — same table, same sequence, its defaults over these, its callbacks after. */
|
|
113
|
+
extend<
|
|
114
|
+
TMoreTraits extends TraitMap<TAttrs & TRow, TTransient> = None,
|
|
115
|
+
TMoreMany extends HasManyMap = None,
|
|
116
|
+
>(
|
|
117
|
+
extension: FactoryExtension<TAttrs, TMoreTraits, TTransient, TRow, TMany, TMoreMany>,
|
|
118
|
+
): Factory<
|
|
119
|
+
TAttrs,
|
|
120
|
+
TTrait | Extract<keyof TMoreTraits, string>,
|
|
121
|
+
TRow,
|
|
122
|
+
TTransient,
|
|
123
|
+
TBelongs,
|
|
124
|
+
TMany & TMoreMany
|
|
125
|
+
>;
|
|
126
|
+
/** Restart the sequence so a second describe block sees the same ids as the first. */
|
|
127
|
+
reset(): void;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Any factory, its types erased: what `lintFactories` and `factorySeed` hold. */
|
|
131
|
+
export type AnyFactory = Factory<object, string, object, object, unknown, unknown>;
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// The two association kinds, as values a factory declares: `belongsTo` (a parent the row points
|
|
2
|
+
// at) and `hasMany` (children that point at the row). Both name the foreign key as a column, so the
|
|
3
|
+
// key a test overrides and the key the factory fills are one spelling.
|
|
4
|
+
|
|
5
|
+
import { finiteCount } from '@ultimat3/core';
|
|
6
|
+
import type { BelongsTo, EntityLike, FactoryLike, HasMany } from './factory-types';
|
|
7
|
+
|
|
8
|
+
export interface BelongsToOptions<TParent> {
|
|
9
|
+
/** The parent column the key holds. Left out: what the child's `references()` names, else `id`. */
|
|
10
|
+
readonly references?: keyof TParent & string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* `belongsTo: { org: belongsTo(orgs, 'orgId') }`. `build()` builds the parent in memory, `create()`
|
|
15
|
+
* writes it first; `create({ org: row })` reuses a row instead; `create({ orgId })` makes none.
|
|
16
|
+
* The key is checked against the child's columns where the factory is declared.
|
|
17
|
+
*/
|
|
18
|
+
export function belongsTo<TBuilt extends object, TRow extends object, const TKey extends string>(
|
|
19
|
+
parent: FactoryLike<TBuilt, TRow>,
|
|
20
|
+
foreignKey: TKey,
|
|
21
|
+
options: BelongsToOptions<TBuilt & TRow> = {},
|
|
22
|
+
): BelongsTo<TBuilt, TRow, TKey> {
|
|
23
|
+
return { kind: 'belongsTo', parent, foreignKey, references: options.references };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface HasManyOptions {
|
|
27
|
+
/** Children made when the call names none. Default 0: a row with children is asked for. */
|
|
28
|
+
readonly count?: number;
|
|
29
|
+
/** The parent column the child's key holds. Left out: the child's `references()`, else `id`. */
|
|
30
|
+
readonly references?: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* `hasMany: { comments: hasMany(comments, 'postId') }` — then `create({ comments: 2 })` or
|
|
35
|
+
* `create({ comments: [{ body: 'first' }, {}] })`. Made AFTER the parent, the key set from the
|
|
36
|
+
* stored parent, the tenant column following it.
|
|
37
|
+
*/
|
|
38
|
+
export function hasMany<
|
|
39
|
+
TBuilt extends object,
|
|
40
|
+
TRow extends object,
|
|
41
|
+
const TKey extends keyof TBuilt & string,
|
|
42
|
+
>(
|
|
43
|
+
child: FactoryLike<TBuilt, TRow>,
|
|
44
|
+
foreignKey: TKey,
|
|
45
|
+
options: HasManyOptions = {},
|
|
46
|
+
): HasMany<TBuilt, TRow, TKey> {
|
|
47
|
+
return {
|
|
48
|
+
kind: 'hasMany',
|
|
49
|
+
child,
|
|
50
|
+
foreignKey,
|
|
51
|
+
references: options.references,
|
|
52
|
+
// Screened here, where it is written: a fraction or a NaN would surface three awaits into the
|
|
53
|
+
// first `create()` as an `Array.from` throw or a loop that never runs.
|
|
54
|
+
count: finiteCount(`hasMany(…, '${foreignKey}')`, 'count', options.count ?? 0),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The parent property `entity`'s `foreignKey` references, read off its own `references()`. */
|
|
59
|
+
export function referencedBy(
|
|
60
|
+
entity: EntityLike,
|
|
61
|
+
foreignKey: string,
|
|
62
|
+
declared: string | undefined,
|
|
63
|
+
): string {
|
|
64
|
+
if (declared !== undefined) return declared;
|
|
65
|
+
const found = entity.$references?.().find((reference) => reference.property === foreignKey);
|
|
66
|
+
return found?.targetProperty ?? 'id';
|
|
67
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// The factory lint's one refusal. Its own file because `errors.ts` is another owner's; the code is
|
|
2
|
+
// registered there (`TESTING_ERROR_CODES`) and documented in `wiki/Error-Codes.md`.
|
|
3
|
+
|
|
4
|
+
import { UltimateError } from '@ultimat3/core';
|
|
5
|
+
|
|
6
|
+
/** One factory, one trait (or none), one strategy that produced a row its entity refuses. */
|
|
7
|
+
export interface FactoryFinding {
|
|
8
|
+
readonly factory: string;
|
|
9
|
+
/** `null` for the factory with no trait applied. */
|
|
10
|
+
readonly trait: string | null;
|
|
11
|
+
readonly strategy: 'build' | 'create';
|
|
12
|
+
/** The entity's own code when it refused the row; `X_TEST_FACTORY_INVALID` for an unknown column. */
|
|
13
|
+
readonly code: string;
|
|
14
|
+
readonly cause: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const label = (finding: FactoryFinding): string =>
|
|
18
|
+
`${finding.factory}${finding.trait === null ? '' : `.with('${finding.trait}')`}.${finding.strategy}()`;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* A factory that builds a row its own entity refuses fails every test that uses it, one at a time
|
|
22
|
+
* and far from the cause. The lint names each one at once, with the entity's own reason.
|
|
23
|
+
*/
|
|
24
|
+
export class FactoryInvalidError extends UltimateError {
|
|
25
|
+
readonly findings: readonly FactoryFinding[];
|
|
26
|
+
|
|
27
|
+
constructor(findings: readonly [FactoryFinding, ...FactoryFinding[]]) {
|
|
28
|
+
const [first] = findings;
|
|
29
|
+
super({
|
|
30
|
+
code: 'X_TEST_FACTORY_INVALID',
|
|
31
|
+
cause: `${findings.length} factory row(s) the entity refuses: ${findings
|
|
32
|
+
.map((finding) => `${label(finding)} — ${finding.code}: ${finding.cause}`)
|
|
33
|
+
.join('; ')}`,
|
|
34
|
+
fix: `defineFactory(<the entity>, { defaults, traits }) — edit the defaults or trait behind ${label(first)} so its row is one the entity stores, then re-run assertFactoriesValid(…)`,
|
|
35
|
+
});
|
|
36
|
+
this.findings = findings;
|
|
37
|
+
}
|
|
38
|
+
}
|