@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/CLAUDE.md
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
# @ultimat3/testing — boundary
|
|
2
2
|
|
|
3
3
|
Tier 5. May import tiers 0–4. Imported by every package's tests and by generated apps.
|
|
4
|
+
A row marked `†` has its full text in [`docs/history/testing-rules.md`](../../docs/history/testing-rules.md).
|
|
4
5
|
|
|
5
|
-
Deps (
|
|
6
|
-
`jobs` `query` `realtime`; `mail` `pwa` `render
|
|
6
|
+
Deps (21): `core` `schema`; `cache` `db` `i18n` `seo` `time`; `auth` `entity` `http` `policy`; `action`
|
|
7
|
+
`jobs` `query` `realtime`; `ai` `mail` `notify` `pwa` `render` `scraping` (`ai`, `auth`, `notify`, `scraping` for `swapAdapter`, dynamic-only). Static in `.`: `scraping/cdp`, `cache`
|
|
7
8
|
(`registry-leak-guard.ts:7`), `i18n`, `jobs`, `policy` (`registry-snapshot.ts:29-38`), `db`
|
|
8
9
|
(`reusable-database.ts:20`), `realtime/server` (`fixture-subscribe.ts:13`). Dynamic-only:
|
|
9
10
|
`action`, `http`, `mail`, `pwa`, `query`, `render`, `schema` (`exercise-input.ts:16`), `time` — no `mail` destructure, no mail
|
|
10
11
|
package; a `packages/core` import never loads `@ultimat3/entity`. `entity` is reached by `await import` only
|
|
11
|
-
(seed writer, tenant witness, `nPlusOne()`, repro, subject proof, the row observer);
|
|
12
|
-
|
|
12
|
+
(seed writer, tenant witness, `nPlusOne()`, repro, subject proof, the row observer); static only in
|
|
13
|
+
the off-barrel entry points `registry-isolation.ts`, `conformance.ts`. Full rule: `docs/history/testing.md`.
|
|
13
14
|
|
|
14
15
|
| Rule | Detail |
|
|
15
16
|
|---|---|
|
|
@@ -17,7 +18,7 @@ import is `registry-isolation.ts`, own entry point, off the barrel. Full rule: `
|
|
|
17
18
|
| No wall clock | `withFrozenClock` / `advanceClock`; `Date.now()` is frozen by the preload |
|
|
18
19
|
| Frozen ≠ different | `globalThis.Date` becomes a subclass; `FrozenDate[Symbol.hasInstance]` brands on the `[[DateValue]]` slot (`Date.prototype.getTime.call(value)` throws or not) |
|
|
19
20
|
| No unmocked egress | `sealed-network.ts` seals `fetch`; `sealed-sockets.ts` `WebSocket`, `Bun.connect`, `node:*`, UDP (not loopback); `sealed-dns*.ts` every resolver, named imports too (wiki `Testing.md`); a miss is `X_TEST_NETWORK_SEALED` |
|
|
20
|
-
| One `mockFetch`, and it grows |
|
|
21
|
+
| One `mockFetch`, and it grows | verbs, ordered answers, pinned dials (`mock-route.ts`), `requestLog` (`request-log.ts`) — one `mockFetch` † |
|
|
21
22
|
| Self is not egress | a port core's `markListening()` announced passes through — a socket test never unseals |
|
|
22
23
|
| Offline is a state, not a mock | `network.offline()` / `.drop()` fail every dial, loopback too, as `X_TEST_NETWORK_OFFLINE` before any mock: the app's offline path runs |
|
|
23
24
|
| One way offline | the `network` fixture. `setNetworkState` is the gate's only writer and is not exported — setting it from a test body skips the fixture's disposal and leaves every later file offline |
|
|
@@ -25,7 +26,7 @@ import is `registry-isolation.ts`, own entry point, off the barrel. Full rule: `
|
|
|
25
26
|
| `toEqualRow` never prints a server-only value | `matcher-row.ts` compares every OWN property (`toEqual` cannot see a `.sealed()` column — empty diff). Full rule: `docs/history/testing.md` |
|
|
26
27
|
| No retries | a flake is fixed or deleted the day it flakes; there is no `retry: 3` |
|
|
27
28
|
| A mutator's `local()` runs against `memoryLocalTx()` | `local-tx.ts`: keyed rows with the record store's rules (update invents nothing, `undefined` leaves a column, rows frozen). Never a hand-rolled table per test |
|
|
28
|
-
| A page test RENDERS, with no cast | `
|
|
29
|
+
| A page test RENDERS, with no cast | `renderRoute(module, { url, actor })` / `renderView(Component, props)` (`render-view.ts`) † |
|
|
29
30
|
| `toBeUltimateError` reads THREE fields | an `X_` code plus a `cause` plus a `fix`, all through core's `stringField`. `typeof value.code === 'string'` alone passed a Node `ENOENT` |
|
|
30
31
|
| One matcher WAITS, and it is `toBeVisible` | `await expect(locator).toBeVisible()` retries `isVisible()` to a budget — 5000ms every 100ms, Playwright's own default, narrowable per call. |
|
|
31
32
|
| The budget is counted in LOOKS, at a FIXED interval | `attemptsFor(budget)` is `1 + floor(timeout / interval)`; never a clock deadline, never a curve. Full rule: `docs/history/testing.md` |
|
|
@@ -35,36 +36,39 @@ import is `registry-isolation.ts`, own entry point, off the barrel. Full rule: `
|
|
|
35
36
|
| Every message thunk needs a test that PROVOKES it | a thunk is a function, so an unread message is an UNCOVERED function and `bun run scripts/coverage-gate.ts --package testing` is what says so |
|
|
36
37
|
| Test names | the filename picks the step; a typed helper prefixes its own name. `testName(type, name)` is for an outer `describe` only — never on the inner `test` too, the prefix would print twice |
|
|
37
38
|
| One body shape, five registrars | `test` (= `fixtureTest`), `unitTest`, `contractTest`, `liveTest`, `jobTest` all take `FixtureBody` + `{ timeoutMs }`: `unitTest('…', async ({ runJobs }) => …)`. Never `describe(testName('unit', …))` + `test` to get a fixture |
|
|
38
|
-
| `runJobs` says who and what | `{ actor }` is the WORKER
|
|
39
|
-
| A `runJobs` pass is a real worker's `tick()` | `fixture-jobs.ts
|
|
40
|
-
|
|
|
41
|
-
| A
|
|
39
|
+
| `runJobs` says who and what | `{ actor }` is the WORKER, `{ tenantId }` the enqueuer; bodies on the frozen clock † |
|
|
40
|
+
| A `runJobs` pass is a real worker's `tick()` | `fixture-jobs.ts`: an unstarted `jobWorker` per pass, so admission runs as in a fleet † |
|
|
41
|
+
| One test double per need | `stub(action \| llm() \| query \| job)` replaces the BODY only; `swapAdapter(port, impl)` borrows a port's installer; both undone by `test-scope.ts` † |
|
|
42
|
+
| A port is swappable or says why not | `swap-adapter.ts`: `BINDINGS` + `UNSWAPPED` cover `ADAPTER_PORTS` as a `Record` — a new core row is a compile error here |
|
|
43
|
+
| `toHaveBeenCalledWith` is bun's name | on a `stub()` it parses the expected input by the primitive's schema (`X_TEST_EXPECTED_INPUT_INVALID`); any other receiver goes to bun's own matcher, captured once (`matcher-stub.ts`) |
|
|
44
|
+
| Per-test state is `per-test-reset.ts` | the app preload's `beforeEach`; `installPerTestReset` installs the test-double scope † |
|
|
45
|
+
| A `mock.module` ends with its file | `module-mock-boundary.ts` restores the real namespace at the boundary (`X_TEST_MODULE_MOCK_UNRESTORABLE`) † |
|
|
42
46
|
| **The frozen clock is reset at every file boundary** | `preload.ts`, `clock-file-boundary.test.ts`: `advanceClock` / `setFrozenClock` move one process-wide instant, and a file that left it moved handed the next file on its worker a different `Date.now()` |
|
|
43
47
|
| An island test is `describeIslandState` | one block per declared state: mounted in `beforeAll` (60 s), disposed in `afterAll`, one build per file. `mountIslandState` + `using` for one test's own mount; an undeclared id is `X_TEST_ISLAND_STATE_UNKNOWN` |
|
|
44
48
|
| An authenticator is tested with `authRequest()` | the hook's own two arguments, real — never `as unknown as Parameters<…>` |
|
|
45
|
-
| `LOG_LEVEL` above `info` filters the TERMINAL | `quiet-logs.ts` pins the logger at `info` while core loads, so a collecting `
|
|
49
|
+
| `LOG_LEVEL` above `info` filters the TERMINAL | `quiet-logs.ts` pins the logger at `info` while core loads, so a collecting `installLogSink` still sees `warn` under `LOG_LEVEL=error`. It stays the preload's FIRST import |
|
|
46
50
|
| Injection | `SqlRunner` and `connect` are parameters, so unit tests need no server |
|
|
47
|
-
| Fixtures | the preload registers the framework bag — an app registers only what it alone knows (`seed
|
|
48
|
-
| Every `e2eTest` is audited | `e2e-a11y
|
|
49
|
-
| The exercise pass runs what is registered | `exercise.ts` (`runExercisePass`): every action, query
|
|
50
|
-
| An override `input` is awaited, as the call's actor | `exercise-override-input.ts`:
|
|
51
|
+
| Fixtures | the preload registers the framework bag — an app registers only what it alone knows: `seed` as `seedFixture({ seeds, driver })` (`fixture-seed.ts`: once per test per name, rows captured on the way in, picked by label), `actorFor` |
|
|
52
|
+
| Every `e2eTest` is audited | `e2e-a11y*.ts`, `ax-node.ts`; no switch, `allow` needs a `because` † |
|
|
53
|
+
| The exercise pass runs what is registered | `exercise.ts` (`runExercisePass`): every action, query, job once, own tenant pair; overrides only via `defineExercise` † |
|
|
54
|
+
| An override `input` is awaited, as the call's actor | `exercise-override-input.ts`: inside the call's own request — the one way to a signed input † |
|
|
51
55
|
| A passkey test signs for real | `softAuthenticator` is `@ultimat3/auth/soft-authenticator`'s, never re-exported here (one value, one path: `flight-copies`) and never a second one (auth's own suites need it, and auth cannot import testing) |
|
|
52
|
-
| A reached job is crash-proven | `exercise-crash.ts`:
|
|
56
|
+
| A reached job is crash-proven | `exercise-crash.ts`: only `diverged` is red (`X_JOB_CRASH_DIVERGED`) † |
|
|
53
57
|
| The tenant proof is taint only | `tenant-proof.ts`: B, A, B; B is A's role minus `tenancy:cross`. Leak = seeded canary or unhanded id (`tenant-canary.ts`); write = moved digest. Only `crossed` is red |
|
|
54
|
-
| Every statement the pass sent is planned | `plan-sweep.ts`
|
|
55
|
-
| A shape that grows with the rows is red | `scale-sweep-run.ts
|
|
56
|
-
| An erase is PROVED, not asserted | `subject-proof.ts
|
|
57
|
-
| A captured failure replays as a test | `repro.ts`: `reproduce(bundle, { driver })
|
|
58
|
-
| A vendor's answers are a cassette | `cassette.ts`: replay =
|
|
58
|
+
| Every statement the pass sent is planned | `plan-sweep.ts` + `plan-oracle.ts`: `X_QUERY_UNINDEXED` / `X_QUERY_SORT_UNSERVED` with the `indexes:` fix; no generic plan is `X_QUERY_PLAN_UNAVAILABLE`, never a pass † |
|
|
59
|
+
| A shape that grows with the rows is red | `scale-sweep-run.ts` + pure `judgeScale`: `X_QUERY_SCALES_WITH_ROWS` † |
|
|
60
|
+
| An erase is PROVED, not asserted | `subject-proof.ts`: a survivor outside `retain` is `X_SUBJECT_ERASE_INCOMPLETE`, never the value † |
|
|
61
|
+
| A captured failure replays as a test | `repro.ts`: `reproduce(bundle, { driver })`, `reproJob(runJobs, failure)` — what `x repro --write` emits † |
|
|
62
|
+
| A vendor's answers are a cassette | `cassette.ts`: replay = `mockFetch` routes, seal kept; record refused under `CI`, secrets scanned before disk; written by action's `stableStringify`, loaded dynamically (`serializeCassette`) † |
|
|
59
63
|
| One seed writer | `entitySeedWriter({ entities, client \| driver })` (`seed-writer.ts`) writes through each entity's own repository; `snapshot` is required; `entity` loads on the first write, so the barrel stays entity-free |
|
|
60
|
-
| Factory values are DECLARED | `
|
|
64
|
+
| Factory values are DECLARED | `seed-graph-values.ts` for `factoriesFor` and `seedGraph`: default, enum, kind, pattern, `$meta.schema` — never the name † |
|
|
61
65
|
| e2e without a driver | `e2eTest` becomes `test.skip`; the gate reports the step SKIPPED (or `X_VERIFY_SUITE_VANISHED` when `x.verify.json` requires it), never passed |
|
|
62
66
|
| The seam has an inverse | `resetE2eDriver()`: `useE2eDriver` writes MODULE scope, so a file that installs a browser undoes it |
|
|
63
67
|
| Built vs declared | `clock` `mail` `network` `runJobs` `statements` `subscribe` are built in-process; `page` `budget` `signIn` `deploy` are declared and wait for a driver (`X_TEST_FIXTURE_UNAVAILABLE`). |
|
|
64
68
|
| `page` HAS a driver; `budget`, `signIn`, `deploy` do not | `installE2eDriver({ page, baseUrl })` registers `page` only. Byte counts, a sign-in route and a new build id are facts no page port can answer; a no-op would read as proof |
|
|
65
69
|
| `network` is THIS process's fetch, and an e2e page is not in this process | `network.offline()` beside `page` is a no-op on the browser. Full rule: `docs/history/testing.md` |
|
|
66
|
-
| `subscribe` is a whole `sync` node, minus the listener | `live-node.ts`; no client store, offline queue or rebase log
|
|
67
|
-
| Strict is opt-in by destructuring | `statements`
|
|
70
|
+
| `subscribe` is a whole `sync` node, minus the listener | `live-node.ts`; no client store, offline queue or rebase log † |
|
|
71
|
+
| Strict is opt-in by destructuring | `statements` subscribes the N+1 detector for one test; its first verdict raised at disposal (a subscriber cannot throw into the statement). No `strict: true` or suite-wide switch |
|
|
68
72
|
| One threshold, one error | `N_PLUS_ONE_THRESHOLD` and `nPlusOne()` are `@ultimat3/entity`'s, never a copy |
|
|
69
73
|
| The unit of work is the test | `x dev`'s ledger tallies per `Ctx` and ignores a statement issued outside a request |
|
|
70
74
|
| Throws once per shape | the failing line is the loop's own statement (why `onStatement` may throw) |
|
|
@@ -85,17 +89,20 @@ import is `registry-isolation.ts`, own entry point, off the barrel. Full rule: `
|
|
|
85
89
|
| A found template is not a migrated one | `template-db.ts` tolerates "already exists" for the `CREATE DATABASE` alone. `config.migrate` runs unconditionally; drop + clone hold the same lock |
|
|
86
90
|
| Fixture teardown | a fixture that installs process-global state (the ambient job or mail driver) implements `Symbol.dispose` / `Symbol.asyncDispose` and restores what was there |
|
|
87
91
|
| Building one by hand | `testJobs()` outside a fixture body is not disposed for you — dispose it in `afterEach`, or the next file inherits your queue and your event bus |
|
|
88
|
-
| Factory strategy | an
|
|
89
|
-
| One write seam | `
|
|
90
|
-
|
|
|
92
|
+
| Factory strategy | `build` (memory), `create` (STORED row), `attributesFor` (an input: no key, no parent key), `buildList`/`createList`. An association uses the strategy that asked: `build()` never reaches a database. Never a fifth strategy |
|
|
93
|
+
| One write seam | `create()` writes through `persistRow` (`usePersister`, else `entityPersister()`); `X_TEST_FACTORY_NOT_PERSISTED` † |
|
|
94
|
+
| One row pipeline | `factory-pipeline.ts` is a generator both strategies drive: `build` answers each yield in memory, `create` awaits it. Never a second copy of the row order — the seeded draws depend on it |
|
|
95
|
+
| Associations | `belongsTo(parent, 'fk')`, `hasMany(child, 'fk')`; the tenant column follows the parent † |
|
|
96
|
+
| Factory seeds | derived from the table name unless given. `reset()` cascades into parents and children, cycle-guarded. `factorySeed` restarts EVERY sequence (`resetFactorySequences`) so a replay draws the same ids |
|
|
97
|
+
| Factory lint | `lintFactories(set)` / `assertFactoriesValid(set)` (`X_TEST_FACTORY_INVALID`): each factory and each trait alone, built (`$parse` + `$assert`, unknown keys) and created into its OWN fresh memory driver |
|
|
91
98
|
| Shared examples | `behavesLike` calls `describe`, so it goes at declaration scope; bun rejects a `describe` inside a test body |
|
|
92
|
-
| A port's contract is shared examples |
|
|
99
|
+
| A port's contract is shared examples | one suite per port on `@ultimat3/testing/conformance`: `behavesLike(<port>Conformance, () => yours)`, each with a broken adapter that must fail † |
|
|
93
100
|
| An island needs a BUILDER, not an import | `buildIslands` is `@ultimat3/cli`'s; `testing → cli` fails `bun run boundaries` |
|
|
94
101
|
| `mountIsland` AWAITS `mount` | `IslandEntry['mount']` returns `unknown`, not `void`, and the call is awaited |
|
|
95
102
|
| Dispose STOPS the island, then restores the globals | when `mount` resolved to a function, `[Symbol.dispose]` calls it BEFORE `restore()` |
|
|
96
103
|
| The micro-DOM is the fixture's, once **for islands** | `island-dom.ts`. Full rule: `docs/history/testing.md` |
|
|
97
|
-
| The micro-DOM records and does not pretend | `style`/`classList
|
|
98
|
-
| The selector grammar is SMALL and REFUSES | `island-selector.ts`:
|
|
104
|
+
| The micro-DOM records and does not pretend | records `style`/`classList`; the box is 0 until written; `ResizeObserver` never fires itself † |
|
|
105
|
+
| The selector grammar is SMALL and REFUSES | `island-selector.ts`: anything else is `X_TEST_ISLAND_SELECTOR_UNSUPPORTED` † |
|
|
99
106
|
| A mount installs process globals | so `MountedIsland` is `Disposable` and a `mount` that THROWS restores before it rethrows. A fake `document` left installed reaches every later FILE in the run |
|
|
100
107
|
| `fire` answers whether a handler ran | a selector matching nothing and an island that attached no handler are the same silence otherwise — the second is a bug, the first a typo. |
|
|
101
108
|
| A states file is PURE DATA, and it is enforced | `defineIslandStates` declares the states an island can be photographed in — error, empty, over-quota, read-only |
|
|
@@ -116,37 +123,21 @@ import is `registry-isolation.ts`, own entry point, off the barrel. Full rule: `
|
|
|
116
123
|
|
|
117
124
|
Through one `instantMs` and core's `finiteOption`/`finiteCount` (`determinism-bounds.test.ts`). Full rule: `docs/history/testing.md`.
|
|
118
125
|
|
|
119
|
-
Commands: `bun test
|
|
126
|
+
Commands: `bun test ./packages/testing/` (from the repo root — the `./` keeps `examples/dummy` out), `bunx tsc --noEmit -p tsconfig.json`.
|
|
120
127
|
|
|
121
|
-
Entry points: `.` (the API), `./preload` (side effects for bunfig)
|
|
122
|
-
(`isolateEntityRegistry()`, kept off `.` because it loads `@ultimat3/entity`)
|
|
128
|
+
Entry points: `.` (the API), `./preload` (side effects for bunfig), `./registry-isolation`
|
|
129
|
+
(`isolateEntityRegistry()`, kept off `.` because it loads `@ultimat3/entity`) and `./conformance`
|
|
130
|
+
(every port suite; static imports of the packages they hold to, so never re-exported from `.`).
|
|
123
131
|
|
|
124
132
|
The island fixture's cost and its whole-chain proof: `docs/history/testing.md`.
|
|
125
133
|
|
|
126
134
|
## The browser-backed e2e driver (moved here from `@ultimat3/cli` in 22.0.0)
|
|
127
135
|
|
|
128
|
-
Raw CDP
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
| `e2e-page.ts` | `PageLike` over four members of `ScrapePage`, declared structurally so a test stands one up in six lines |
|
|
134
|
-
| `e2e-locator.ts` | `LocatorLike` — a handle that resolves nothing until asked, one round trip per question |
|
|
135
|
-
| `e2e-selection.ts` | what a locator SELECTS, as data, and the one in-page expression that resolves it |
|
|
136
|
-
| `e2e-evaluate.ts` | the closure→string crossing, which is the only lossy edge in the adapter |
|
|
137
|
-
| `e2e-errors.ts` | one constructor per refusal |
|
|
138
|
-
| `e2e-dom-fixture.ts` | a document small enough to hold in a test and real enough to RUN the expressions above |
|
|
139
|
-
| `cdp-browser.ts` | the two doors: `openE2eBrowserIfAvailable()` (undefined when there is no browser) and `openE2eBrowser()` (refuses by name), and the close that undoes both halves |
|
|
140
|
-
| `cdp-launch.ts` | which Chrome, its flags, the launch deadline (`LAUNCH_TIMEOUT_MS`, 60 s — a cold start is not a call) and the ONE relaunch (`LAUNCH_ATTEMPTS`) |
|
|
141
|
-
| `cdp-launch-attempt.ts` | one start in its own group; on no answer a full reap (group, then profile + singleton dir: `cdp-launch-profile.ts`). ONE awaited `close()` |
|
|
142
|
-
| `cdp-connection.ts` | CDP over a transport — the launched Chrome's pipe (`cdp-pipe.ts`), a remote one's `WebSocket` (`cdpConnect`): reply correlation by `id`, event waiters, the per-call deadline; why one went unanswered is `cdp-wire-watch.ts` |
|
|
143
|
-
| `cdp-e2e-session.ts` | the BROWSER half, `E2eSession`: every target PAUSED until its Network domain is on |
|
|
144
|
-
| `cdp-e2e-page.ts` | one TAB, `E2eTab`: `E2eBrowserPage`'s six methods (`accessibilityTree` required) plus `reload`, `waitFor`, `indexedDbNames`, `close`. `offline()` forwards to the session — the switch is browser-wide |
|
|
145
|
-
| `e2e-app.ts` | `startE2eApp({ root, mode, seed })`: a THROWAWAY `ULTIMATE_STATE_DIR`, `/readyz`-gated; `stop()` removes it. Full rule: `docs/history/testing.md` |
|
|
146
|
-
| `failure-context.ts` | a FAILED test's message ends with the e2e app's last 40 log lines (≤ 4 kB): `e2e-run.ts` installs `app.log()`, `fixtureTest` and `e2eTest` append it. Never on a pass |
|
|
147
|
-
| `e2e-preload.ts` + `e2e-browser-handle.ts` | the `e2e` step's preload (`@ultimat3/testing/e2e-preload`): with `ULTIMATE_E2E_ROOT` set it spawns the app, opens ONE browser, installs its first tab, and publishes `e2eBrowser()`, `e2eApp()`, `e2eBaseUrl()` |
|
|
148
|
-
| `packages/cli/src/verify-e2e.ts` | `withE2eApp` (cli's): in an app on a machine with Chrome, the `e2e` step runs the suite with that preload; otherwise exactly as before |
|
|
149
|
-
| `cdp-errors.ts` | one constructor per way the browser half refuses |
|
|
136
|
+
Raw CDP; `cli` imports it over `cli -> testing`. Launcher + connection: `@ultimat3/scraping/cdp`
|
|
137
|
+
(31.0.0), never re-exported. One job per
|
|
138
|
+
file (`e2e-*.ts`, `cdp-*.ts`); the table of which file does what is
|
|
139
|
+
[`docs/history/testing-e2e-driver.md`](../../docs/history/testing-e2e-driver.md). The ONE call an
|
|
140
|
+
app's test preload makes is `installE2eDriver({ page, baseUrl })` (`e2e-driver.ts`).
|
|
150
141
|
|
|
151
142
|
**Absent by default** until `installE2eDriver`: [`docs/history/testing.md`](../../docs/history/testing.md#the-browser-backed-e2e-driver-moved-here-from-ultimat3cli-in-2200).
|
|
152
143
|
|
package/README.md
CHANGED
|
@@ -22,6 +22,10 @@ unitTest('the clock moves only when the test moves it', ({ clock }) => {
|
|
|
22
22
|
| `harness.ts` | `describeApp()` / `testApp()` — boot an app in-process with its own database |
|
|
23
23
|
| `template-db.ts` | N workers, N databases, one migrated template, `CREATE DATABASE ... TEMPLATE` |
|
|
24
24
|
| `determinism.ts` | frozen clock, seeded RNG, seeded uuids, `assertDeterministic` |
|
|
25
|
+
| `stub.ts` | `stub(action \| llm() \| query \| job)` — the body answers from a script (`stub-script.ts`); see [Test doubles](#test-doubles) |
|
|
26
|
+
| `swap-adapter.ts` | `swapAdapter(port, impl)` — one `ADAPTER_PORTS` port replaced for one test, through its `./adapter` installer |
|
|
27
|
+
| `test-scope.ts` | when a double is put back: after its test, or at its file's end — the preload's hooks, never the file's |
|
|
28
|
+
| `matcher-stub.ts` · `matcher-doubles.ts` | `toHaveBeenCalledWith` on a stub; `toHaveEnqueued`, `toHaveSentMail` |
|
|
25
29
|
| `sealed-network.ts` | any unmocked `fetch`, `WebSocket` or `Bun.connect` egress fails, with the URL and the line that fixes it |
|
|
26
30
|
| `sealed-sockets.ts` | the `WebSocket` and `Bun.connect` patches, behind `sealed-network.ts`'s one gate |
|
|
27
31
|
| `factories.ts` | `defineFactory` — seeded rows, traits, associations, `build` vs `create` |
|
|
@@ -36,7 +40,8 @@ unitTest('the clock moves only when the test moves it', ({ clock }) => {
|
|
|
36
40
|
| `exercise.ts` | `runExercisePass({ entities, writer, roles, seed?, overrides?, only? })` — every registered action, query and job once, each on its own committed tenant pair, one `ExerciseRecord` per primitive, the tenant proof's verdict on its `tenant`. What `x exercise` runs |
|
|
37
41
|
| `define-exercise.ts` | `defineExercise({ <name>: { actor, input?, runs? } \| { off: '<why>' } }, { actor?: <entity>, factories?: { <entity name>: defineFactory(…) }, setup?: () => mockFetch(…) \| cassette(…) })` — an app's overrides (the second argument names the entity whose rows are the actors, and the factories that build a table no generated row satisfies — a cross-column `satisfies` — keyed by entity name, unknown ones `X_DECLARATION_UNKNOWN`), `apps/web/exercise.ts`'s one export; a blank `off` is `X_CONTRACT_EXERCISE_UNDECLARED`, an unknown name `X_DECLARATION_UNKNOWN` when the pass runs |
|
|
38
42
|
| `exercise-setup.ts` | `withExerciseSetup(room, setup)`: the app's `setup` run inside the sealed room before the first row, its handle disposed before the room restores the network; an `allowHost` in it is `X_EXERCISE_SETUP_UNSEALED`. Types `ExerciseSetup`, `ExerciseSetupHandle` |
|
|
39
|
-
| `exercise-actor.ts` · `exercise-input.ts` · `exercise-report.ts` | the first `x policy explain` actor the policy allows, minted in the primitive's tenant · the input: override, then a seeded id by field stem, then the minimal draw (`@ultimat3/schema/sample`, loaded dynamically) · the room one run executes in (network sealed, mail captured, clock frozen) and its record
|
|
43
|
+
| `exercise-actor.ts` · `exercise-input.ts` · `exercise-report.ts` | the first `x policy explain` actor the policy allows, minted in the primitive's tenant · the input: override, then a seeded id by field stem, then the minimal draw (`@ultimat3/schema/sample`, loaded dynamically) · the room one run executes in (network sealed, mail captured, clock frozen) and its record |
|
|
44
|
+
| `exercise-override-line.ts` | `overrideLine`, the entry an unreached record says to paste: valid TS — the actor the pass ran as (`testActor(name, { roles, permissions }).actor`, `null` signed out, left out when the entry declares one) and each id field bound to the seeded row the pass used; an id it could not bind is the string `UNBOUND_ID` |
|
|
40
45
|
| `tenant-proof.ts` | internal (`CROSS_TENANT_SCOPE` is `@ultimat3/entity`'s): `proveTenant` — B with A's ids, A's own call, B again; each B leg between two snapshots of A's rows. `withoutCrossTenant` strips `tenancy:cross` (`CROSS_TENANT_SCOPE`) from B; `publicReason` decides `public` |
|
|
41
46
|
| `tenant-canary.ts` | internal: `tenantTaint` — one tenant's rows, ids and marks (row canaries, key parts of `MIN_TAINT_ID_LENGTH` 8 or more no other tenant shares); `findTaint` — every path holding one |
|
|
42
47
|
| `exercise-crash.ts` | internal: `proveCrash` — a job the pass reached, run through `crashProof` with its control's input and actor, after the tenant proof; the `CrashProof` on `ExerciseRecord.crash` |
|
|
@@ -82,7 +87,7 @@ unitTest('the clock moves only when the test moves it', ({ clock }) => {
|
|
|
82
87
|
| `registry-leak-guard.ts` | fails the run naming the FILE that left a process-global registry dirty, and restores the ones that can be restored at the same boundary |
|
|
83
88
|
| `registry-snapshot.ts` | `captureProcessRegistries()` / `restoreProcessRegistries()` — the locale config, the catalogs, the permission set, the role map, the tasks and the declared measurement actor, put back as a file inherited them. A module-scope declaration evaluates once per process (`bun test` without `--isolate`, `As of 2026-08`), so a neighbour's `clearPermissions()` is otherwise permanent |
|
|
84
89
|
| `registry-isolation.ts` | `isolateEntityRegistry()` — an empty entity registry, and the process's back after. Its own entry point (`@ultimat3/testing/registry-isolation`), never the barrel: it value-imports `@ultimat3/entity`, and the barrel is what a tier-0 test imports for `expect` |
|
|
85
|
-
| `quiet-logs.ts` | a green run prints the reporter and nothing else: the framework's log lines go to a sink that drops them. `LOG_LEVEL=info bun test <file>` shows them — naming `LOG_LEVEL` is the one escape hatch, and a level above `info` filters what the TERMINAL shows, never what the logger emits (below). A test asserting on log output hands `structuredLogger({ level, writer })` its own writer, or installs its own `
|
|
90
|
+
| `quiet-logs.ts` | a green run prints the reporter and nothing else: the framework's log lines go to a sink that drops them. `LOG_LEVEL=info bun test <file>` shows them — naming `LOG_LEVEL` is the one escape hatch, and a level above `info` filters what the TERMINAL shows, never what the logger emits (below). A test asserting on log output hands `structuredLogger({ level, writer })` its own writer, or installs its own with `installLogSink` and calls the release it returns |
|
|
86
91
|
| `preload.ts` | the bunfig preload that installs all of the above |
|
|
87
92
|
|
|
88
93
|
## Install
|
|
@@ -205,6 +210,75 @@ unitTest('the sweep runs as the billing worker', async ({ runJobs }) => {
|
|
|
205
210
|
| **a real worker's pass** | each round is `jobWorker(...).tick()`: admission, the limiter and keyed `concurrency` (`whenBusy: 'fail'` settles `refused`, `X_JOB_KEY_BUSY`) hold exactly as in production |
|
|
206
211
|
| **a cancel reaches a running body** | the worker renews its lease on the TEST clock — every millisecond of it — and a renewal that misses the row aborts `ctx.signal` with `X_JOB_LEASE_LOST`: start `runJobs.drain()`, cancel the row (`cancelJob(jobDriver(), id)` or the app's own action), `clock.advance(1)`, await the drain. No hand-built worker, no sleep, no wall-clock timer |
|
|
207
212
|
|
|
213
|
+
## Test doubles
|
|
214
|
+
|
|
215
|
+
One way per need. Every double is put back by the preload's own hooks: made inside a test, after
|
|
216
|
+
that test; made outside one (`beforeAll`, module scope), at the end of its file. No `afterEach`, no
|
|
217
|
+
`restore()`, nothing a skipped block can leave behind.
|
|
218
|
+
|
|
219
|
+
| Need | The one way |
|
|
220
|
+
|---|---|
|
|
221
|
+
| an action, an `llm()`, a query or a job answers what the test says | `const s = await stub(chargeCard); s.returns(out)` — `.returns(a, b)` answers in order, the last repeats; `.throws(new YourError(…))` |
|
|
222
|
+
| it was called, with this input | `expect(s).toHaveBeenCalledWith(input)` — the input is parsed by the primitive's schema first |
|
|
223
|
+
| who called it, how often | `s.calls` — `{ input, actor }[]`, oldest first |
|
|
224
|
+
| a backend (queue, mail driver, event bus, store, clock, transport…) is a fake | `await swapAdapter('jobs', memoryJobDriver())` — any port in `SwappablePort` |
|
|
225
|
+
| a job was enqueued | `await expect(runJobs).toHaveEnqueued(sendWelcome, { userId })` |
|
|
226
|
+
| a mail was sent | `expect(mail).toHaveSentMail(welcomeMail, { to: address })` |
|
|
227
|
+
| a vendor's HTTP answer | `mockFetch` / `cassette()` — [Sealed network](#sealed-network) |
|
|
228
|
+
| time | the `clock` fixture |
|
|
229
|
+
| rows a test reads by name | `const { ada } = await seed('demo').pick({ ada: 'member:ada' })` — the app registers `defineFixtures({ seed: seedFixture({ seeds: [demo], driver: () => appDriver }) })` once; `demo` is a `factorySeed` ([Factories](#factories)) |
|
|
230
|
+
| one row, here | a factory: `await postFactory.create()` ([Factories](#factories)) |
|
|
231
|
+
|
|
232
|
+
```ts
|
|
233
|
+
import type { Action } from '@ultimat3/action';
|
|
234
|
+
import type { Actor } from '@ultimat3/core';
|
|
235
|
+
import type { JobHandle } from '@ultimat3/jobs';
|
|
236
|
+
import type { StandardSchemaV1 } from '@ultimat3/schema';
|
|
237
|
+
import { expect, stub, unitTest } from '@ultimat3/testing';
|
|
238
|
+
|
|
239
|
+
// Yours: two actions (or an llm()), a job, a mail and a member.
|
|
240
|
+
declare const chargeCard: Action<
|
|
241
|
+
StandardSchemaV1<{ cartId: string; cents: number }>,
|
|
242
|
+
StandardSchemaV1<{ chargeId: string }>
|
|
243
|
+
>;
|
|
244
|
+
declare const checkout: Action<StandardSchemaV1<{ cartId: string }>, StandardSchemaV1<unknown>>;
|
|
245
|
+
declare const sendReceipt: JobHandle<{ cartId: string }>;
|
|
246
|
+
declare const receiptMail: { readonly id: string };
|
|
247
|
+
declare const member: Actor & { readonly email: string };
|
|
248
|
+
declare const cartId: string;
|
|
249
|
+
|
|
250
|
+
unitTest('checkout charges the cart and queues the receipt', async ({ runJobs, mail }) => {
|
|
251
|
+
const charged = await stub(chargeCard);
|
|
252
|
+
charged.returns({ chargeId: 'ch_1' });
|
|
253
|
+
await checkout.as(member, { cartId }); // the real action, calling the stubbed one
|
|
254
|
+
expect(charged).toHaveBeenCalledWith({ cartId, cents: 1200 });
|
|
255
|
+
await expect(runJobs).toHaveEnqueued(sendReceipt, { cartId });
|
|
256
|
+
await runJobs.drain();
|
|
257
|
+
expect(mail).toHaveSentMail(receiptMail, { to: member.email });
|
|
258
|
+
});
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
What a stub replaces is the BODY, and nothing else:
|
|
262
|
+
|
|
263
|
+
| Still real | Why it matters |
|
|
264
|
+
|---|---|
|
|
265
|
+
| the policy, the input parse, the rate limit, the meter, idempotency | a stub cannot hide a refusal the caller would meet |
|
|
266
|
+
| the output schema | a canned answer the declaration would reject fails the call, as it would in production |
|
|
267
|
+
| every surface — a direct call, `.as()`, HTTP, MCP, `.job()`, a worker pass | the stub is seen wherever the primitive is reached |
|
|
268
|
+
| `errors:` | a scripted `throws` of an undeclared code is `X_ERROR_UNDECLARED`, as a real one is |
|
|
269
|
+
|
|
270
|
+
| Refusal | When |
|
|
271
|
+
|---|---|
|
|
272
|
+
| `X_TEST_STUB_UNANSWERED` | the stub was called before `.returns()` / `.throws()` |
|
|
273
|
+
| `X_TEST_STUB_TARGET_UNSUPPORTED` | `stub()` was handed something that is not an action, `llm()`, query or job |
|
|
274
|
+
| `X_TEST_EXPECTED_INPUT_INVALID` | an assertion's expected input fails the primitive's own schema — no call could have matched it |
|
|
275
|
+
| `X_TEST_ADAPTER_PORT_UNSWAPPABLE` | the port has no process-global slot; the cause says what a test does instead (`UNSWAPPED`) |
|
|
276
|
+
| `X_TEST_SCOPE_UNINSTALLED` | no `@ultimat3/testing/preload`, so nothing would put the double back |
|
|
277
|
+
| `X_TEST_RUN_JOBS_EXPECTED` / `X_TEST_MAIL_EXPECTED` | the matcher's receiver is not the `runJobs` / `mail` fixture |
|
|
278
|
+
|
|
279
|
+
`toHaveBeenCalledWith` keeps bun's meaning for a `mock()` or a `spyOn`: only a `stub()` receiver is
|
|
280
|
+
schema-checked. `As of 2026-11`.
|
|
281
|
+
|
|
208
282
|
## An N+1 fails the test it happened in
|
|
209
283
|
|
|
210
284
|
```ts
|
|
@@ -217,8 +291,8 @@ test('the feed reads its authors once', async ({ statements }) => {
|
|
|
217
291
|
});
|
|
218
292
|
```
|
|
219
293
|
|
|
220
|
-
Opting in is naming it. `statements`
|
|
221
|
-
one test and
|
|
294
|
+
Opting in is naming it. `statements` subscribes to the `db.statement` bus event for the length of
|
|
295
|
+
one test and unsubscribes afterwards, so there is no `strict: true` to remember and no
|
|
222
296
|
suite-wide switch to forget.
|
|
223
297
|
|
|
224
298
|
| | |
|
|
@@ -226,7 +300,7 @@ suite-wide switch to forget.
|
|
|
226
300
|
| **the unit of work is the test** | `x dev`'s ledger counts per request and skips a statement issued outside one; a unit test calling `posts.findById(id)` has no request anywhere, and that is the loop it was written to catch |
|
|
227
301
|
| **one threshold** | `N_PLUS_ONE_THRESHOLD` from `@ultimat3/entity`, the number `x dev` warns at. A loop that fails a test and a loop that warns in dev are the same loop |
|
|
228
302
|
| **one error** | `nPlusOne()`'s, so the `fix:` is the `preload()` the schema's own relations spell — never a line this package composes |
|
|
229
|
-
| **it
|
|
303
|
+
| **it fails the test at teardown** | `As of 2026-11` (v31): the bus contains a subscriber's throw, so the loop runs to its end and the fixture raises the first verdict when it is disposed — the error names the shape (`members.findById`) and its count, and its stack is the looping line's: the fixture holds core's `captureStatementStacks()` for its lifetime, so both drivers stamp the sender's stack (`DbStatementEvent.callerStack`) before their first `await` — a cost production, which never holds it, does not pay. One verdict per shape, readable earlier through `verdicts()`; a body that swallows every error cannot swallow it |
|
|
230
304
|
| **measurement ≠ verdict** | `all()` `count()` `shapes()` count every statement, `expectedQueryLoop` ones included; only the verdict honours the suppression |
|
|
231
305
|
|
|
232
306
|
`expectedQueryLoop(reason, fn)` from `@ultimat3/db` stays the one way to declare a loop deliberate —
|
|
@@ -279,28 +353,48 @@ themselves, not from a directory convention.
|
|
|
279
353
|
## Factories
|
|
280
354
|
|
|
281
355
|
```ts
|
|
282
|
-
|
|
283
|
-
defaults: (n, ids): Org => ({ id: ids.uuid(), name: `org-${n}` }),
|
|
284
|
-
});
|
|
356
|
+
import { belongsTo, defineFactory, hasMany } from '@ultimat3/testing';
|
|
285
357
|
|
|
286
|
-
const
|
|
287
|
-
defaults: (n, ids)
|
|
288
|
-
|
|
289
|
-
|
|
358
|
+
const orgFactory = defineFactory(orgs, {
|
|
359
|
+
defaults: (n, ids) => ({ id: ids.uuid(), slug: `org-${n}`, name: `Org ${n}` }),
|
|
360
|
+
});
|
|
361
|
+
const postBase = defineFactory(posts, {
|
|
362
|
+
defaults: (n, ids) => ({ id: ids.uuid(), orgId: '', slug: `post-${n}`, title: `Post ${n}` }),
|
|
363
|
+
traits: { published: { status: 'published', publishedAt: new Date('2026-01-05T09:00:00Z') } },
|
|
364
|
+
transient: { shout: false },
|
|
365
|
+
belongsTo: { org: belongsTo(orgFactory, 'orgId') },
|
|
366
|
+
afterBuild: (post, { transient }) => {
|
|
367
|
+
if (transient.shout) post.title = post.title.toUpperCase();
|
|
368
|
+
},
|
|
290
369
|
});
|
|
370
|
+
const commentFactory = defineFactory(comments, {
|
|
371
|
+
defaults: (n, ids) => ({ id: ids.uuid(), orgId: '', postId: '', body: `Comment ${n}` }),
|
|
372
|
+
belongsTo: { post: belongsTo(postBase, 'postId') },
|
|
373
|
+
});
|
|
374
|
+
const postFactory = postBase.extend({ hasMany: { comments: hasMany(commentFactory, 'postId') } });
|
|
291
375
|
|
|
292
|
-
|
|
293
|
-
await
|
|
376
|
+
postFactory.build(); // memory: org built alongside, nothing written
|
|
377
|
+
const post = await postFactory.with('published').create({ comments: 2 }); // the STORED row
|
|
378
|
+
const org = await orgFactory.create();
|
|
379
|
+
await postFactory.createList(3, { org }); // reuses that org, makes none
|
|
380
|
+
postFactory.attributesFor(); // an action input: no id, no orgId
|
|
294
381
|
```
|
|
295
382
|
|
|
296
383
|
| | |
|
|
297
384
|
|---|---|
|
|
298
|
-
| **
|
|
299
|
-
| **
|
|
300
|
-
| **
|
|
301
|
-
|
|
|
302
|
-
| **
|
|
303
|
-
|
|
|
385
|
+
| **strategies** | `build` (memory, never a database), `create` (writes, answers the row AS STORED: declared defaults, generated columns, timestamps), `attributesFor` (an input: no primary key, no `belongsTo` key, no transient), `buildList` / `createList` |
|
|
386
|
+
| **sequence** | `index` (`n` above), per factory, shared by every `with()` view and `extend()` child — ids never repeat |
|
|
387
|
+
| **trait** | a named partial (or `(n, ids, transient) => partial`). `with('a', 'b')` composes left to right; a call's override wins. An undeclared one fails at `with()` (`X_TEST_FACTORY_TRAIT_UNKNOWN`) |
|
|
388
|
+
| **transient** | declared defaults a call may override; read by `defaults`, traits and callbacks; never written |
|
|
389
|
+
| **callbacks** | `afterBuild(row, ctx)` on both strategies before any write; `afterCreate(storedRow, ctx)` after the row and its children are stored |
|
|
390
|
+
| **inheritance** | `factory.extend({ defaults, traits, transient, hasMany, afterBuild, afterCreate })` — same table, same sequence, its defaults over the parent's, callbacks chained after |
|
|
391
|
+
| **`belongsTo`** | the parent made with the child's strategy; `{ org: row }` reuses a row; `{ orgId }` makes none. The `defaults` must name the key, so a key that is not a column does not compile |
|
|
392
|
+
| **`hasMany`** | `{ comments: 2 }` or `{ comments: [{ body: 'a' }, {}] }`: made after the parent, key set from the stored parent; on the answer as a non-enumerable `post.comments`, so the row itself `toEqual`s a read of the table |
|
|
393
|
+
| **tenant** | the tenant column follows the parent; the tenant's own association resolves first, so a comment, its post and its post's author share one org |
|
|
394
|
+
| **persister** | `create()` writes through the entity's own repository on `defaultDriver()`; an app that names its driver installs `usePersister(entityPersister({ driver }))` (or `{ client }`) once in its test preload |
|
|
395
|
+
| **seeded per table** | the default seed is derived from the table name, so two tables never draw the same uuid |
|
|
396
|
+
| **lint** | `await assertFactoriesValid({ orgFactory, postFactory, … })`: every factory and each trait alone, built and created against its entity on a throwaway driver; one `X_TEST_FACTORY_INVALID` naming each `factory.with('trait').strategy()` and the entity's own code |
|
|
397
|
+
| **seeds** | `factorySeed('demo', async ({ id }) => { await postFactory.create({ org: await orgFactory.create({ id: id('org:acme') }) }) })` is a `Seed` (`x db seed demo`, or `.run({ driver })`): every sequence restarts, every write is the seed's idempotent insert — a replay writes nothing |
|
|
304
398
|
|
|
305
399
|
`factoriesFor(registry)` builds one factory per registered entity, each value read off the
|
|
306
400
|
column's declaration — its default, an enumerated value, its kind, `null` only where nullable — and
|
|
@@ -396,26 +490,68 @@ failure line reads `publishPost > behaves like an authenticated action > denies
|
|
|
396
490
|
— which subject, and which shared rule. `behavesLike` calls `describe`, so it goes at declaration
|
|
397
491
|
scope, never inside a test body.
|
|
398
492
|
|
|
399
|
-
|
|
400
|
-
|
|
493
|
+
### Conformance: a port's contract
|
|
494
|
+
|
|
495
|
+
Every interface an app may implement has a suite on its own entry point,
|
|
496
|
+
`@ultimat3/testing/conformance` (off `.`: the suites statically import the packages they hold to).
|
|
497
|
+
A custom adapter proves itself with one file; the shipped ones run the same suite, memory in
|
|
498
|
+
`unit`, Postgres / Redis / S3 / NATS in `live`. Names match `ADAPTER_PORTS[].conformance`.
|
|
401
499
|
|
|
402
500
|
```ts
|
|
403
|
-
import {
|
|
404
|
-
import {
|
|
405
|
-
import {
|
|
501
|
+
import { memoryStorageDriver } from '@ultimat3/storage';
|
|
502
|
+
import { behavesLike, describe } from '@ultimat3/testing';
|
|
503
|
+
import { storageDriverConformance } from '@ultimat3/testing/conformance';
|
|
406
504
|
|
|
407
|
-
// The shipped
|
|
408
|
-
describe('my
|
|
409
|
-
describe('my budget store', () => behavesLike(budgetStoreConformance, () => memoryBudgetStore()));
|
|
505
|
+
// The shipped memory driver passes; put your own `StorageDriver` where it is.
|
|
506
|
+
describe('my disk', () => behavesLike(storageDriverConformance, () => memoryStorageDriver()));
|
|
410
507
|
```
|
|
411
508
|
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
| `jobDriverConformance` | claim once · ack/nack fenced on the claim · a live key dedupes · `queues: []` refused · dead-letter never re-claimed · a lapsed lease re-claimed, the loser unable to renew · a lease lapsed on the final attempt buried, reported through `onExhausted` once, `failed` under `dropExhausted` |
|
|
415
|
-
| `budgetStoreConformance` | 24 concurrent `take`s on one key never overspend · a refused take spends nothing · negative `add` · `reset(key)` scoped |
|
|
509
|
+
Each suite also exports its checks (`<PORT>_CHECKS`), so a test can run one against a subject that
|
|
510
|
+
is meant to FAIL it. The subject is called once per test.
|
|
416
511
|
|
|
417
|
-
|
|
418
|
-
|
|
512
|
+
| Interface (package) | Suite, as you call it |
|
|
513
|
+
|---|---|
|
|
514
|
+
| `AuditSink` (core) | `behavesLike(auditSinkConformance, () => ({ sink, kept, persists }))` |
|
|
515
|
+
| `AuthAdapter` (auth) | `behavesLike(authAdapterConformance, () => ({ adapter, clock }))` — `clock` is the `FrozenClock` it stamps from |
|
|
516
|
+
| `AuthLimiterFactory` (auth) | `behavesLike(authLimiterFactoryConformance, () => ({ factory, clock }))` |
|
|
517
|
+
| `AuthServerStore` (auth) | `behavesLike(authServerStoreConformance, () => store)` |
|
|
518
|
+
| `BudgetStore` (ai) | `behavesLike(budgetStoreConformance, () => store)` |
|
|
519
|
+
| `CacheTier` (cache) | `behavesLike(cacheTierConformance, () => tier)` — each check runs inside a request |
|
|
520
|
+
| entity `Driver` (entity) | `behavesLike(entityDriverConformance, () => ({ open: (entities) => driver, capabilities, foreignKeys }))` — `open` hands a driver over EMPTY tables for `entities`; an undeclared capability is asserted REFUSED |
|
|
521
|
+
| `ErrorGroupsStore` (admin) | `behavesLike(errorGroupsStoreConformance, () => store)` |
|
|
522
|
+
| `ErrorReporter` (core) | `behavesLike(errorReporterConformance, () => ({ reporter, delivered }))` — `delivered()` is the text each report left as; only a `localErrorSink`-marked reporter may carry a secret |
|
|
523
|
+
| `EventBus` (jobs) | `behavesLike(eventBusConformance, () => ({ bus, elapse }))` |
|
|
524
|
+
| `FailureStore` (core) | `behavesLike(failureStoreConformance, () => ({ store, find, client }))` |
|
|
525
|
+
| `Gateway` (ai) | `behavesLike(gatewayConformance, () => ({ gateway, model }))` |
|
|
526
|
+
| `IdempotencyStore` (action) | `behavesLike(idempotencyStoreConformance, () => ({ store, client, reclaimAfterMs, … }))` |
|
|
527
|
+
| `IdentityProvider` (auth) | `behavesLike(identityProviderConformance, () => ({ provider, callbackUrl, clock, answer, tamper }))` — the harness plays the IdP: `answer(redirect)` is a consenting user's callback params, `tamper(params)` alters their proof. Not an `ADAPTER_PORTS` row: an app holds several providers at once |
|
|
528
|
+
| `ImageTransformDriver` (seo) | `behavesLike(imageTransformDriverConformance, () => ({ driver, src }))` — `src` reads as `IMAGE_CONFORMANCE_SOURCE` (64×32 PNG) |
|
|
529
|
+
| `IsrStore` (render) | `behavesLike(isrStoreConformance, () => store)` — the tag-fence check runs only when `store.tagFence` exists |
|
|
530
|
+
| `JobDriver` (jobs) | `behavesLike(jobDriverConformance, () => driver)` |
|
|
531
|
+
| `LeaseStore` (jobs) | `behavesLike(leaseStoreConformance, () => ({ store, elapse }))` — every grant needs a `fence` greater than every earlier one, takeovers included (`withLock`'s token) |
|
|
532
|
+
| `MailDriver` (mail) | `behavesLike(mailDriverConformance, () => driver)` |
|
|
533
|
+
| `McpConfirmationStore` (mcp) | `behavesLike(mcpConfirmationStoreConformance, () => store)` |
|
|
534
|
+
| `MeterStore` (action) | `behavesLike(meterStoreConformance, () => store)` |
|
|
535
|
+
| `NotifyStores` (notify) | `behavesLike(notifyStoresConformance, () => ({ ledger, inbox, preferences, digest }))`; one store alone: `deliveryLedgerConformance`, `inboxStoreConformance`, `preferenceStoreConformance`, `digestStoreConformance` |
|
|
536
|
+
| `OutboxStore` (jobs) | `behavesLike(outboxStoreConformance, () => ({ relay, claimLeaseMs, transaction, elapse }))` |
|
|
537
|
+
| `Provider` (ai) | `behavesLike(providerConformance, () => ({ provider, model }))`; over HTTP also `providerTransportConformance` |
|
|
538
|
+
| `PurgeDriver` (cache) | `behavesLike(purgeDriverConformance, () => ({ driver, refused }))` — omit `refused` for noop |
|
|
539
|
+
| `PushDeviceStore` (notify) | `behavesLike(pushDeviceStoreConformance, () => store)` |
|
|
540
|
+
| `PushSubscriptionStore` (pwa) | `behavesLike(pushSubscriptionStoreConformance, () => store)` |
|
|
541
|
+
| `RateLimitStore` (http) | `behavesLike(rateLimitStoreConformance, () => store)` |
|
|
542
|
+
| `ScrapeDriver` (scraping) | `behavesLike(scrapeDriverConformance, () => driver)` — serving `SCRAPE_CONFORMANCE_PAGES` on `shop.test` |
|
|
543
|
+
| `SecretSource` (core) | `behavesLike(secretSourceConformance, () => ({ source, holding, empty }))` |
|
|
544
|
+
| `SmsTransport` (notify) | `behavesLike(smsTransportConformance, () => transport)` — `memorySmsTransport()` passes; a provider adapter (Twilio, Vonage, SNS) proves itself here |
|
|
545
|
+
| `SleepClock` (core) | `behavesLike(sleepClockConformance, () => clock)` |
|
|
546
|
+
| `StepStore` (jobs) | `behavesLike(stepStoreConformance, () => driver)` — any `JobDriver`; a lone store: `memoryJobDriver({ steps })` |
|
|
547
|
+
| `StorageDriver` (storage) | `behavesLike(storageDriverConformance, () => disk)` — checks write under `conformance/<uuid>/` |
|
|
548
|
+
| `TotpReplayGuard` (auth) | `behavesLike(totpReplayGuardConformance, () => guard)` |
|
|
549
|
+
| `Transport` (realtime) | `behavesLike(transportConformance, () => bus)` — fresh and open per test; the suite closes it |
|
|
550
|
+
| `VectorStore` (ai) | `behavesLike(vectorStoreConformance, () => store)` — unbound, `VECTOR_CONFORMANCE_DIMENSION` wide |
|
|
551
|
+
|
|
552
|
+
`elapse(ms)` is required — there is no real-time fallback: a memory store on a frozen clock passes
|
|
553
|
+
`clock.advance`; a database-clocked store moves its own rows back by `ms` (the Postgres
|
|
554
|
+
suites age `expires_at` / `claimed_at` / `published_at`), never a real sleep.
|
|
419
555
|
|
|
420
556
|
## Parallel databases
|
|
421
557
|
|
|
@@ -985,6 +1121,10 @@ declared edge and the reverse is a `bun run boundaries` failure.
|
|
|
985
1121
|
|
|
986
1122
|
## Launching Chrome
|
|
987
1123
|
|
|
1124
|
+
**Imported from `@ultimat3/scraping/cdp` since 31.0.0** — its one home, which `pdf()` prints
|
|
1125
|
+
through: `findChrome`, `launchChrome`, `CHROME_*`, `LAUNCH_*`, `LAUNCHED_CLOSE_MS`, `cdpConnect*` and
|
|
1126
|
+
the `Cdp*Error`s. Never re-exported here (`flight-copies`, `X_HELPER_COPY`).
|
|
1127
|
+
|
|
988
1128
|
`launchChrome({ executable, timeoutMs, launchTimeoutMs?, wire? })` — what the `e2e` step and `x shot`
|
|
989
1129
|
both start a browser with. Driven over `--remote-debugging-pipe`, and on Windows — where the parent
|
|
990
1130
|
cannot hold Chrome's fds 3 and 4 — over `--remote-debugging-port=0` and the profile's
|
|
@@ -1000,7 +1140,7 @@ on Linux, the app bundles on macOS, Chrome under `%ProgramFiles%` / `%ProgramFil
|
|
|
1000
1140
|
| `LAUNCH_ATTEMPTS` | `2` — an unanswered start is reaped and started once more on a fresh profile. Never more |
|
|
1001
1141
|
| `LAUNCH_BUDGET_MS` | derived: `LAUNCH_ATTEMPTS × (LAUNCH_TIMEOUT_MS + LAUNCH_REAP_MS)` — the longest a launch is designed to take, both starts and their bounded reaps |
|
|
1002
1142
|
| `E2E_BROWSER_OPEN_MS` | derived: `LAUNCH_BUDGET_MS` + the session's two setup calls + the first tab, at `DEFAULT_CDP_TIMEOUT_MS` each. THE deadline of every `beforeAll` that opens a browser — one below it is killed by Bun before the relaunch, and `X_CDP_LAUNCH_FAILED` never names the slow step |
|
|
1003
|
-
| `E2E_BROWSER_CLOSE_MS` | derived: `4 × CLOSE_GRACE_MS` — SIGTERM's grace, SIGKILL's, the group reap, the profile's removal. THE deadline of an `afterAll` that closes a browser it holds (one that releases a lease takes `E2E_BROWSER_OPEN_MS`: it may await the open). At Bun's 5 s default a close cut short by the run's end left the profile half-removed in the temp root |
|
|
1143
|
+
| `LAUNCHED_CLOSE_MS` (`@ultimat3/scraping/cdp`; was `E2E_BROWSER_CLOSE_MS`) | derived: `4 × CLOSE_GRACE_MS` — SIGTERM's grace, SIGKILL's, the group reap, the profile's removal. THE deadline of an `afterAll` that closes a browser it holds (one that releases a lease takes `E2E_BROWSER_OPEN_MS`: it may await the open). At Bun's 5 s default a close cut short by the run's end left the profile half-removed in the temp root |
|
|
1004
1144
|
| `E2E_TAB_OPEN_MS` | derived: one more `session.newTab()` — `Target.createTarget`, then its attach |
|
|
1005
1145
|
| `E2E_GOTO_MS` | derived: one `tab.goto()` — the navigate raced by the load event, then two reads of the document |
|
|
1006
1146
|
| `E2E_APP_START_MS` | derived: `startE2eApp()` at its default deadline — `x db reset`, `x db seed` and `/readyz` (wall-clock), each its whole 90 s, then a refused boot's stop |
|
|
@@ -1086,7 +1226,7 @@ a job boundary the class is gone and the `code` is what survives — match on th
|
|
|
1086
1226
|
|
|
1087
1227
|
## Log lines under test
|
|
1088
1228
|
|
|
1089
|
-
| `LOG_LEVEL` | The terminal shows | A
|
|
1229
|
+
| `LOG_LEVEL` | The terminal shows | A sink a test installs with `installLogSink` receives |
|
|
1090
1230
|
|---|---|---|
|
|
1091
1231
|
| unset | nothing — the reporter only | `info` and above |
|
|
1092
1232
|
| `info` | `info` and above | `info` and above |
|
|
@@ -1104,8 +1244,8 @@ what was named), and installs the filter. It is the preload's first import for t
|
|
|
1104
1244
|
|
|
1105
1245
|
`bun test` runs every file of one invocation in the same process — only `x verify`'s shards pass
|
|
1106
1246
|
`--isolate`. A file that leaves a process-global registry dirty therefore changes what every later
|
|
1107
|
-
file sees, and the failure lands on an innocent suite in another package: `bun test packages/query
|
|
1108
|
-
packages/cli
|
|
1247
|
+
file sees, and the failure lands on an innocent suite in another package: `bun test ./packages/query/
|
|
1248
|
+
./packages/cli/` failed five tests in `query`, all of them installed by `cli`, while either package
|
|
1109
1249
|
alone was green.
|
|
1110
1250
|
|
|
1111
1251
|
The preload installs the guard. It samples the cache tag set and the cache tier registry once per
|
|
@@ -1117,7 +1257,7 @@ X_TEST_REGISTRY_LEAK: a test file left a process-global registry dirty —
|
|
|
1117
1257
|
"packages/cli/src/cmd-dev.test.ts" left cache tags declared ["devfixture"] after its last test
|
|
1118
1258
|
fix: in "packages/cli/src/cmd-dev.test.ts" add: import { isolateDeclaredTags } from
|
|
1119
1259
|
'@ultimat3/cache'; const restoreTags = isolateDeclaredTags(); afterAll(restoreTags);
|
|
1120
|
-
— then re-run: bun test "packages/cli/src/cmd-dev.test.ts"
|
|
1260
|
+
— then re-run: bun test "./packages/cli/src/cmd-dev.test.ts"
|
|
1121
1261
|
```
|
|
1122
1262
|
|
|
1123
1263
|
The baseline is not a `beforeEach`: a file's own `beforeAll` runs **before** a preload's
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/testing",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "31.1.0",
|
|
4
4
|
"description": "Test harness: cloned template DBs per worker, frozen clock, sealed network, 6 test types",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ultimate",
|
|
@@ -25,6 +25,7 @@
|
|
|
25
25
|
},
|
|
26
26
|
"exports": {
|
|
27
27
|
".": "./src/index.ts",
|
|
28
|
+
"./conformance": "./src/conformance.ts",
|
|
28
29
|
"./preload": "./src/preload.ts",
|
|
29
30
|
"./e2e-preload": "./src/e2e-preload.ts",
|
|
30
31
|
"./registry-isolation": "./src/registry-isolation.ts",
|
|
@@ -46,21 +47,26 @@
|
|
|
46
47
|
"test": "bun test"
|
|
47
48
|
},
|
|
48
49
|
"dependencies": {
|
|
49
|
-
"@ultimat3/action": "
|
|
50
|
-
"@ultimat3/
|
|
51
|
-
"@ultimat3/
|
|
52
|
-
"@ultimat3/
|
|
53
|
-
"@ultimat3/
|
|
54
|
-
"@ultimat3/
|
|
55
|
-
"@ultimat3/
|
|
56
|
-
"@ultimat3/
|
|
57
|
-
"@ultimat3/
|
|
58
|
-
"@ultimat3/
|
|
59
|
-
"@ultimat3/
|
|
60
|
-
"@ultimat3/
|
|
61
|
-
"@ultimat3/
|
|
62
|
-
"@ultimat3/
|
|
63
|
-
"@ultimat3/
|
|
64
|
-
"@ultimat3/
|
|
50
|
+
"@ultimat3/action": "31.1.0",
|
|
51
|
+
"@ultimat3/ai": "31.1.0",
|
|
52
|
+
"@ultimat3/auth": "31.1.0",
|
|
53
|
+
"@ultimat3/cache": "31.1.0",
|
|
54
|
+
"@ultimat3/core": "31.1.0",
|
|
55
|
+
"@ultimat3/db": "31.1.0",
|
|
56
|
+
"@ultimat3/entity": "31.1.0",
|
|
57
|
+
"@ultimat3/http": "31.1.0",
|
|
58
|
+
"@ultimat3/i18n": "31.1.0",
|
|
59
|
+
"@ultimat3/jobs": "31.1.0",
|
|
60
|
+
"@ultimat3/mail": "31.1.0",
|
|
61
|
+
"@ultimat3/notify": "31.1.0",
|
|
62
|
+
"@ultimat3/policy": "31.1.0",
|
|
63
|
+
"@ultimat3/pwa": "31.1.0",
|
|
64
|
+
"@ultimat3/query": "31.1.0",
|
|
65
|
+
"@ultimat3/realtime": "31.1.0",
|
|
66
|
+
"@ultimat3/render": "31.1.0",
|
|
67
|
+
"@ultimat3/schema": "31.1.0",
|
|
68
|
+
"@ultimat3/scraping": "31.1.0",
|
|
69
|
+
"@ultimat3/seo": "31.1.0",
|
|
70
|
+
"@ultimat3/time": "31.1.0"
|
|
65
71
|
}
|
|
66
72
|
}
|