@rexezuge/testing 1.11.0 → 1.13.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/README.md +104 -0
- package/package.json +4 -4
package/README.md
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
# @rexezuge/testing
|
|
2
|
+
|
|
3
|
+
Test doubles for the Rexezuge-CloudflareWorkers family, in one **dev-only** package. Thirteen repos copied the
|
|
4
|
+
same `cloudflare:workers` mock, a dozen hand-rolled `{ prepare: vi.fn().mockReturnValue(stmt) }` D1 objects, and
|
|
5
|
+
each wrote its own Access-token signing for auth tests. This package is the one definition.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pnpm add -D @rexezuge/testing
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Production code never imports it. `@rexezuge/http`, `@rexezuge/runtime` and `@rexezuge/shared` are its dependencies
|
|
12
|
+
(it re-exports their `/testing` seams and the `Clock` / `IdGenerator` doubles).
|
|
13
|
+
|
|
14
|
+
| Export | Replaces |
|
|
15
|
+
| -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
|
|
16
|
+
| `DurableObject`, `RpcTarget`, `WorkflowEntrypoint` | `test/mocks/cloudflare-workers.ts` (13 copies; also `/cloudflare-workers`) |
|
|
17
|
+
| `createMemoryD1()` | the hand-rolled fake D1 |
|
|
18
|
+
| `createMemoryKv({ now? })` | hand-rolled `KVNamespace` maps |
|
|
19
|
+
| `FixedClock`, `FixedIdGenerator` | local clocks and id queues (re-exported from `@rexezuge/shared`) |
|
|
20
|
+
| `forgeAccessJwt`, `accessJwksFetch`, `forgeAccessRequest`, `accessJwks` | `jose` `SignJWT` + a stubbed JWKS `fetch` |
|
|
21
|
+
| `createTestApp(app, { env, headers })`, `requestJson` | `app.fetch(new Request(...), env, ctx)` boilerplate |
|
|
22
|
+
| `resetAllForTests`, `resetRateLimitForTests`, `getRateLimitBucketCountForTests`, `resetBreakerForTests`, `resetLogLevelForTests` | the `/testing` seams of `http` and `runtime` |
|
|
23
|
+
|
|
24
|
+
## The `cloudflare:workers` mock
|
|
25
|
+
|
|
26
|
+
A superset of every family copy: `DurableObject` and `WorkflowEntrypoint` store `ctx` and `env` (so a real subclass can be
|
|
27
|
+
constructed and driven without Miniflare), `RpcTarget` is empty (a missing base is a module-load failure, not a test failure), and
|
|
28
|
+
`WorkflowEntrypoint#run` is a no-op. **Delete your `test/mocks/cloudflare-workers.ts`**: `defineUnitVitestConfig` and
|
|
29
|
+
`defineRepoVitestConfig` from `@rexezuge/tooling` alias `cloudflare:workers` to this module when the repo has no copy of its own.
|
|
30
|
+
A repo that wants to keep the path re-exports it: `export * from '@rexezuge/testing/cloudflare-workers';`.
|
|
31
|
+
|
|
32
|
+
## `createMemoryD1()`: a recording fake, not a SQL engine
|
|
33
|
+
|
|
34
|
+
No SQLite is available to the family's unit pool (no repo depends on `better-sqlite3`, `sql.js` or Miniflare in unit tests), and the unit
|
|
35
|
+
suites do not need one: they assert on the SQL a DAO prepares and feed it canned rows. `createMemoryD1` is that object, written once.
|
|
36
|
+
A test that needs **real SQL semantics** (constraints, joins, migrations) belongs in the integration pool, where `createMigrationHelper`
|
|
37
|
+
from `@rexezuge/tooling` runs the real migrations on workerd's D1.
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
const db = createMemoryD1();
|
|
41
|
+
db.when(/FROM users WHERE id = \?/, { rows: [{ id: 'u1', email: 'a@example.com' }] });
|
|
42
|
+
db.when(/^DELETE FROM sessions/, { changes: 3 });
|
|
43
|
+
db.when('INSERT INTO audit', { error: 'constraint failed' }); // resolves { success: false }, as D1 does
|
|
44
|
+
db.when('FROM flaky', { throws: new Error('D1_ERROR'), once: true }); // rejects once
|
|
45
|
+
|
|
46
|
+
const dao = new UserDAO(db.asD1<D1Database>());
|
|
47
|
+
await dao.find('u1');
|
|
48
|
+
expect(db.calls[0]).toEqual({ sql: expect.stringContaining('FROM users'), params: ['u1'], method: 'first' });
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
- `when(matcher, answer)`: `matcher` is a substring, a `RegExp` or `(call) => boolean`; the **latest** matching rule wins. `answer` is
|
|
52
|
+
`{ rows, first, changes, lastRowId, error, throws, once }`; `rows` and `first` may be functions of the call.
|
|
53
|
+
- Unmatched statements answer an empty database: no rows, `changes: 0`, `success: true`.
|
|
54
|
+
- `calls` records every statement in order (`sql`, `params`, `method`); `batches` records each `batch()`; `callsMatching(matcher)`, `reset()`.
|
|
55
|
+
- `batch`, `exec` and `withSession(bookmark?)` (with `getBookmark()`) are provided for `createApiApp({ d1: { bookmarks } })` tests.
|
|
56
|
+
|
|
57
|
+
## `createMemoryKv({ now? })`
|
|
58
|
+
|
|
59
|
+
`get` (text / json / arrayBuffer), `getWithMetadata`, `put` with `expirationTtl` / `expiration` / `metadata`, `delete`, and a cursor-paged `list({ prefix })`.
|
|
60
|
+
It satisfies `KvCache`'s namespace port structurally (`new KvCache(createMemoryKv())`). Pass `now: () => clock.now()` and advance a `FixedClock`
|
|
61
|
+
to expire entries; there is no sleeping in a TTL test.
|
|
62
|
+
|
|
63
|
+
## Cloudflare Access tokens
|
|
64
|
+
|
|
65
|
+
```ts
|
|
66
|
+
const TEAM = 'https://team.example.com';
|
|
67
|
+
beforeEach(() => vi.stubGlobal('fetch', accessJwksFetch(TEAM)));
|
|
68
|
+
afterEach(() => vi.unstubAllGlobals());
|
|
69
|
+
|
|
70
|
+
const request = await forgeAccessRequest('https://app.example.com/user/me', {
|
|
71
|
+
email: 'alice@example.com',
|
|
72
|
+
aud: 'aud-123',
|
|
73
|
+
teamDomain: TEAM,
|
|
74
|
+
});
|
|
75
|
+
await expect(authenticateAccess(request, undefined, { teamDomain: TEAM, policyAud: 'aud-123' })).resolves.toBe('alice@example.com');
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Tokens are really RS256-signed (WebCrypto, one key pair per module instance) and the JWKS really travels through `fetch`, so the production
|
|
79
|
+
verifier runs end to end. Options: `emailVerified` (omitted from the token when unset, as Access does), `claims` (override anything),
|
|
80
|
+
`expiresInSeconds` (negative mints an expired token), `now`. No `jose` import is needed in the repo's tests; the strict lint rule that bans it
|
|
81
|
+
outside the http layer exempts tests anyway.
|
|
82
|
+
|
|
83
|
+
## `createTestApp` / `requestJson`
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
const app = createApiApp<Env>({ routes: (app) => registerContract(app, itemsContract, handlers) });
|
|
87
|
+
const api = createTestApp(app, { env: { DB: db.asD1() }, headers: { 'cf-access-jwt-assertion': token } });
|
|
88
|
+
|
|
89
|
+
const { status, body } = await api.json<{ id: string }>('/user/items/1');
|
|
90
|
+
const created = await api.json('/user/items', { body: { name: 'x' } }); // a body defaults the method to POST
|
|
91
|
+
await api.settled(); // every waitUntil promise the app registered
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
The app is taken structurally (`{ fetch(request, env, ctx) }`), so the package imports neither `hono` nor `chanfana`. `body` is the parsed JSON,
|
|
95
|
+
or `null` for an empty response; `response` is the raw `Response`.
|
|
96
|
+
|
|
97
|
+
## Extending
|
|
98
|
+
|
|
99
|
+
The doubles are open where a test varies and closed where fidelity matters (see the [design charter](../../docs/design-charter.md)).
|
|
100
|
+
|
|
101
|
+
- **Open:** D1 answer rules (`when`), the KV clock (`now`), the app `env` / `headers` / `baseUrl`, claim overrides on a forged token,
|
|
102
|
+
`accessJwksFetch(team, fallback)` for other URLs, any `{ fetch }` object as an app.
|
|
103
|
+
- **Closed:** a forged token is always really signed, the D1 double never answers `success: true` for a rule that says `error`, a programmed
|
|
104
|
+
`throws` always rejects the promise (D1 never throws synchronously), and KV expiry is always checked against the injected clock.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rexezuge/testing",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.13.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -31,9 +31,9 @@
|
|
|
31
31
|
},
|
|
32
32
|
"description": "Test doubles for the Rexezuge family: the cloudflare:workers mock, in-memory D1 and KV, an Access JWT forger, and createApiApp test helpers. Dev-only.",
|
|
33
33
|
"dependencies": {
|
|
34
|
-
"@rexezuge/http": "1.
|
|
35
|
-
"@rexezuge/
|
|
36
|
-
"@rexezuge/
|
|
34
|
+
"@rexezuge/http": "1.13.0",
|
|
35
|
+
"@rexezuge/shared": "1.13.0",
|
|
36
|
+
"@rexezuge/runtime": "1.13.0"
|
|
37
37
|
},
|
|
38
38
|
"scripts": {
|
|
39
39
|
"build": "tsc -p tsconfig.json && node ../../scripts/minify-dist.mjs",
|