hazo_testing 0.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/CHANGE_LOG.md +55 -0
- package/README.md +359 -0
- package/SETUP_CHECKLIST.md +115 -0
- package/config/hazo_testing_config.ini.sample +22 -0
- package/dist/api/test_client.d.ts +24 -0
- package/dist/api/test_client.js +82 -0
- package/dist/components/test_providers.d.ts +20 -0
- package/dist/components/test_providers.js +10 -0
- package/dist/db/augmented_adapter.d.ts +8 -0
- package/dist/db/augmented_adapter.js +24 -0
- package/dist/db/test_database.d.ts +16 -0
- package/dist/db/test_database.js +42 -0
- package/dist/errors.d.ts +7 -0
- package/dist/errors.js +22 -0
- package/dist/factories/scopes.d.ts +19 -0
- package/dist/factories/scopes.js +12 -0
- package/dist/factories/users.d.ts +14 -0
- package/dist/factories/users.js +44 -0
- package/dist/fixtures/registry.d.ts +6 -0
- package/dist/fixtures/registry.js +11 -0
- package/dist/fixtures/starter.d.ts +1 -0
- package/dist/fixtures/starter.js +47 -0
- package/dist/hooks/after_each_setup.d.ts +1 -0
- package/dist/hooks/after_each_setup.js +6 -0
- package/dist/hooks/polyfills.d.ts +1 -0
- package/dist/hooks/polyfills.js +6 -0
- package/dist/hooks/reset_hooks.d.ts +4 -0
- package/dist/hooks/reset_hooks.js +5 -0
- package/dist/index.client.d.ts +2 -0
- package/dist/index.client.js +3 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +15 -0
- package/dist/nextjs/index.d.ts +10 -0
- package/dist/nextjs/index.js +26 -0
- package/dist/playwright/index.d.ts +13 -0
- package/dist/playwright/index.js +8 -0
- package/dist/wiring/jobs.d.ts +5 -0
- package/dist/wiring/jobs.js +46 -0
- package/dist/wiring/llm.d.ts +8 -0
- package/dist/wiring/llm.js +83 -0
- package/dist/wiring/notify.d.ts +8 -0
- package/dist/wiring/notify.js +52 -0
- package/jest-preset.cjs +21 -0
- package/package.json +55 -0
package/CHANGE_LOG.md
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# hazo_testing changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0 — 2026-05-31
|
|
4
|
+
|
|
5
|
+
### Initial release
|
|
6
|
+
|
|
7
|
+
**Database**
|
|
8
|
+
- `createTestDatabase({ mode, setupSqlFiles, migrations })` — in-memory SQLite via `hazo_connect`'s `SqliteAdapter` (sql.js). `mode` defaults to `"sqlite"`; `mode: "docker"` throws `DockerNotSupported` (Docker mode deferred — see below).
|
|
9
|
+
- `createTestDatabaseSqlite(opts)` — explicit-name alias for `mode: "sqlite"`.
|
|
10
|
+
- `createTestDatabaseDocker()` — always throws `DockerNotSupported`.
|
|
11
|
+
- Augmented adapter: `adapter.insertOne(table, row)` and `adapter.findOne(table, where)` shims over `hazo_connect`'s `createCrudService`. `insert(row) → T[]` and `findOneBy(where) → T | null` (no `DbResult` wrapper).
|
|
12
|
+
|
|
13
|
+
**Auth factories**
|
|
14
|
+
- `createTestUser(adapter, opts)` — writes a real `hazo_users` row; mints a session cookie via `jose` (HS256, same algorithm as `hazo_auth`). Reads `JWT_SECRET` from env.
|
|
15
|
+
- `createTestScope(adapter, opts)` — writes a real `hazo_scopes` row with required `level TEXT NOT NULL`.
|
|
16
|
+
|
|
17
|
+
**Wiring helpers — no fakes; real packages wired against the test DB**
|
|
18
|
+
- `wireHazoJobs(adapter, opts?)` — applies hazo_jobs SQLite DDL and creates a `JobsClient` in sqlite dialect. Zero external I/O; fully assertable.
|
|
19
|
+
- `wireHazoNotify(adapter, opts?)` — boots hazo_notify inbox (DB-backed) and registers channels. Auto-registers a no-op `inapp` stub so the inbox path works without credentials. Email/telegram channels are real — skip-gate tests on credential env vars.
|
|
20
|
+
- `wireHazoLlmApi(opts)` — registers real Gemini/Qwen providers, calls `initialize_llm_api`. Real, billed, non-deterministic; skip-gate tests on `GEMINI_API_KEY`/`QWEN_API_KEY`.
|
|
21
|
+
|
|
22
|
+
**API client**
|
|
23
|
+
- `apiTestClient(baseUrl, opts?)` — per-instance cookie jar, JSON helpers (`get`/`post`/`patch`/`delete`), multipart `upload`, async-iterator `stream` (SSE), `X-Correlation-Id` capture, Bearer injection.
|
|
24
|
+
|
|
25
|
+
**Fixtures**
|
|
26
|
+
- `seedTestData(adapter, { fixture })` + `registerFixture(name, seedFn)`.
|
|
27
|
+
- Built-in: `empty_with_one_user`, `small_dataset` (5 users / 2 scopes), `large_dataset` (500 users / 50 scopes).
|
|
28
|
+
|
|
29
|
+
**Jest preset**
|
|
30
|
+
- `hazo_testing/jest-preset` — `.cjs` factory (package is `type: "module"` but Jest config must be CJS). Configures ts-jest with `isolatedModules: true`, jsdom environment, `transformIgnorePatterns` for `hazo_*`, polyfills, afterEach reset hooks, `testTimeout: 10 000`.
|
|
31
|
+
|
|
32
|
+
**Reset hooks**
|
|
33
|
+
- `registerResetHook(fn)` / `runResetHooks()` / `__clearResetHooks()` — opt-in per-test cleanup registry; called automatically in afterEach by the preset.
|
|
34
|
+
|
|
35
|
+
**Client sub-export**
|
|
36
|
+
- `hazo_testing/client` — `<TestProviders>` component for mounting hazo auth + scope context in component tests.
|
|
37
|
+
|
|
38
|
+
**Optional sub-exports (D2)**
|
|
39
|
+
- `hazo_testing/playwright` — Playwright `@playwright/test` fixture extensions (optional peer `@playwright/test`).
|
|
40
|
+
- `hazo_testing/nextjs` — `startNextServer({ dir, port?, env? })` in-process Next.js server (optional peer `next`).
|
|
41
|
+
|
|
42
|
+
**Errors**
|
|
43
|
+
- `DockerNotSupported` — `HAZO_TESTING_DOCKER_NOT_SUPPORTED` code.
|
|
44
|
+
- `UnmappedLlmCall` — `HAZO_TESTING_UNMAPPED_LLM_CALL` code.
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
### Deferred (not in v0.1.0)
|
|
49
|
+
|
|
50
|
+
- **Docker/PostgreSQL mode.** `createTestDatabaseDocker()` and `mode: "docker"` throw `DockerNotSupported`. API shape reserved for future implementation.
|
|
51
|
+
- **`hazo_user_scopes` membership rows in factories.** `createTestUser` and `createTestScope` do not write membership rows. `hazo_user_scopes` requires `root_scope_id` and `role_id` FKs to `hazo_roles`; a `wireHazoAuth` helper to set up full membership is deferred.
|
|
52
|
+
- **Session cookie via hazo_auth primitives.** `create_session_token` from `hazo_auth/server-lib` is not in the public export and carries a `server-only` guard that complicates Jest imports. The factory mints the JWT directly via `jose` using the same HS256 algorithm and claims (`user_id`, `email`).
|
|
53
|
+
- **`large_dataset` at full spec size.** Spec called for 5 000 users / 500 scopes; v0.1.0 uses 500/50 for in-memory `sql.js` performance. Will be raised to full spec size when a file-based SQLite mode is available.
|
|
54
|
+
- **Provider registry public export from `hazo_llm_api`.** `wireHazoLlmApi` reaches `clear_registry`/`register_provider`/`set_enabled_llms`/`set_primary_llm`/`GeminiProvider`/`QwenProvider` via internal dist paths (not the public `hazo_llm_api/server` export). Tracked as FR-001 in `hazo_llm_api/design/feature_requests/`.
|
|
55
|
+
- **Consumer migration guides** (Kinstripe, Hazodocs) — README appendix in a later pass.
|
package/README.md
ADDED
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
# hazo_testing
|
|
2
|
+
|
|
3
|
+
Shared test infrastructure for hazo apps. Gives a consumer's Jest suite:
|
|
4
|
+
|
|
5
|
+
1. A real SQLite test database (in-memory `sql.js` via `hazo_connect`) with ordered migration application and teardown.
|
|
6
|
+
2. Auth factories that write real `hazo_auth` user/scope rows and mint session cookies.
|
|
7
|
+
3. **Real-package wiring helpers** that stand up `hazo_jobs`, `hazo_notify`, and `hazo_llm_api` against the test DB — no fakes.
|
|
8
|
+
4. An `apiTestClient`, seed fixtures, a Jest preset, and in-process reset hooks.
|
|
9
|
+
5. Optional sub-exports for Playwright and Next.js integration testing.
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
> **WARNING: real external I/O.**
|
|
14
|
+
>
|
|
15
|
+
> - `wireHazoNotify` with `channels: ["email"]` or `["telegram"]` **will send real email and real Telegram messages** through ZeptoMail / Telegram Bot API. Tests that enable those channels are skip-gated on the presence of `ZEPTOMAIL_API_KEY` / telegram credentials.
|
|
16
|
+
> - `wireHazoLlmApi` **makes real, billed API calls** to Gemini / Qwen. Tests that call `llm.run(...)` are skip-gated on `GEMINI_API_KEY` / `QWEN_API_KEY`.
|
|
17
|
+
> - The inbox-only notify path and all jobs/fixture/factory tests need no credentials and run fully offline.
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## Install
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
npm install --save-dev hazo_testing
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Peer dependencies (install all that your test suite exercises):
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
npm install hazo_core hazo_connect hazo_auth hazo_jobs hazo_notify hazo_llm_api
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## Quick start
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
// your_suite.test.ts
|
|
39
|
+
import { createTestDatabase, createTestUser, seedTestData } from "hazo_testing";
|
|
40
|
+
|
|
41
|
+
let db: Awaited<ReturnType<typeof createTestDatabase>>;
|
|
42
|
+
|
|
43
|
+
beforeAll(async () => {
|
|
44
|
+
process.env.JWT_SECRET = "test-secret-min-32-chars-12345678";
|
|
45
|
+
db = await createTestDatabase({
|
|
46
|
+
setupSqlFiles: [
|
|
47
|
+
"node_modules/hazo_auth/db_setup_sqlite.sql",
|
|
48
|
+
],
|
|
49
|
+
});
|
|
50
|
+
await seedTestData(db.adapter, { fixture: "small_dataset" });
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
afterAll(() => db.teardown());
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
---
|
|
57
|
+
|
|
58
|
+
## `createTestDatabase`
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
import { createTestDatabase } from "hazo_testing";
|
|
62
|
+
|
|
63
|
+
const { adapter, baseUrl, teardown } = await createTestDatabase({
|
|
64
|
+
mode: "sqlite", // default — "docker" throws DockerNotSupported
|
|
65
|
+
setupSqlFiles: [ // full-schema .sql files, applied in array order
|
|
66
|
+
"node_modules/hazo_auth/db_setup_sqlite.sql",
|
|
67
|
+
"node_modules/hazo_jobs/db_setup_sqlite.sql",
|
|
68
|
+
"node_modules/hazo_notify/db_setup_sqlite.sql",
|
|
69
|
+
"./migrations/my_app_schema.sql",
|
|
70
|
+
],
|
|
71
|
+
migrations: [ // numbered-migration directories (NNNN_*.sql)
|
|
72
|
+
"./migrations",
|
|
73
|
+
],
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
// adapter — AugmentedAdapter (real SqliteAdapter + insertOne/findOne helpers)
|
|
77
|
+
// baseUrl — always null (SQLite mode has no HTTP endpoint)
|
|
78
|
+
// teardown() — disposes the in-memory DB
|
|
79
|
+
|
|
80
|
+
await teardown();
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
- Each call creates an independent in-memory database — safe for parallel test workers.
|
|
84
|
+
- `mode: "docker"` throws `DockerNotSupported` (deferred to a future version).
|
|
85
|
+
- `createTestDatabaseSqlite(opts)` is an explicit-name alias.
|
|
86
|
+
- `createTestDatabaseDocker()` always throws `DockerNotSupported`.
|
|
87
|
+
|
|
88
|
+
### Augmented adapter
|
|
89
|
+
|
|
90
|
+
`adapter` is a `HazoConnectAdapter` augmented with two helper methods:
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
adapter.insertOne(table, row) // → T & { id: string }
|
|
94
|
+
adapter.findOne(table, where) // → T | null
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
These are thin shims over `createCrudService` from `hazo_connect`. They handle UUID generation automatically. The underlying `CrudService` API is `insert(row) → T[]` and `findOneBy(where) → T | null` (no `DbResult` wrapper).
|
|
98
|
+
|
|
99
|
+
---
|
|
100
|
+
|
|
101
|
+
## Auth factories
|
|
102
|
+
|
|
103
|
+
### `createTestUser`
|
|
104
|
+
|
|
105
|
+
```ts
|
|
106
|
+
import { createTestUser } from "hazo_testing";
|
|
107
|
+
|
|
108
|
+
const user = await createTestUser(adapter, {
|
|
109
|
+
email: "alice@example.com",
|
|
110
|
+
name: "Alice", // optional — defaults to email prefix
|
|
111
|
+
columnOverrides: { role: "admin" }, // app-specific columns
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
// user.id — generated UUID
|
|
115
|
+
// user.email — "alice@example.com"
|
|
116
|
+
// user.sessionCookie — ready "Cookie:" header string
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
- Writes a real `hazo_users` row. Note: the column is `email_address` in the schema; the factory maps the `email` option automatically.
|
|
120
|
+
- Mints a session cookie using HS256 JWT (same algorithm as `hazo_auth`) signed with `process.env.JWT_SECRET`.
|
|
121
|
+
- **v0.1.0 limitation:** `createTestUser` does NOT write a `hazo_user_scopes` membership row. The `hazo_user_scopes` schema requires `root_scope_id` and `role_id` FKs pointing to existing `hazo_roles` rows — this setup is deferred. Pass the returned `id` to your own membership setup if needed.
|
|
122
|
+
|
|
123
|
+
### `createTestScope`
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
import { createTestScope } from "hazo_testing";
|
|
127
|
+
|
|
128
|
+
const scope = await createTestScope(adapter, {
|
|
129
|
+
name: "Acme Corp",
|
|
130
|
+
level: "firm", // optional — defaults to "firm"; hazo_scopes.level is NOT NULL
|
|
131
|
+
members: [], // accepted but ignored in v0.1.0 (membership rows deferred)
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
// scope.id — generated UUID
|
|
135
|
+
// scope.name — "Acme Corp"
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
- Writes a real `hazo_scopes` row.
|
|
139
|
+
- `hazo_scopes` requires `level TEXT NOT NULL` — always supply a value or accept the `"firm"` default.
|
|
140
|
+
- `hazo_scopes` has no `owner_user_id` column. The `owner_user_id` option is accepted for future use but is not stored.
|
|
141
|
+
|
|
142
|
+
---
|
|
143
|
+
|
|
144
|
+
## Wiring helpers
|
|
145
|
+
|
|
146
|
+
### `wireHazoJobs` — zero external I/O
|
|
147
|
+
|
|
148
|
+
```ts
|
|
149
|
+
import { wireHazoJobs } from "hazo_testing";
|
|
150
|
+
|
|
151
|
+
const jobs = await wireHazoJobs(adapter);
|
|
152
|
+
|
|
153
|
+
const { jobId } = await jobs.submit({ type: "my-job", description: "test run", payload: { n: 1 } });
|
|
154
|
+
|
|
155
|
+
const worker = jobs.worker({ workerId: "w1", types: ["my-job"] });
|
|
156
|
+
await worker.run(async (job) => {
|
|
157
|
+
const payload = JSON.parse(job.payload as string); // payload is a raw JSON string
|
|
158
|
+
worker.stop(); // stop from INSIDE the handler
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
const row = await jobs.get(jobId);
|
|
162
|
+
expect(row.status).toBe("completed");
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
- Applies hazo_jobs DDL and creates a `JobsClient` against the test adapter.
|
|
166
|
+
- Fully real, fully deterministic — pure DB rows and handler invocation.
|
|
167
|
+
- **`worker.run()` is a blocking poll loop** — always call `worker.stop()` from inside the handler, not after `run()` awaits.
|
|
168
|
+
- `job.payload` is a raw JSON string; call `JSON.parse()` inside the handler.
|
|
169
|
+
- hazo_jobs DDL is loaded from the package root (`db_setup_sqlite.sql`) via `import.meta.resolve` because the file is not in the package exports map.
|
|
170
|
+
- `hazo_jobs/server` is imported via dynamic `import()` to avoid a CJS/ESM module-load race under Jest's `--experimental-vm-modules` runner.
|
|
171
|
+
|
|
172
|
+
### `wireHazoNotify` — real external sends when channels enabled
|
|
173
|
+
|
|
174
|
+
```ts
|
|
175
|
+
import { wireHazoNotify } from "hazo_testing";
|
|
176
|
+
|
|
177
|
+
// Inbox-only path — no credentials needed
|
|
178
|
+
const notify = await wireHazoNotify(adapter);
|
|
179
|
+
const result = await notify.dispatch({
|
|
180
|
+
scope_id: scope.id,
|
|
181
|
+
event_type: "test.event",
|
|
182
|
+
recipient_user_ids: [user.id],
|
|
183
|
+
in_app_text: "Hello",
|
|
184
|
+
deep_link: "/dashboard",
|
|
185
|
+
surfaces: ["inapp"],
|
|
186
|
+
channels: { inapp: true },
|
|
187
|
+
channel_payloads: {},
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
// Real email — requires ZEPTOMAIL_API_KEY
|
|
191
|
+
const notifyEmail = await wireHazoNotify(adapter, { channels: ["email"] });
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
- Always auto-registers a no-op `inapp` stub channel so the inbox path works without credentials. Inbox table: `hazo_notify_inbox`.
|
|
195
|
+
- Real email/telegram channels perform live I/O — skip-gate tests on env var presence.
|
|
196
|
+
- `__resetChannelRegistry` is called automatically at the start of each `wireHazoNotify` call so tests can call it multiple times without "channel already registered" errors.
|
|
197
|
+
- The `hazo_notify_inbox`, `hazo_notify_channel_deliveries`, `hazo_notify_preferences`, and template tables must exist in the test database — include `hazo_notify/db_setup_sqlite.sql` in `setupSqlFiles`.
|
|
198
|
+
|
|
199
|
+
### `wireHazoLlmApi` — real billed calls
|
|
200
|
+
|
|
201
|
+
```ts
|
|
202
|
+
import { wireHazoLlmApi } from "hazo_testing";
|
|
203
|
+
|
|
204
|
+
const llm = await wireHazoLlmApi({ providers: ["gemini"], primary: "gemini" });
|
|
205
|
+
|
|
206
|
+
// Assertions check shape, not text (non-deterministic)
|
|
207
|
+
const res = await llm.run({ prompt: "Say hello in one word" }, "gemini");
|
|
208
|
+
expect(res.success).toBe(true);
|
|
209
|
+
expect(typeof res.text).toBe("string");
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
- Registers the real Gemini/Qwen providers with API keys read from environment variables.
|
|
213
|
+
- Provider constructors accept an empty `api_key` without throwing — errors only surface at call time. This lets you assert `typeof llm.run === "function"` without credentials.
|
|
214
|
+
- Skip-gate tests that call `llm.run(...)` on `GEMINI_API_KEY` / `QWEN_API_KEY`.
|
|
215
|
+
- **Fragile internal path:** `clear_registry`, `register_provider`, `set_enabled_llms`, `set_primary_llm`, `GeminiProvider`, and `QwenProvider` are not exported from `hazo_llm_api/server`. `wireHazoLlmApi` reaches them via `import.meta.resolve("hazo_llm_api/server")` → dist root → dynamic import of internal dist paths. This will break if `hazo_llm_api` restructures its dist. Track FR-001 in `hazo_llm_api/design/feature_requests/FR-001-export-provider-registry.md`.
|
|
216
|
+
- `initialize_llm_api` is called with a stub `hazo_connect` (`api_log: { enabled: false }`) so no `prompt_library.sqlite` is written to disk. If you see that file appearing, add it to your consumer's `.gitignore`.
|
|
217
|
+
|
|
218
|
+
---
|
|
219
|
+
|
|
220
|
+
## `apiTestClient`
|
|
221
|
+
|
|
222
|
+
```ts
|
|
223
|
+
import { apiTestClient } from "hazo_testing";
|
|
224
|
+
|
|
225
|
+
const client = apiTestClient("http://localhost:3000", {
|
|
226
|
+
sessionCookie: user.sessionCookie, // optional
|
|
227
|
+
token: "bearer-token", // optional — injects Authorization header
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
const { status, body } = await client.get("/api/items");
|
|
231
|
+
const { status: s2 } = await client.post("/api/items", { name: "test" });
|
|
232
|
+
const { status: s3 } = await client.patch("/api/items/1", { name: "updated" });
|
|
233
|
+
const { status: s4 } = await client.delete("/api/items/1");
|
|
234
|
+
|
|
235
|
+
// File upload
|
|
236
|
+
const { status: s5 } = await client.upload("/api/files", {
|
|
237
|
+
file: Buffer.from("hello"),
|
|
238
|
+
mimeType: "text/plain",
|
|
239
|
+
fieldName: "file", // optional, default "file"
|
|
240
|
+
filename: "hello.txt", // optional
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
// SSE streaming
|
|
244
|
+
for await (const chunk of client.stream("/api/stream", { prompt: "..." })) {
|
|
245
|
+
process.stdout.write(chunk);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Correlation ID from last response
|
|
249
|
+
console.log(client.lastCorrelationId);
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
- Cookie jar is per-client instance and auto-rotates `Set-Cookie` headers.
|
|
253
|
+
- Returns `{ status, body, headers }` on every call. `body` is auto-parsed as JSON if `Content-Type: application/json`.
|
|
254
|
+
|
|
255
|
+
---
|
|
256
|
+
|
|
257
|
+
## Fixtures
|
|
258
|
+
|
|
259
|
+
```ts
|
|
260
|
+
import { seedTestData, registerFixture } from "hazo_testing";
|
|
261
|
+
|
|
262
|
+
// Built-in fixtures
|
|
263
|
+
await seedTestData(adapter, { fixture: "empty_with_one_user" });
|
|
264
|
+
await seedTestData(adapter, { fixture: "small_dataset" }); // ~5 users / 2 scopes
|
|
265
|
+
await seedTestData(adapter, { fixture: "large_dataset" }); // 500 users / 50 scopes
|
|
266
|
+
|
|
267
|
+
// Register a custom fixture
|
|
268
|
+
registerFixture("my_fixture", async (adapter) => {
|
|
269
|
+
const user = await createTestUser(adapter, { email: "admin@acme.com" });
|
|
270
|
+
return { users: [user] };
|
|
271
|
+
});
|
|
272
|
+
await seedTestData(adapter, { fixture: "my_fixture" });
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
- Built-in fixtures write auth/scope rows only (S6 neutrality — no app-domain rows).
|
|
276
|
+
- `large_dataset` is 500 users / 50 scopes in v0.1.0 (the spec's 5 000/500 was scaled down for in-memory `sql.js` performance).
|
|
277
|
+
|
|
278
|
+
---
|
|
279
|
+
|
|
280
|
+
## Jest preset
|
|
281
|
+
|
|
282
|
+
```js
|
|
283
|
+
// jest.config.cjs
|
|
284
|
+
module.exports = require("hazo_testing/jest-preset")({
|
|
285
|
+
aliasRoot: "<rootDir>/src", // optional — sets @/... alias; pass false to disable
|
|
286
|
+
setupFilesAfterEnv: [], // optional — additional setup files
|
|
287
|
+
});
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
- Sets `testEnvironment: "jsdom"`, `ts-jest` transform with `isolatedModules: true`.
|
|
291
|
+
- `transformIgnorePatterns` allows `hazo_*` packages to be transformed.
|
|
292
|
+
- Injects polyfills (`TextEncoder`, `structuredClone`, `fetch`) via `setupFiles`.
|
|
293
|
+
- Calls all registered reset hooks in `afterEach` via `setupFilesAfterEnv`.
|
|
294
|
+
- `testTimeout: 10 000` ms.
|
|
295
|
+
- `jest-preset.cjs` is CommonJS (the package is `type: "module"` but Jest config must be CJS).
|
|
296
|
+
|
|
297
|
+
**Jest must run with:**
|
|
298
|
+
|
|
299
|
+
```json
|
|
300
|
+
{ "test": "NODE_OPTIONS=--experimental-vm-modules jest" }
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
Without `--experimental-vm-modules`, ESM imports (`hazo_notify`, `hazo_jobs`, `hazo_llm_api`) will fail.
|
|
304
|
+
|
|
305
|
+
---
|
|
306
|
+
|
|
307
|
+
## Reset hooks
|
|
308
|
+
|
|
309
|
+
```ts
|
|
310
|
+
import { registerResetHook, runResetHooks } from "hazo_testing";
|
|
311
|
+
|
|
312
|
+
// Register a cleanup function to run after each test
|
|
313
|
+
registerResetHook(() => { myCache.clear(); });
|
|
314
|
+
|
|
315
|
+
// The preset calls runResetHooks() automatically in afterEach.
|
|
316
|
+
// __clearResetHooks() is available for test isolation if needed.
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
---
|
|
320
|
+
|
|
321
|
+
## Optional sub-exports
|
|
322
|
+
|
|
323
|
+
### `hazo_testing/playwright`
|
|
324
|
+
|
|
325
|
+
```ts
|
|
326
|
+
import { hazoPage } from "hazo_testing/playwright";
|
|
327
|
+
```
|
|
328
|
+
|
|
329
|
+
Provides `@playwright/test` fixtures. Requires the optional peer `@playwright/test`.
|
|
330
|
+
|
|
331
|
+
### `hazo_testing/nextjs`
|
|
332
|
+
|
|
333
|
+
```ts
|
|
334
|
+
import { startNextServer } from "hazo_testing/nextjs";
|
|
335
|
+
|
|
336
|
+
const server = await startNextServer({ dir: "/path/to/app", port: 3999 });
|
|
337
|
+
// server.url — "http://127.0.0.1:3999"
|
|
338
|
+
await server.teardown();
|
|
339
|
+
```
|
|
340
|
+
|
|
341
|
+
Boots a Next.js dev/prod server in-process. Requires the optional peer `next`. Port `0` binds to a random available port.
|
|
342
|
+
|
|
343
|
+
---
|
|
344
|
+
|
|
345
|
+
## Test plan
|
|
346
|
+
|
|
347
|
+
The package's own suite (`src/**/__tests__`) covers:
|
|
348
|
+
|
|
349
|
+
| Scenario | Tests | Creds needed | Runs green locally |
|
|
350
|
+
|----------|-------|--------------|--------------------|
|
|
351
|
+
| `db_lifecycle` (sqlite) | 2–3 | none | yes |
|
|
352
|
+
| `factories` | 5 | none (JWT_SECRET defaulted) | yes |
|
|
353
|
+
| `real_io` — jobs | 3 | none | yes |
|
|
354
|
+
| `real_io` — notify | 2 | `ZEPTOMAIL_API_KEY` etc. | skip-gated |
|
|
355
|
+
| `real_io` — llm | 2 | `GEMINI_API_KEY`/`QWEN_API_KEY` | skip-gated |
|
|
356
|
+
| `api_client` | 5 | none (in-test handler) | yes |
|
|
357
|
+
| `fixtures` | 4 | none | yes |
|
|
358
|
+
|
|
359
|
+
Skip-gated tests print a clear `it.skip` reason when credentials are absent.
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
# Setup Checklist
|
|
2
|
+
|
|
3
|
+
## v0.1.0 — initial setup
|
|
4
|
+
|
|
5
|
+
### 1. Add the dev dependency
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install --save-dev hazo_testing
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Add peer dependencies for the packages your test suite exercises:
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
npm install hazo_core hazo_connect hazo_auth hazo_jobs hazo_notify hazo_llm_api
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
### 2. Create `jest.config.cjs`
|
|
18
|
+
|
|
19
|
+
```js
|
|
20
|
+
// jest.config.cjs
|
|
21
|
+
module.exports = require("hazo_testing/jest-preset")({
|
|
22
|
+
// aliasRoot: "<rootDir>/src", // uncomment to enable @/... alias
|
|
23
|
+
});
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Update `package.json` scripts:
|
|
27
|
+
|
|
28
|
+
```json
|
|
29
|
+
{
|
|
30
|
+
"scripts": {
|
|
31
|
+
"test": "NODE_OPTIONS=--experimental-vm-modules jest"
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
`NODE_OPTIONS=--experimental-vm-modules` is required. Without it, ESM imports from `hazo_notify`, `hazo_jobs`, and `hazo_llm_api` will fail under Jest.
|
|
37
|
+
|
|
38
|
+
### 3. Set `JWT_SECRET`
|
|
39
|
+
|
|
40
|
+
The auth factories need `JWT_SECRET` to mint session cookies. Set it in your test suite's `beforeAll` or in a `.env.test` file:
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
// any suite that calls createTestUser
|
|
44
|
+
beforeAll(() => {
|
|
45
|
+
process.env.JWT_SECRET = "test-secret-minimum-32-chars-here";
|
|
46
|
+
});
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
The value is arbitrary in tests — it just needs to be at least 32 characters.
|
|
50
|
+
|
|
51
|
+
### 4. Point `setupSqlFiles` at the package schema files
|
|
52
|
+
|
|
53
|
+
Pass the path to each package's `db_setup_sqlite.sql` when creating the test database. The files are in the package root (not in `dist/`):
|
|
54
|
+
|
|
55
|
+
```ts
|
|
56
|
+
const db = await createTestDatabase({
|
|
57
|
+
setupSqlFiles: [
|
|
58
|
+
"node_modules/hazo_auth/db_setup_sqlite.sql",
|
|
59
|
+
"node_modules/hazo_jobs/db_setup_sqlite.sql",
|
|
60
|
+
"node_modules/hazo_notify/db_setup_sqlite.sql",
|
|
61
|
+
"./migrations/my_app_schema.sql", // your own app tables
|
|
62
|
+
],
|
|
63
|
+
});
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Order matters — apply packages before your own migrations if your tables reference their foreign keys.
|
|
67
|
+
|
|
68
|
+
### 5. (Optional) Enable notify credentials
|
|
69
|
+
|
|
70
|
+
Tests that exercise real email or Telegram channels need these env vars. Without them the tests are automatically skipped.
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
# .env.test.local (gitignored)
|
|
74
|
+
ZEPTOMAIL_API_KEY=...
|
|
75
|
+
TELEGRAM_BOT_TOKEN=...
|
|
76
|
+
TELEGRAM_CHAT_ID=...
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
### 6. (Optional) Enable LLM credentials
|
|
80
|
+
|
|
81
|
+
Tests that call `wireHazoLlmApi` and then `llm.run(...)` with real providers need:
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
# .env.test.local (gitignored)
|
|
85
|
+
GEMINI_API_KEY=...
|
|
86
|
+
QWEN_API_KEY=...
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Without these variables the LLM real-I/O tests are automatically skipped. Calling `wireHazoLlmApi` itself (to assert `typeof llm.run === "function"`) does not require credentials.
|
|
90
|
+
|
|
91
|
+
### 7. (Optional) Playwright sub-export
|
|
92
|
+
|
|
93
|
+
If you use `hazo_testing/playwright`, install the optional peer:
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
npm install --save-dev @playwright/test
|
|
97
|
+
npx playwright install
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
### 8. (Optional) Next.js sub-export
|
|
101
|
+
|
|
102
|
+
If you use `hazo_testing/nextjs` for in-process server tests, install the optional peer:
|
|
103
|
+
|
|
104
|
+
```bash
|
|
105
|
+
npm install --save-dev next
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
### 9. Add `.gitignore` entries
|
|
109
|
+
|
|
110
|
+
`wireHazoLlmApi` calls `initialize_llm_api` internally, which creates a `prompt_library.sqlite` file in the current working directory. Add it to your consumer's `.gitignore`:
|
|
111
|
+
|
|
112
|
+
```
|
|
113
|
+
prompt_library.sqlite
|
|
114
|
+
*.sqlite
|
|
115
|
+
```
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
; hazo_testing configuration sample
|
|
2
|
+
; Copy this file to hazo_testing_config.ini in your app's config/ directory.
|
|
3
|
+
; Env-var overrides: HAZO_TESTING_<SECTION>_<KEY>
|
|
4
|
+
; Per-env overlay: hazo_testing_config.<HAZO_ENV>.ini (e.g. hazo_testing_config.staging.ini)
|
|
5
|
+
|
|
6
|
+
; -----------------------------------------------------------------------
|
|
7
|
+
[env]
|
|
8
|
+
; The deployment environment. hazo_testing reads this to resolve the
|
|
9
|
+
; per-env config overlay (hazo_testing_config.<env>.ini).
|
|
10
|
+
; Resolution: process.env.HAZO_ENV ?? process.env.NODE_ENV ?? 'development'
|
|
11
|
+
; Override: HAZO_ENV=staging
|
|
12
|
+
;
|
|
13
|
+
; env = development
|
|
14
|
+
|
|
15
|
+
; -----------------------------------------------------------------------
|
|
16
|
+
[test_db]
|
|
17
|
+
; Which test-database mode to use.
|
|
18
|
+
; sqlite — in-memory sql.js (default). Works anywhere, no external deps.
|
|
19
|
+
; docker — NOT SUPPORTED in v0.1.0. createTestDatabaseDocker() throws
|
|
20
|
+
; DockerNotSupported. Reserved for a future release.
|
|
21
|
+
;
|
|
22
|
+
mode = sqlite
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export interface ApiTestClientOptions {
|
|
2
|
+
sessionCookie?: string;
|
|
3
|
+
token?: string;
|
|
4
|
+
}
|
|
5
|
+
export interface ApiResponse<T = any> {
|
|
6
|
+
status: number;
|
|
7
|
+
body: T;
|
|
8
|
+
headers: Headers;
|
|
9
|
+
}
|
|
10
|
+
export interface ApiTestClient {
|
|
11
|
+
lastCorrelationId: string | null;
|
|
12
|
+
get<T = any>(path: string): Promise<ApiResponse<T>>;
|
|
13
|
+
post<T = any>(path: string, body?: unknown): Promise<ApiResponse<T>>;
|
|
14
|
+
patch<T = any>(path: string, body?: unknown): Promise<ApiResponse<T>>;
|
|
15
|
+
delete<T = any>(path: string): Promise<ApiResponse<T>>;
|
|
16
|
+
upload<T = any>(path: string, opts: {
|
|
17
|
+
file: Buffer | Uint8Array;
|
|
18
|
+
mimeType: string;
|
|
19
|
+
fieldName?: string;
|
|
20
|
+
filename?: string;
|
|
21
|
+
}): Promise<ApiResponse<T>>;
|
|
22
|
+
stream(path: string, body?: unknown): AsyncIterable<string>;
|
|
23
|
+
}
|
|
24
|
+
export declare function apiTestClient(baseUrl: string, opts?: ApiTestClientOptions): ApiTestClient;
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
export function apiTestClient(baseUrl, opts = {}) {
|
|
2
|
+
let cookie = opts.sessionCookie ?? "";
|
|
3
|
+
const client = {
|
|
4
|
+
lastCorrelationId: null,
|
|
5
|
+
get: (p) => request("GET", p),
|
|
6
|
+
post: (p, b) => request("POST", p, b),
|
|
7
|
+
patch: (p, b) => request("PATCH", p, b),
|
|
8
|
+
delete: (p) => request("DELETE", p),
|
|
9
|
+
upload: (p, o) => upload(p, o),
|
|
10
|
+
stream: (p, b) => streamRequest(p, b),
|
|
11
|
+
};
|
|
12
|
+
function baseHeaders(json) {
|
|
13
|
+
const h = {};
|
|
14
|
+
if (json)
|
|
15
|
+
h["Content-Type"] = "application/json";
|
|
16
|
+
if (cookie)
|
|
17
|
+
h["Cookie"] = cookie;
|
|
18
|
+
if (opts.token)
|
|
19
|
+
h["Authorization"] = `Bearer ${opts.token}`;
|
|
20
|
+
return h;
|
|
21
|
+
}
|
|
22
|
+
function absorb(res) {
|
|
23
|
+
// Node 18+ fetch may fold set-cookie or expose via getSetCookie()
|
|
24
|
+
let setCookieValues = [];
|
|
25
|
+
if (typeof res.headers.getSetCookie === "function") {
|
|
26
|
+
setCookieValues = res.headers.getSetCookie();
|
|
27
|
+
}
|
|
28
|
+
else {
|
|
29
|
+
const set = res.headers.get("set-cookie");
|
|
30
|
+
if (set)
|
|
31
|
+
setCookieValues = [set];
|
|
32
|
+
}
|
|
33
|
+
for (const sc of setCookieValues) {
|
|
34
|
+
const val = sc.split(";")[0];
|
|
35
|
+
if (!val)
|
|
36
|
+
continue;
|
|
37
|
+
cookie = cookie ? `${cookie}; ${val}` : val;
|
|
38
|
+
}
|
|
39
|
+
const corr = res.headers.get("x-correlation-id");
|
|
40
|
+
if (corr)
|
|
41
|
+
client.lastCorrelationId = corr;
|
|
42
|
+
}
|
|
43
|
+
async function toBody(res) {
|
|
44
|
+
const ct = res.headers.get("content-type") ?? "";
|
|
45
|
+
return ct.includes("application/json") ? await res.json() : await res.text();
|
|
46
|
+
}
|
|
47
|
+
async function request(method, path, body) {
|
|
48
|
+
const res = await fetch(baseUrl + path, {
|
|
49
|
+
method, headers: baseHeaders(body !== undefined),
|
|
50
|
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
51
|
+
});
|
|
52
|
+
absorb(res);
|
|
53
|
+
return { status: res.status, body: await toBody(res), headers: res.headers };
|
|
54
|
+
}
|
|
55
|
+
async function upload(path, o) {
|
|
56
|
+
const form = new FormData();
|
|
57
|
+
// Cast to BlobPart — Node Buffer's ArrayBufferLike variance isn't assignable
|
|
58
|
+
// to BlobPart under strict lib.dom types, though it is a valid blob part at runtime.
|
|
59
|
+
const blob = new Blob([o.file], { type: o.mimeType });
|
|
60
|
+
form.append(o.fieldName ?? "file", blob, o.filename ?? "upload.bin");
|
|
61
|
+
const headers = baseHeaders(false);
|
|
62
|
+
const res = await fetch(baseUrl + path, { method: "POST", headers, body: form });
|
|
63
|
+
absorb(res);
|
|
64
|
+
return { status: res.status, body: await toBody(res), headers: res.headers };
|
|
65
|
+
}
|
|
66
|
+
async function* streamRequest(path, body) {
|
|
67
|
+
const res = await fetch(baseUrl + path, {
|
|
68
|
+
method: "POST", headers: baseHeaders(body !== undefined),
|
|
69
|
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
70
|
+
});
|
|
71
|
+
absorb(res);
|
|
72
|
+
const reader = res.body.getReader();
|
|
73
|
+
const dec = new TextDecoder();
|
|
74
|
+
for (;;) {
|
|
75
|
+
const { done, value } = await reader.read();
|
|
76
|
+
if (done)
|
|
77
|
+
break;
|
|
78
|
+
yield dec.decode(value, { stream: true });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return client;
|
|
82
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import React from "react";
|
|
2
|
+
export interface TestUserCtx {
|
|
3
|
+
id: string;
|
|
4
|
+
email: string;
|
|
5
|
+
}
|
|
6
|
+
export interface TestScopeCtx {
|
|
7
|
+
id: string;
|
|
8
|
+
name: string;
|
|
9
|
+
}
|
|
10
|
+
interface TestCtxValue {
|
|
11
|
+
user?: TestUserCtx;
|
|
12
|
+
scope?: TestScopeCtx;
|
|
13
|
+
}
|
|
14
|
+
export declare const useTestContext: () => TestCtxValue;
|
|
15
|
+
export declare function TestProviders(props: {
|
|
16
|
+
user?: TestUserCtx;
|
|
17
|
+
scope?: TestScopeCtx;
|
|
18
|
+
children: React.ReactNode;
|
|
19
|
+
}): import("react/jsx-runtime").JSX.Element;
|
|
20
|
+
export {};
|