@ultimat3/testing 30.9.0 → 31.0.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 +30 -51
- package/src/exercise.ts +12 -6
- 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/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/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/stub.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// Single responsibility: `stub(primitive)` — the one test double for an action, an `llm()` (which
|
|
2
|
+
// IS an action), a query or a job. Its body answers from a script; everything around the body stays the
|
|
3
|
+
// real path, and the stub is put back after the test that made it (`test-scope.ts`).
|
|
4
|
+
|
|
5
|
+
import type { Action } from '@ultimat3/action';
|
|
6
|
+
import type { JobHandle } from '@ultimat3/jobs';
|
|
7
|
+
import { isJobHandle } from '@ultimat3/jobs';
|
|
8
|
+
import type { Query } from '@ultimat3/query';
|
|
9
|
+
import type { InferOutput, StandardSchemaV1 } from '@ultimat3/schema';
|
|
10
|
+
import { TestStubTargetUnsupportedError } from './stub-errors';
|
|
11
|
+
import { stubJobBody } from './stub-job';
|
|
12
|
+
import type { Stub, StubWiring } from './stub-script';
|
|
13
|
+
import { stubScript } from './stub-script';
|
|
14
|
+
import type { Undo } from './test-scope';
|
|
15
|
+
import { scopedInstall } from './test-scope';
|
|
16
|
+
|
|
17
|
+
const isCallableObject = (value: unknown): value is object =>
|
|
18
|
+
(typeof value === 'object' || typeof value === 'function') && value !== null;
|
|
19
|
+
|
|
20
|
+
async function install(
|
|
21
|
+
target: unknown,
|
|
22
|
+
wiring: (input: StandardSchemaV1) => StubWiring<unknown, unknown>,
|
|
23
|
+
): Promise<{ readonly stub: Stub<unknown, unknown>; readonly undo: Undo }> {
|
|
24
|
+
if (isJobHandle(target)) {
|
|
25
|
+
const wired = wiring(target.input);
|
|
26
|
+
return { stub: wired.stub, undo: stubJobBody(target, wired) };
|
|
27
|
+
}
|
|
28
|
+
// Loaded only now: the barrel stays action-free for a tier-0 test importing it for `expect`.
|
|
29
|
+
const { isAction } = await import('@ultimat3/action');
|
|
30
|
+
if (isAction(target)) {
|
|
31
|
+
const { stubActionHandler } = await import('./stub-action');
|
|
32
|
+
const wired = wiring(target.input);
|
|
33
|
+
return { stub: wired.stub, undo: await stubActionHandler(target, wired) };
|
|
34
|
+
}
|
|
35
|
+
const { isQuery } = await import('@ultimat3/query');
|
|
36
|
+
if (isQuery(target)) {
|
|
37
|
+
const { stubQueryRows } = await import('./stub-query');
|
|
38
|
+
const wired = wiring(target.input) as StubWiring<unknown, readonly object[]>;
|
|
39
|
+
return { stub: wired.stub, undo: await stubQueryRows(target, wired) };
|
|
40
|
+
}
|
|
41
|
+
throw new TestStubTargetUnsupportedError(target);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Replace `target`'s body for this test — inside a test, until it ends; outside one (`beforeAll`,
|
|
46
|
+
* module scope), until its file ends. `returns(...)` / `throws(error)` script the answers;
|
|
47
|
+
* `expect(stubbed).toHaveBeenCalledWith(input)` reads the calls.
|
|
48
|
+
*
|
|
49
|
+
* ```ts
|
|
50
|
+
* const charged = await stub(chargeCard);
|
|
51
|
+
* charged.returns({ chargeId: 'ch_1' });
|
|
52
|
+
* await checkout({ cartId }); // the real action, calling the stubbed one
|
|
53
|
+
* expect(charged).toHaveBeenCalledWith({ cartId, amount });
|
|
54
|
+
* ```
|
|
55
|
+
*/
|
|
56
|
+
export function stub<TInput extends StandardSchemaV1, TOutput extends StandardSchemaV1>(
|
|
57
|
+
target: Action<TInput, TOutput>,
|
|
58
|
+
): Promise<Stub<InferOutput<TInput>, InferOutput<TOutput>>>;
|
|
59
|
+
export function stub<TInput extends StandardSchemaV1, TRow extends object, TSingle extends boolean>(
|
|
60
|
+
target: Query<TInput, TRow, TSingle>,
|
|
61
|
+
): Promise<Stub<InferOutput<TInput>, readonly TRow[]>>;
|
|
62
|
+
export function stub<I>(target: JobHandle<I>): Promise<Stub<I, unknown>>;
|
|
63
|
+
export async function stub(target: unknown): Promise<Stub<unknown, unknown>> {
|
|
64
|
+
if (!isCallableObject(target)) throw new TestStubTargetUnsupportedError(target);
|
|
65
|
+
const name = (target as { readonly name?: unknown }).name;
|
|
66
|
+
const label = typeof name === 'string' ? name : '';
|
|
67
|
+
return scopedInstall(`stub(${label})`, async () => {
|
|
68
|
+
// Stubs STACK on a target (`stub-stack.ts`): a second one answers over the first, and its undo
|
|
69
|
+
// hands the first back — a file's stub survives a test's.
|
|
70
|
+
const { stub: made, undo } = await install(target, (input) => stubScript(label, input));
|
|
71
|
+
return { value: made, undo };
|
|
72
|
+
});
|
|
73
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// Single responsibility: `swapAdapter(port, impl)` — the one way a test replaces an adapter port
|
|
2
|
+
// (`ADAPTER_PORTS`, core's registrar) for itself: installed through the port's own `./adapter`
|
|
3
|
+
// installer, put back after the test (`test-scope.ts`). Every port is either bound here or listed in
|
|
4
|
+
// `UNSWAPPED` with what a test does instead — a new row in core's table is a compile error here.
|
|
5
|
+
|
|
6
|
+
import type { IdempotencyStore, MeterStore } from '@ultimat3/action/adapter';
|
|
7
|
+
import type { Embedder, Gateway, SemanticCacheFactory } from '@ultimat3/ai/adapter';
|
|
8
|
+
import type { AuthLimiterFactory, TotpReplayGuard } from '@ultimat3/auth/adapter';
|
|
9
|
+
import type { AdapterPortName } from '@ultimat3/core';
|
|
10
|
+
import type {
|
|
11
|
+
AuditSink,
|
|
12
|
+
ErrorReporter,
|
|
13
|
+
FailureStore,
|
|
14
|
+
SecretSource,
|
|
15
|
+
SleepClock,
|
|
16
|
+
} from '@ultimat3/core/adapter';
|
|
17
|
+
import type { SearchIndex } from '@ultimat3/entity/adapter';
|
|
18
|
+
import type { RateLimitStore } from '@ultimat3/http/adapter';
|
|
19
|
+
import type { EventBus, JobDriver } from '@ultimat3/jobs/adapter';
|
|
20
|
+
import type { MailDriver } from '@ultimat3/mail/adapter';
|
|
21
|
+
import type { NotifyStores, SmsTransport } from '@ultimat3/notify/adapter';
|
|
22
|
+
import type { Transport } from '@ultimat3/realtime/adapter';
|
|
23
|
+
import type { ScrapeDriver } from '@ultimat3/scraping/adapter';
|
|
24
|
+
import { TestAdapterPortUnswappableError } from './stub-errors';
|
|
25
|
+
import type { Undo } from './test-scope';
|
|
26
|
+
import { scopedInstall } from './test-scope';
|
|
27
|
+
|
|
28
|
+
/** What each process-global port takes. The key is the `ADAPTER_PORTS` row's `port`. */
|
|
29
|
+
export interface SwappableAdapters {
|
|
30
|
+
readonly aiGateway: Gateway;
|
|
31
|
+
readonly auditSink: AuditSink;
|
|
32
|
+
readonly authLimiter: AuthLimiterFactory;
|
|
33
|
+
readonly clock: SleepClock;
|
|
34
|
+
readonly embedder: Embedder;
|
|
35
|
+
readonly errorReporter: ErrorReporter;
|
|
36
|
+
readonly eventBus: EventBus;
|
|
37
|
+
readonly failureStore: FailureStore;
|
|
38
|
+
readonly idempotencyStore: IdempotencyStore;
|
|
39
|
+
readonly jobs: JobDriver;
|
|
40
|
+
readonly mail: MailDriver;
|
|
41
|
+
readonly meterStore: MeterStore;
|
|
42
|
+
readonly notifyStores: NotifyStores;
|
|
43
|
+
readonly rateLimitStore: RateLimitStore;
|
|
44
|
+
readonly scrapeDriver: ScrapeDriver;
|
|
45
|
+
readonly searchIndex: SearchIndex;
|
|
46
|
+
readonly secretSource: SecretSource;
|
|
47
|
+
readonly semanticCache: SemanticCacheFactory;
|
|
48
|
+
readonly smsTransport: SmsTransport;
|
|
49
|
+
readonly totpReplay: TotpReplayGuard;
|
|
50
|
+
readonly transport: Transport;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The ports `swapAdapter` takes. Every one is a row of `ADAPTER_PORTS`, or this fails to compile. */
|
|
54
|
+
export type SwappablePort = keyof SwappableAdapters & AdapterPortName;
|
|
55
|
+
|
|
56
|
+
type Bindings = { readonly [P in SwappablePort]: (impl: SwappableAdapters[P]) => Promise<Undo> };
|
|
57
|
+
|
|
58
|
+
// Every installer answers its own release, restoring the value it replaced.
|
|
59
|
+
const BINDINGS: Bindings = {
|
|
60
|
+
aiGateway: async (impl) => (await import('@ultimat3/ai/adapter')).installAiGateway(impl),
|
|
61
|
+
auditSink: async (impl) => (await import('@ultimat3/core/adapter')).installAuditSink(impl),
|
|
62
|
+
authLimiter: async (impl) => (await import('@ultimat3/auth/adapter')).installAuthLimiters(impl),
|
|
63
|
+
clock: async (impl) => (await import('@ultimat3/core/adapter')).installClock(impl),
|
|
64
|
+
embedder: async (impl) => (await import('@ultimat3/ai/adapter')).installAiEmbedder(impl),
|
|
65
|
+
errorReporter: async (impl) =>
|
|
66
|
+
(await import('@ultimat3/core/adapter')).installErrorReporter(impl),
|
|
67
|
+
eventBus: async (impl) => (await import('@ultimat3/jobs/adapter')).installEventBus(impl),
|
|
68
|
+
failureStore: async (impl) => (await import('@ultimat3/core/adapter')).installFailureStore(impl),
|
|
69
|
+
idempotencyStore: async (impl) =>
|
|
70
|
+
(await import('@ultimat3/action/adapter')).installIdempotencyStore(impl),
|
|
71
|
+
jobs: async (impl) => (await import('@ultimat3/jobs/adapter')).installJobDriver(impl),
|
|
72
|
+
mail: async (impl) => (await import('@ultimat3/mail/adapter')).installMailDriver(impl),
|
|
73
|
+
meterStore: async (impl) => (await import('@ultimat3/action/adapter')).installMeterStore(impl),
|
|
74
|
+
notifyStores: async (impl) =>
|
|
75
|
+
(await import('@ultimat3/notify/adapter')).installNotifyStores(impl),
|
|
76
|
+
rateLimitStore: async (impl) =>
|
|
77
|
+
(await import('@ultimat3/http/adapter')).installRateLimitStore(impl),
|
|
78
|
+
scrapeDriver: async (impl) =>
|
|
79
|
+
(await import('@ultimat3/scraping/adapter')).installScrapeDriver(impl),
|
|
80
|
+
searchIndex: async (impl) => (await import('@ultimat3/entity/adapter')).installSearchIndex(impl),
|
|
81
|
+
secretSource: async (impl) => (await import('@ultimat3/core/adapter')).installSecretSource(impl),
|
|
82
|
+
semanticCache: async (impl) => (await import('@ultimat3/ai/adapter')).installSemanticCache(impl),
|
|
83
|
+
smsTransport: async (impl) =>
|
|
84
|
+
(await import('@ultimat3/notify/adapter')).installSmsTransport(impl),
|
|
85
|
+
// The slot takes a factory; the port carries one guard, which every call hands back.
|
|
86
|
+
totpReplay: async (impl) =>
|
|
87
|
+
(await import('@ultimat3/auth/adapter')).installTotpReplay(() => impl),
|
|
88
|
+
transport: async (impl) =>
|
|
89
|
+
(await import('@ultimat3/realtime/adapter')).installChannelTransport(impl),
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* The ports with no process-global slot a test could borrow, each with what a test does instead.
|
|
94
|
+
* A `Record` over the rest of `AdapterPortName`: a port added to core's table is a compile error
|
|
95
|
+
* until it is bound above or given its instruction here.
|
|
96
|
+
*/
|
|
97
|
+
export const UNSWAPPED: Readonly<Record<Exclude<AdapterPortName, SwappablePort>, string>> = {
|
|
98
|
+
authServerStore:
|
|
99
|
+
'passed to the authorization server when the app builds it: build one over a memory store in the test',
|
|
100
|
+
cacheTiers:
|
|
101
|
+
"registered by the boot from cache.tiers: register the test's tier with @ultimat3/cache's isolateTiers()",
|
|
102
|
+
images:
|
|
103
|
+
'handed to the image route when the boot mounts it: call the route with your driver in the test',
|
|
104
|
+
isrStore: 'handed to the renderer at boot: pass your store to the render call under test',
|
|
105
|
+
mcpConfirmationStore:
|
|
106
|
+
'handed to the MCP server when the boot builds it: build the server with your store in the test',
|
|
107
|
+
outboxStore: "the boot's outbox relay takes it: build the relay with your store in the test",
|
|
108
|
+
purge: "handed to the cache's CDN purge at boot: pass your driver to the bust under test",
|
|
109
|
+
pushSubscriptionStore: 'the push fixture owns one: destructure { push } in the test',
|
|
110
|
+
storage: 'disks are built by the boot: build the disk over your driver in the test',
|
|
111
|
+
uploadScanner:
|
|
112
|
+
'@ultimat3/testing takes no dependency on @ultimat3/storage: call installUploadScanner(scanner) from @ultimat3/storage/adapter in the test and run the release it answers in afterEach',
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
const isSwappable = (port: string): port is SwappablePort => Object.hasOwn(BINDINGS, port);
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Replace a port's adapter for this test — inside a test, until it ends; outside one, until the
|
|
119
|
+
* file ends — and hand back `impl`, so the swap and the reference are one line:
|
|
120
|
+
*
|
|
121
|
+
* ```ts
|
|
122
|
+
* const queue = await swapAdapter('jobs', memoryJobDriver());
|
|
123
|
+
* ```
|
|
124
|
+
*/
|
|
125
|
+
export async function swapAdapter<P extends SwappablePort>(
|
|
126
|
+
port: P,
|
|
127
|
+
impl: SwappableAdapters[P],
|
|
128
|
+
): Promise<SwappableAdapters[P]> {
|
|
129
|
+
if (!isSwappable(port)) throw new TestAdapterPortUnswappableError(port, UNSWAPPED);
|
|
130
|
+
const install = BINDINGS[port] as (next: SwappableAdapters[P]) => Promise<Undo>;
|
|
131
|
+
return scopedInstall(`swapAdapter('${port}')`, async () => ({
|
|
132
|
+
value: impl,
|
|
133
|
+
undo: await install(impl),
|
|
134
|
+
}));
|
|
135
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// Single responsibility: WHEN a test double is put back. A stub or a swapped adapter made inside a
|
|
2
|
+
// test is undone after that test; one made outside any test (a `beforeAll`, module scope) after its
|
|
3
|
+
// FILE. The preload's own hooks do it, so no test file writes an `afterEach` that a skipped block
|
|
4
|
+
// could leave unreached (`X_SKIP_CLEANUP_UNREACHED`'s defect, made impossible rather than refused).
|
|
5
|
+
|
|
6
|
+
import { afterEach, beforeEach } from 'bun:test';
|
|
7
|
+
import { onFileBoundary } from './file-boundary';
|
|
8
|
+
import { TestScopeUninstalledError } from './stub-errors';
|
|
9
|
+
|
|
10
|
+
/** Puts one double back. Synchronous: a file boundary cannot await, and no installer needs to. */
|
|
11
|
+
export type Undo = () => void;
|
|
12
|
+
|
|
13
|
+
let installed = false;
|
|
14
|
+
let inTest = false;
|
|
15
|
+
const testUndos: Undo[] = [];
|
|
16
|
+
const fileUndos: Undo[] = [];
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Last made, first undone — two swaps of one port inside one test unwind to the value the test
|
|
20
|
+
* found. Every undo runs even when one throws; the first throw is what the caller sees.
|
|
21
|
+
*/
|
|
22
|
+
function unwind(undos: Undo[]): void {
|
|
23
|
+
let first: { readonly error: unknown } | undefined;
|
|
24
|
+
for (let undo = undos.pop(); undo !== undefined; undo = undos.pop()) {
|
|
25
|
+
try {
|
|
26
|
+
undo();
|
|
27
|
+
} catch (error) {
|
|
28
|
+
first ??= { error };
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
if (first !== undefined) throw first.error;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Hand `undo` to the scope that is open now: the running test's, else the file's. Refused — never
|
|
36
|
+
* silently kept — in a process the testing preload did not set up: nothing would ever run it, and
|
|
37
|
+
* the double would answer for every later file on the worker.
|
|
38
|
+
*/
|
|
39
|
+
export function deferRestore(what: string, undo: Undo): void {
|
|
40
|
+
if (!installed) throw new TestScopeUninstalledError(what);
|
|
41
|
+
(inTest ? testUndos : fileUndos).push(undo);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* `deferRestore` for an install that has to AWAIT (a module loaded on first use). The undo is
|
|
46
|
+
* registered first, so a missing preload refuses before anything changes; and when the scope ends
|
|
47
|
+
* while the install is still in flight — a test that timed out on a cold import — the install that
|
|
48
|
+
* lands afterwards is undone the moment it lands, never left to answer for every later test.
|
|
49
|
+
*/
|
|
50
|
+
export async function scopedInstall<T>(
|
|
51
|
+
what: string,
|
|
52
|
+
install: () => Promise<{ readonly value: T; readonly undo: Undo }>,
|
|
53
|
+
): Promise<T> {
|
|
54
|
+
let closed = false;
|
|
55
|
+
let undo: Undo | undefined;
|
|
56
|
+
deferRestore(what, () => {
|
|
57
|
+
closed = true;
|
|
58
|
+
undo?.();
|
|
59
|
+
});
|
|
60
|
+
const installed = await install();
|
|
61
|
+
if (closed) installed.undo();
|
|
62
|
+
else undo = installed.undo;
|
|
63
|
+
return installed.value;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Whether a double made now is the running test's (`true`) or its file's (`false`). */
|
|
67
|
+
export function inTestScope(): boolean {
|
|
68
|
+
return inTest;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The test's half, run by the preload's `afterEach`. Exported for this package's own tests. */
|
|
72
|
+
export function endTestScope(): void {
|
|
73
|
+
inTest = false;
|
|
74
|
+
unwind(testUndos);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The file's half, run at the boundary before the next file — after its tests' halves. */
|
|
78
|
+
export function endFileScope(): void {
|
|
79
|
+
endTestScope();
|
|
80
|
+
unwind(fileUndos);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Called once per process by both preloads, through `installPerTestReset`. A preload's
|
|
85
|
+
* `beforeEach` runs before a file's own and its `afterEach` after, so a file's `afterEach` still
|
|
86
|
+
* sees its stubs and nothing it made outlives the test.
|
|
87
|
+
*/
|
|
88
|
+
export function installTestScope(): void {
|
|
89
|
+
if (installed) return;
|
|
90
|
+
installed = true;
|
|
91
|
+
beforeEach(() => {
|
|
92
|
+
inTest = true;
|
|
93
|
+
});
|
|
94
|
+
afterEach(endTestScope);
|
|
95
|
+
onFileBoundary(endFileScope);
|
|
96
|
+
}
|
package/src/test-types.ts
CHANGED
|
@@ -155,7 +155,7 @@ export const hasE2eDriver = (): boolean => e2eDriver !== undefined;
|
|
|
155
155
|
* Put the seam back. The counterpart `useE2eDriver` shipped without, and the module scope it
|
|
156
156
|
* writes to is process-global: `bun test` shares one process across files, so a file that installs
|
|
157
157
|
* a browser and does not undo it hands every later file an `e2eTest` that opens a page nobody
|
|
158
|
-
* asked for. Same shape and same reason as `@ultimat3/scraping
|
|
158
|
+
* asked for. Same shape and same reason as `resetScrapeDriver()` on `@ultimat3/scraping/adapter`.
|
|
159
159
|
*/
|
|
160
160
|
export const resetE2eDriver = (): void => {
|
|
161
161
|
e2eDriver = undefined;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// The `TotpReplayGuard` contract of `@ultimat3/auth` as shared examples, for a guard of your own:
|
|
2
|
+
// `behavesLike(totpReplayGuardConformance, () => guard)`. One atomic claim per (subject, step): a
|
|
3
|
+
// code is single-use across every replica that shares the guard, and two concurrent completions
|
|
4
|
+
// carrying one code admit exactly one.
|
|
5
|
+
|
|
6
|
+
import { expect, test } from 'bun:test';
|
|
7
|
+
import type { TotpReplayGuard } from '@ultimat3/auth/adapter';
|
|
8
|
+
import type { SharedExamples } from './shared-examples';
|
|
9
|
+
import { sharedExamples } from './shared-examples';
|
|
10
|
+
|
|
11
|
+
export interface TotpReplayGuardCheck {
|
|
12
|
+
readonly name: string;
|
|
13
|
+
run(guard: TotpReplayGuard): Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** A TOTP step is 30 s. `at` and `step` agree, as `verifyTotp` hands them over. */
|
|
17
|
+
const STEP_MS = 30_000;
|
|
18
|
+
const AT = new Date('2031-03-04T05:06:00.000Z');
|
|
19
|
+
const STEP = Math.floor(AT.getTime() / STEP_MS);
|
|
20
|
+
const later = (steps: number): Date => new Date(AT.getTime() + steps * STEP_MS);
|
|
21
|
+
const RACERS = 10;
|
|
22
|
+
|
|
23
|
+
/** A subject no other check, run or process shares — a shared table holds every run's steps. */
|
|
24
|
+
const subjectOf = (label: string): string => `conformance:${label}:${crypto.randomUUID()}`;
|
|
25
|
+
|
|
26
|
+
export const TOTP_REPLAY_GUARD_CHECKS: readonly TotpReplayGuardCheck[] = [
|
|
27
|
+
{
|
|
28
|
+
name: 'the first claim of a step is true, every repeat is false',
|
|
29
|
+
async run(guard) {
|
|
30
|
+
const subject = subjectOf('once');
|
|
31
|
+
expect(await guard.claim(subject, STEP, AT)).toBe(true);
|
|
32
|
+
expect(await guard.claim(subject, STEP, AT)).toBe(false);
|
|
33
|
+
expect(await guard.claim(subject, STEP, later(1))).toBe(false);
|
|
34
|
+
},
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
name: 'a step is spent per subject, and a neighbouring step is its own',
|
|
38
|
+
async run(guard) {
|
|
39
|
+
const [ada, grace] = [subjectOf('ada'), subjectOf('grace')];
|
|
40
|
+
expect(await guard.claim(ada, STEP, AT)).toBe(true);
|
|
41
|
+
expect(await guard.claim(grace, STEP, AT)).toBe(true);
|
|
42
|
+
expect(await guard.claim(ada, STEP + 1, AT)).toBe(true);
|
|
43
|
+
expect(await guard.claim(ada, STEP - 1, AT)).toBe(true);
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
name: 'a step spent stays spent while the drift window can still offer it',
|
|
48
|
+
async run(guard) {
|
|
49
|
+
const subject = subjectOf('window');
|
|
50
|
+
expect(await guard.claim(subject, STEP, AT)).toBe(true);
|
|
51
|
+
expect(await guard.claim(subject, STEP + 1, later(1))).toBe(true);
|
|
52
|
+
// One step on, `verifyTotp` with the default drift still offers STEP: it must still be spent.
|
|
53
|
+
expect(await guard.claim(subject, STEP, later(1))).toBe(false);
|
|
54
|
+
},
|
|
55
|
+
},
|
|
56
|
+
{
|
|
57
|
+
name: `${RACERS} concurrent claims of one step: exactly one is true`,
|
|
58
|
+
async run(guard) {
|
|
59
|
+
const subject = subjectOf('race');
|
|
60
|
+
const answers = await Promise.all(
|
|
61
|
+
Array.from({ length: RACERS }, () => guard.claim(subject, STEP, AT)),
|
|
62
|
+
);
|
|
63
|
+
expect(answers.filter(Boolean)).toHaveLength(1);
|
|
64
|
+
},
|
|
65
|
+
},
|
|
66
|
+
];
|
|
67
|
+
|
|
68
|
+
export const totpReplayGuardConformance: SharedExamples<
|
|
69
|
+
TotpReplayGuard | Promise<TotpReplayGuard>
|
|
70
|
+
> = sharedExamples('a TOTP replay guard', (subject) => {
|
|
71
|
+
for (const check of TOTP_REPLAY_GUARD_CHECKS) {
|
|
72
|
+
test(check.name, async () => {
|
|
73
|
+
await check.run(await subject());
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
});
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
// The realtime `Transport` contract as shared examples: `behavesLike(transportConformance, () =>
|
|
2
|
+
// bus)`. The subject is a FRESH, open transport per test, closed by the suite. Delivery may be
|
|
3
|
+
// asynchronous (a real bus), so every "did not arrive" is proved by a later sentinel that did — one
|
|
4
|
+
// connection's messages arrive in order — never by waiting a while and calling silence an answer.
|
|
5
|
+
|
|
6
|
+
import { expect, test } from 'bun:test';
|
|
7
|
+
import { isUltimateError } from '@ultimat3/core';
|
|
8
|
+
import type { Transport } from '@ultimat3/realtime/adapter';
|
|
9
|
+
import type { SharedExamples } from './shared-examples';
|
|
10
|
+
import { sharedExamples } from './shared-examples';
|
|
11
|
+
|
|
12
|
+
export interface TransportCheck {
|
|
13
|
+
readonly name: string;
|
|
14
|
+
run(transport: Transport): Promise<void>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Real milliseconds: a bus delivers on its own socket, whatever the preload froze. */
|
|
18
|
+
const POLL_MS = 5;
|
|
19
|
+
const POLLS = 400;
|
|
20
|
+
|
|
21
|
+
const arrived = async (done: () => boolean): Promise<void> => {
|
|
22
|
+
for (let poll = 0; poll < POLLS && !done(); poll += 1) await Bun.sleep(POLL_MS);
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/** A subject root no other check, file or process on a shared server publishes under. */
|
|
26
|
+
const rootOf = (): string => `xconf.${Bun.randomUUIDv7().replaceAll('-', '')}`;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Every subject a check composes, joined in one place. A `Transport` is BELOW `channel()` — that
|
|
30
|
+
* declaration maps onto these raw bus subjects — so the suite has no declaration to pass, only the
|
|
31
|
+
* one spelling rule: tokens joined by `.`, the wildcard a token of its own.
|
|
32
|
+
*/
|
|
33
|
+
const subjectOf = (...tokens: readonly string[]): string => tokens.join('.');
|
|
34
|
+
|
|
35
|
+
const codeOf = (value: unknown): string =>
|
|
36
|
+
isUltimateError(value) ? value.code : `not an UltimateError: ${String(value)}`;
|
|
37
|
+
|
|
38
|
+
const refusal = (pending: Promise<unknown>): Promise<unknown> =>
|
|
39
|
+
pending.then(
|
|
40
|
+
() => 'answered',
|
|
41
|
+
(error: unknown) => error,
|
|
42
|
+
);
|
|
43
|
+
|
|
44
|
+
export const TRANSPORT_CHECKS: readonly TransportCheck[] = [
|
|
45
|
+
{
|
|
46
|
+
name: 'a publish reaches a subscriber on its exact subject, payload byte for byte',
|
|
47
|
+
async run(bus) {
|
|
48
|
+
const subject = `${rootOf()}.change`;
|
|
49
|
+
const payload = '{"id":"p1","title":"Grüße — 東京 🚀"}';
|
|
50
|
+
const seen: string[] = [];
|
|
51
|
+
await bus.subscribe(subject, (body, on) => seen.push(`${on}=${body}`));
|
|
52
|
+
await bus.publish(subject, payload);
|
|
53
|
+
await arrived(() => seen.length > 0);
|
|
54
|
+
expect(seen).toEqual([`${subject}=${payload}`]);
|
|
55
|
+
},
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
name: '`*` matches exactly one token and `>` one or more trailing ones',
|
|
59
|
+
async run(bus) {
|
|
60
|
+
const root = rootOf();
|
|
61
|
+
const [star, tail]: [string[], string[]] = [[], []];
|
|
62
|
+
await bus.subscribe(subjectOf(root, '*'), (_body, on) => star.push(on));
|
|
63
|
+
await bus.subscribe(subjectOf(root, '>'), (_body, on) => tail.push(on));
|
|
64
|
+
for (const leaf of ['a', 'a.b', 'end']) await bus.publish(subjectOf(root, leaf), leaf);
|
|
65
|
+
await bus.publish(root, 'the root itself matches neither');
|
|
66
|
+
await arrived(() => tail.includes(`${root}.end`) && star.includes(`${root}.end`));
|
|
67
|
+
expect([star, tail]).toEqual([
|
|
68
|
+
[`${root}.a`, `${root}.end`],
|
|
69
|
+
[`${root}.a`, `${root}.a.b`, `${root}.end`],
|
|
70
|
+
]);
|
|
71
|
+
},
|
|
72
|
+
},
|
|
73
|
+
{
|
|
74
|
+
name: 'a subscriber hears only the subjects it asked for',
|
|
75
|
+
async run(bus) {
|
|
76
|
+
const root = rootOf();
|
|
77
|
+
const seen: string[] = [];
|
|
78
|
+
await bus.subscribe(subjectOf(root, 'comments', '*'), (body) => seen.push(body));
|
|
79
|
+
await bus.publish(subjectOf(root, 'posts', 'org-1'), 'wrong entity');
|
|
80
|
+
await bus.publish(subjectOf(root, 'comments', 'org-1'), 'right entity');
|
|
81
|
+
await arrived(() => seen.length > 0);
|
|
82
|
+
expect(seen).toEqual(['right entity']);
|
|
83
|
+
},
|
|
84
|
+
},
|
|
85
|
+
{
|
|
86
|
+
name: 'every subscriber on one subject hears it, and an unsubscribed one stops hearing',
|
|
87
|
+
async run(bus) {
|
|
88
|
+
const subject = `${rootOf()}.fanout`;
|
|
89
|
+
const [kept, dropped]: [string[], string[]] = [[], []];
|
|
90
|
+
await bus.subscribe(subject, (body) => kept.push(body));
|
|
91
|
+
const leaving = await bus.subscribe(subject, (body) => dropped.push(body));
|
|
92
|
+
await bus.publish(subject, 'one');
|
|
93
|
+
await arrived(() => kept.length === 1 && dropped.length === 1);
|
|
94
|
+
leaving.unsubscribe();
|
|
95
|
+
await bus.publish(subject, 'two');
|
|
96
|
+
await arrived(() => kept.length === 2);
|
|
97
|
+
expect([kept, dropped]).toEqual([['one', 'two'], ['one']]);
|
|
98
|
+
},
|
|
99
|
+
},
|
|
100
|
+
{
|
|
101
|
+
name: 'a subscriber that throws does not cost the others their message',
|
|
102
|
+
async run(bus) {
|
|
103
|
+
const subject = `${rootOf()}.faulty`;
|
|
104
|
+
const seen: string[] = [];
|
|
105
|
+
// A listener that cannot parse what it was sent — the throw an app's subscriber really makes.
|
|
106
|
+
await bus.subscribe(subject, (body) => JSON.parse(body));
|
|
107
|
+
await bus.subscribe(subject, (body) => seen.push(body));
|
|
108
|
+
await bus.publish(subject, 'still delivered');
|
|
109
|
+
await bus.publish(subject, 'and the next one');
|
|
110
|
+
await arrived(() => seen.length === 2);
|
|
111
|
+
expect(seen).toEqual(['still delivered', 'and the next one']);
|
|
112
|
+
},
|
|
113
|
+
},
|
|
114
|
+
{
|
|
115
|
+
name: 'shared: put lists a member with its value; touch answers whether it was live',
|
|
116
|
+
async run(bus) {
|
|
117
|
+
const key = `${rootOf()}.presence`;
|
|
118
|
+
await bus.shared.put(key, 'm1', '{"actorId":"alice"}', 30_000);
|
|
119
|
+
await bus.shared.put(key, 'm2', '{"actorId":"bob"}', 30_000);
|
|
120
|
+
const listed = await bus.shared.entries(key);
|
|
121
|
+
expect(listed.map((entry) => [entry.member, entry.value]).sort()).toEqual([
|
|
122
|
+
['m1', '{"actorId":"alice"}'],
|
|
123
|
+
['m2', '{"actorId":"bob"}'],
|
|
124
|
+
]);
|
|
125
|
+
expect([
|
|
126
|
+
await bus.shared.touch(key, 'm1', 30_000),
|
|
127
|
+
await bus.shared.touch(key, 'ghost', 30_000),
|
|
128
|
+
]).toEqual([true, false]);
|
|
129
|
+
},
|
|
130
|
+
},
|
|
131
|
+
{
|
|
132
|
+
name: 'shared: drop removes one member, a dotted member id survives, an unknown key is empty',
|
|
133
|
+
async run(bus) {
|
|
134
|
+
const key = `${rootOf()}.room`;
|
|
135
|
+
await bus.shared.put(key, 'socket.7', 'dotted', 30_000);
|
|
136
|
+
await bus.shared.put(key, 'plain', 'kept', 30_000);
|
|
137
|
+
await bus.shared.drop(key, 'plain');
|
|
138
|
+
expect((await bus.shared.entries(key)).map((entry) => entry.member)).toEqual(['socket.7']);
|
|
139
|
+
expect(await bus.shared.entries(`${rootOf()}.nobody`)).toEqual([]);
|
|
140
|
+
await bus.shared.drop(key, 'socket.7');
|
|
141
|
+
expect(await bus.shared.entries(key)).toEqual([]);
|
|
142
|
+
},
|
|
143
|
+
},
|
|
144
|
+
{
|
|
145
|
+
name: 'onReconnect hands back an unsubscribe that can be called',
|
|
146
|
+
async run(bus) {
|
|
147
|
+
const stop = bus.onReconnect(() => undefined);
|
|
148
|
+
expect(typeof stop).toBe('function');
|
|
149
|
+
stop();
|
|
150
|
+
},
|
|
151
|
+
},
|
|
152
|
+
{
|
|
153
|
+
name: 'a closed transport refuses publish and subscribe with X_TRANSPORT_UNAVAILABLE',
|
|
154
|
+
async run(bus) {
|
|
155
|
+
const subject = `${rootOf()}.closed`;
|
|
156
|
+
await bus.close();
|
|
157
|
+
expect(codeOf(await refusal(bus.publish(subject, '{}')))).toBe('X_TRANSPORT_UNAVAILABLE');
|
|
158
|
+
expect(codeOf(await refusal(bus.subscribe(subject, () => undefined)))).toBe(
|
|
159
|
+
'X_TRANSPORT_UNAVAILABLE',
|
|
160
|
+
);
|
|
161
|
+
},
|
|
162
|
+
},
|
|
163
|
+
];
|
|
164
|
+
|
|
165
|
+
export const transportConformance: SharedExamples<Transport | Promise<Transport>> = sharedExamples(
|
|
166
|
+
'a realtime transport',
|
|
167
|
+
(subject) => {
|
|
168
|
+
for (const check of TRANSPORT_CHECKS) {
|
|
169
|
+
test(check.name, async () => {
|
|
170
|
+
const bus = await subject();
|
|
171
|
+
try {
|
|
172
|
+
await check.run(bus);
|
|
173
|
+
} finally {
|
|
174
|
+
await bus.close();
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
},
|
|
179
|
+
);
|