@cslug/testing 0.0.0-stage → 0.2.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 +6 -2
- package/docs/README.md +27 -0
- package/docs/api.md +53 -0
- package/package.json +85 -4
- package/src/fakes.ts +84 -0
- package/src/index.ts +7 -0
- package/src/request.ts +422 -0
- package/src/test-app.ts +341 -0
package/README.md
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @cslug/testing
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`testApp()` starts your app once per test file and isolates every test (database rollback or truncate). Send
|
|
4
|
+
requests without a port, assert on responses, and sign in with `t.actingAs`.
|
|
5
|
+
|
|
6
|
+
Part of [cslug](https://github.com/cslugts/cslug). Docs: [docs/README.md](docs/README.md), [docs/api.md](docs/api.md),
|
|
7
|
+
[guide 19](../../guides/19-testing.md).
|
package/docs/README.md
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# @cslug/testing
|
|
2
|
+
|
|
3
|
+
`testApp()` builds and starts your app once per test file and isolates every test:
|
|
4
|
+
|
|
5
|
+
- **database**: each test runs in a transaction that is rolled back (`database: 'truncate'` for real commits)
|
|
6
|
+
- **cookies**: a fresh browser-like cookie jar per test
|
|
7
|
+
- **clock**: a new `FakeClock` per test (`t.clock.travelTo()`, `advance()`)
|
|
8
|
+
- **swaps and fakes**: reset after each test
|
|
9
|
+
- **in-memory stores** (cache, locks, rate limits, sessions): fresh in each test
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { testApp } from '@cslug/testing'
|
|
13
|
+
|
|
14
|
+
const t = testApp({ fakes: ['events'] })
|
|
15
|
+
|
|
16
|
+
test('adding a todo', async () => {
|
|
17
|
+
await t.post('/todos').form({ title: 'Buy bread' }).assertRedirect().assertSessionHas('success').follow().assertSee('Buy bread')
|
|
18
|
+
await t.assertDatabaseHas('todos', { title: 'Buy bread' })
|
|
19
|
+
t.events.assertEmitted(TodoCreated)
|
|
20
|
+
})
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Requests go straight to the HTTP kernel (no port). `.form()` adds the CSRF token and a Referer as a browser
|
|
24
|
+
would, so failed validation redirects back and `assertInvalid()` / `assertOldInput()` read the flashed errors.
|
|
25
|
+
|
|
26
|
+
Packages plug in: `actingAs`, `t.auth`, `t.tokens` (auth), `t.queue` and `t.schedule` (queue), `assertView` /
|
|
27
|
+
`assertIsland` (vue), `t.mail` (mail). See [api.md](api.md).
|
package/docs/api.md
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# @cslug/testing: API
|
|
2
|
+
|
|
3
|
+
## `testApp(options?)`
|
|
4
|
+
|
|
5
|
+
| Option | Default | |
|
|
6
|
+
|---|---|---|
|
|
7
|
+
| `create` | `createApp()` from `bootstrap/app.ts` | Build the app |
|
|
8
|
+
| `config` | | Overrides by dotted path |
|
|
9
|
+
| `fakes` | `[]` | `'events'`, `'queue'`, `'mail'` (loaded from their package). A fake listed here is typed as present on `t` |
|
|
10
|
+
| `database` | `'transaction'` | `'truncate'` or `false` |
|
|
11
|
+
| `migrate` | `true` | Runs `database/migrations` once |
|
|
12
|
+
| `host` | host of `app.url` | |
|
|
13
|
+
|
|
14
|
+
Returns: `app`, `clock`, `resolve`, `swap`, `actingAs(user)` (for every request of the test), `get/post/put/patch/delete(path)`, `beforeRequest(hook)`,
|
|
15
|
+
`db.count(table, where?)`, `db.find(table, id)`, `assertDatabaseHas/Missing(table, where)` (camelCase keys; values
|
|
16
|
+
or `@cslug/database` operators: `{ remindedAt: notNull() }`), each installed fake as `t.<name>`, and:
|
|
17
|
+
|
|
18
|
+
- `auth.check()` / `auth.user()`: who the session says is signed in after the last request (@cslug/auth).
|
|
19
|
+
- `tokens.create(user, { abilities?, name?, expiresIn? })` → `{ plainText }` (@cslug/auth).
|
|
20
|
+
- `schedule.runDue()`: run the schedule entries due at `t.clock`'s time (@cslug/queue's ScheduleProvider).
|
|
21
|
+
|
|
22
|
+
## Requests (`PendingRequest`, awaited to run)
|
|
23
|
+
|
|
24
|
+
Building: `header`, `headers({…})`, `withToken`, `actingAs(user)` (signed in through the session, with
|
|
25
|
+
@cslug/auth), `json(data)` (writes carry the session's CSRF token in `X-CSRF-Token`, as an island's `useForm`
|
|
26
|
+
does), `form(data)` (nested keys, CSRF, Referer).
|
|
27
|
+
|
|
28
|
+
Assertions (queued, run in order): `assertStatus`, `assertOk`, `assertCreated`, `assertNoContent`,
|
|
29
|
+
`assertNotFound`, `assertForbidden`, `assertUnauthorized`, `assertRedirect(to?)`, `assertJson(subset)`,
|
|
30
|
+
`assertProblem(status, code)`, `assertInvalid({ field: 'part of message' })` (JSON 422 or flashed),
|
|
31
|
+
`assertOldInput`, `assertSessionHas(key, value?)`, `assertSessionMissing`, `assertSee`, `assertDontSee`,
|
|
32
|
+
`assertHeader`, `assertCookie`, `assertView(View, (props) => …)` (the page `view()` rendered for this request,
|
|
33
|
+
@cslug/vue), `assertIsland(name, props?)` (an island marker in the HTML; `name` with or without its folder,
|
|
34
|
+
`props` a deep subset). `follow()` makes the GET to the redirect location with the same cookies.
|
|
35
|
+
|
|
36
|
+
The awaited value is a `TestResponse`: `status`, `headers`, `body()`, `json()`, `session()`, `views`, `islands()`.
|
|
37
|
+
|
|
38
|
+
## Fakes
|
|
39
|
+
|
|
40
|
+
`EventFake` (`'events'`): `emitted`, `of(Event)`, `assertEmitted(Event, predicate?)`, `assertNotEmitted`,
|
|
41
|
+
`assertNothingEmitted`.
|
|
42
|
+
|
|
43
|
+
Packages add theirs:
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
registerFake('queue', (app) => { const fake = new QueueFake(); app.swap(Queue, fake); return fake })
|
|
47
|
+
declare module '@cslug/testing' { interface TestFakes { queue: QueueFake } }
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Database isolation
|
|
51
|
+
|
|
52
|
+
`Database.pin()` (from `@cslug/database`) holds one transaction for the test; queries without their own
|
|
53
|
+
transaction use it, and `transaction()` calls become savepoints whose `afterCommit` hooks run on release.
|
package/package.json
CHANGED
|
@@ -1,6 +1,87 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cslug/testing",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Test kit: testApp(), HTTP and HTML assertions, database isolation, fakes, time travel.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/cslugts/cslug.git",
|
|
10
|
+
"directory": "packages/testing"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/cslugts/cslug/tree/main/packages/testing",
|
|
13
|
+
"keywords": [
|
|
14
|
+
"cslug",
|
|
15
|
+
"bun",
|
|
16
|
+
"framework"
|
|
17
|
+
],
|
|
18
|
+
"exports": {
|
|
19
|
+
".": "./src/index.ts"
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"src",
|
|
23
|
+
"docs",
|
|
24
|
+
"stubs",
|
|
25
|
+
"README.md"
|
|
26
|
+
],
|
|
27
|
+
"engines": {
|
|
28
|
+
"bun": ">=1.3.14"
|
|
29
|
+
},
|
|
30
|
+
"peerDependencies": {
|
|
31
|
+
"@cslug/core": "0.2.0",
|
|
32
|
+
"@cslug/validation": "0.2.0",
|
|
33
|
+
"@cslug/http": "0.2.0",
|
|
34
|
+
"@cslug/vue": "0.2.0",
|
|
35
|
+
"@cslug/database": "0.2.0",
|
|
36
|
+
"@cslug/redis": "0.2.0",
|
|
37
|
+
"@cslug/queue": "0.2.0",
|
|
38
|
+
"@cslug/auth": "0.2.0",
|
|
39
|
+
"@cslug/mail": "0.2.0",
|
|
40
|
+
"@cslug/notification": "0.2.0",
|
|
41
|
+
"@cslug/storage": "0.2.0",
|
|
42
|
+
"@cslug/webhook": "0.2.0",
|
|
43
|
+
"@cslug/ai": "0.2.0",
|
|
44
|
+
"@cslug/cli": "0.2.0"
|
|
45
|
+
},
|
|
46
|
+
"peerDependenciesMeta": {
|
|
47
|
+
"@cslug/validation": {
|
|
48
|
+
"optional": true
|
|
49
|
+
},
|
|
50
|
+
"@cslug/http": {
|
|
51
|
+
"optional": true
|
|
52
|
+
},
|
|
53
|
+
"@cslug/vue": {
|
|
54
|
+
"optional": true
|
|
55
|
+
},
|
|
56
|
+
"@cslug/database": {
|
|
57
|
+
"optional": true
|
|
58
|
+
},
|
|
59
|
+
"@cslug/redis": {
|
|
60
|
+
"optional": true
|
|
61
|
+
},
|
|
62
|
+
"@cslug/queue": {
|
|
63
|
+
"optional": true
|
|
64
|
+
},
|
|
65
|
+
"@cslug/auth": {
|
|
66
|
+
"optional": true
|
|
67
|
+
},
|
|
68
|
+
"@cslug/mail": {
|
|
69
|
+
"optional": true
|
|
70
|
+
},
|
|
71
|
+
"@cslug/notification": {
|
|
72
|
+
"optional": true
|
|
73
|
+
},
|
|
74
|
+
"@cslug/storage": {
|
|
75
|
+
"optional": true
|
|
76
|
+
},
|
|
77
|
+
"@cslug/webhook": {
|
|
78
|
+
"optional": true
|
|
79
|
+
},
|
|
80
|
+
"@cslug/ai": {
|
|
81
|
+
"optional": true
|
|
82
|
+
},
|
|
83
|
+
"@cslug/cli": {
|
|
84
|
+
"optional": true
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
package/src/fakes.ts
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { expect } from 'bun:test'
|
|
2
|
+
import { type AnyEventClass, type Application, EventBus, type EventClass, Logger } from '@cslug/core'
|
|
3
|
+
|
|
4
|
+
/** Fakes available as `t.<name>`; packages add theirs with module augmentation and `registerFake`. */
|
|
5
|
+
// biome-ignore lint/suspicious/noEmptyInterface: augmented by packages
|
|
6
|
+
export interface TestFakes {}
|
|
7
|
+
|
|
8
|
+
export type FakeInstaller = (app: Application) => unknown
|
|
9
|
+
const installers = new Map<string, FakeInstaller>()
|
|
10
|
+
|
|
11
|
+
/** Packages register their fake: `registerFake('queue', (app) => { const f = new QueueFake(); app.swap(Queue, f); return f })`. */
|
|
12
|
+
export function registerFake(name: string, install: FakeInstaller): void {
|
|
13
|
+
installers.set(name, install)
|
|
14
|
+
}
|
|
15
|
+
export const fakeInstaller = (name: string) => installers.get(name)
|
|
16
|
+
|
|
17
|
+
/** Fakes of optional packages, loaded on first use (the package may not be installed). */
|
|
18
|
+
const lazy: Record<string, () => Promise<FakeInstaller>> = {
|
|
19
|
+
queue: async () => (await import('@cslug/queue')).installQueueFake,
|
|
20
|
+
mail: async () => (await import('@cslug/mail')).installMailFake,
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** The installer for `name`: registered, or loaded from its package. Undefined if neither. */
|
|
24
|
+
export async function loadFake(name: string): Promise<FakeInstaller | undefined> {
|
|
25
|
+
const known = installers.get(name)
|
|
26
|
+
if (known || !lazy[name]) return known
|
|
27
|
+
try {
|
|
28
|
+
const install = await (lazy[name] as () => Promise<FakeInstaller>)()
|
|
29
|
+
installers.set(name, install)
|
|
30
|
+
return install
|
|
31
|
+
} catch {
|
|
32
|
+
return undefined
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
type Recorded = { event: AnyEventClass; payload: unknown }
|
|
37
|
+
|
|
38
|
+
/** Records emitted events instead of running listeners. */
|
|
39
|
+
export class EventFake extends EventBus {
|
|
40
|
+
readonly emitted: Recorded[] = []
|
|
41
|
+
|
|
42
|
+
constructor(app: Application) {
|
|
43
|
+
super(app, Logger.null())
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
override async emit<P>(event: EventClass<P>, payload: P): Promise<void> {
|
|
47
|
+
this.emitted.push({ event, payload })
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Emitted events of one class (payloads). */
|
|
51
|
+
of<P>(event: EventClass<P>): P[] {
|
|
52
|
+
return this.emitted.filter((e) => e.event === event).map((e) => e.payload as P)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
assertEmitted<P>(event: EventClass<P>, predicate?: (e: { payload: P }) => boolean): void {
|
|
56
|
+
const matching = this.of(event).filter((payload) => !predicate || predicate({ payload }))
|
|
57
|
+
expect(
|
|
58
|
+
matching.length,
|
|
59
|
+
`expected ${event.eventName} to be emitted${predicate ? ' (matching the predicate)' : ''}`,
|
|
60
|
+
).toBeGreaterThan(0)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
assertNotEmitted<P>(event: EventClass<P>): void {
|
|
64
|
+
expect(this.of(event).length, `expected ${event.eventName} not to be emitted`).toBe(0)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
assertNothingEmitted(): void {
|
|
68
|
+
expect(this.emitted.map((e) => e.event.eventName)).toEqual([])
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
registerFake('events', (app) => {
|
|
73
|
+
const fake = new EventFake(app)
|
|
74
|
+
app.swap(EventBus, fake)
|
|
75
|
+
return fake
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
declare module './fakes' {
|
|
79
|
+
interface TestFakes {
|
|
80
|
+
events: EventFake
|
|
81
|
+
queue: import('@cslug/queue').QueueFake
|
|
82
|
+
mail: import('@cslug/mail').MailFake
|
|
83
|
+
}
|
|
84
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @cslug/testing: `testApp()` (the app per test file, isolated per test), HTTP requests without a port and
|
|
3
|
+
* their assertions, database helpers, the fake clock, and the fake registry other packages plug into.
|
|
4
|
+
*/
|
|
5
|
+
export { EventFake, type FakeInstaller, registerFake, type TestFakes } from './fakes'
|
|
6
|
+
export { CookieJar, PendingRequest, TestResponse } from './request'
|
|
7
|
+
export { type TestApp, type TestAppOptions, testApp } from './test-app'
|
package/src/request.ts
ADDED
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
import { expect } from 'bun:test'
|
|
2
|
+
import type { Application } from '@cslug/core'
|
|
3
|
+
import { SessionStore } from '@cslug/core'
|
|
4
|
+
|
|
5
|
+
type Assertion = (res: TestResponse) => void | Promise<void>
|
|
6
|
+
export type Handler = (request: Request) => Promise<Response>
|
|
7
|
+
|
|
8
|
+
/** The session of the test's cookie jar (created if needed), to read and write as a request would. */
|
|
9
|
+
/** The session data of the jar's session cookie, or undefined (never creates a session). */
|
|
10
|
+
export async function readSession(app: Application, jar: CookieJar): Promise<Record<string, unknown> | undefined> {
|
|
11
|
+
const id = jar.cookies.get(app.config<string | undefined>('session.cookie') ?? 'cslug_session')
|
|
12
|
+
return id ? ((await app.resolve(SessionStore).read(id)) ?? undefined) : undefined
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** The session behind a test client's cookie jar (created when missing), to read and seed it. */
|
|
16
|
+
export async function testSession(app: Application, jar: CookieJar) {
|
|
17
|
+
const name = app.config<string | undefined>('session.cookie') ?? 'cslug_session'
|
|
18
|
+
const store = app.resolve(SessionStore)
|
|
19
|
+
let id = jar.cookies.get(name)
|
|
20
|
+
let data = id ? await store.read(id) : undefined
|
|
21
|
+
if (!id || !data) {
|
|
22
|
+
id = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString('base64url')
|
|
23
|
+
data = {}
|
|
24
|
+
jar.cookies.set(name, id)
|
|
25
|
+
}
|
|
26
|
+
const sessionId = id
|
|
27
|
+
const current = data
|
|
28
|
+
return {
|
|
29
|
+
data: current,
|
|
30
|
+
async write(values: Record<string, unknown>) {
|
|
31
|
+
Object.assign(current, values)
|
|
32
|
+
await store.write(sessionId, current, '1h')
|
|
33
|
+
},
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Cookies kept between the requests of one test (like a browser). */
|
|
38
|
+
export class CookieJar {
|
|
39
|
+
readonly cookies = new Map<string, string>()
|
|
40
|
+
header(): string | undefined {
|
|
41
|
+
return this.cookies.size ? [...this.cookies].map(([k, v]) => `${k}=${v}`).join('; ') : undefined
|
|
42
|
+
}
|
|
43
|
+
store(res: Response): void {
|
|
44
|
+
for (const c of res.headers.getSetCookie()) {
|
|
45
|
+
const [pair, ...attrs] = c.split(';')
|
|
46
|
+
const i = (pair ?? '').indexOf('=')
|
|
47
|
+
if (i < 0) continue
|
|
48
|
+
const name = (pair as string).slice(0, i).trim()
|
|
49
|
+
const value = (pair as string).slice(i + 1).trim()
|
|
50
|
+
const expired = attrs.some((a) => /max-age=0\b/i.test(a.trim()))
|
|
51
|
+
if (expired || value === '') this.cookies.delete(name)
|
|
52
|
+
else this.cookies.set(name, value)
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
clear(): void {
|
|
56
|
+
this.cookies.clear()
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A finished request, with assertions (also usable directly on a PendingRequest). */
|
|
61
|
+
export class TestResponse {
|
|
62
|
+
private text?: string
|
|
63
|
+
|
|
64
|
+
constructor(
|
|
65
|
+
readonly response: Response,
|
|
66
|
+
readonly request: Request,
|
|
67
|
+
private readonly ctx: { app: Application; jar: CookieJar },
|
|
68
|
+
/** Pages rendered by `view()` for this request (needs @cslug/vue). */
|
|
69
|
+
readonly views: { page: unknown; props: Record<string, unknown> }[] = [],
|
|
70
|
+
) {}
|
|
71
|
+
|
|
72
|
+
/** The islands in the HTML: `{ id: 'components/todo-item', props }` (`data-island`, `data-props`). */
|
|
73
|
+
async islands(): Promise<{ id: string; props: Record<string, unknown> }[]> {
|
|
74
|
+
const html = await this.body()
|
|
75
|
+
return [...html.matchAll(/<cslug-island\b([^>]*)>/g)].map(([, attrs]) => {
|
|
76
|
+
const attr = (name: string) => new RegExp(`${name}="([^"]*)"`).exec(attrs ?? '')?.[1] ?? ''
|
|
77
|
+
const decoded = attr('data-props').replace(/&(quot|amp|lt|gt|#39);/g, (_m, e: string) =>
|
|
78
|
+
e === 'quot' ? '"' : e === 'amp' ? '&' : e === 'lt' ? '<' : e === 'gt' ? '>' : "'",
|
|
79
|
+
)
|
|
80
|
+
return { id: attr('data-island'), props: decoded ? (JSON.parse(decoded) as Record<string, unknown>) : {} }
|
|
81
|
+
})
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
get status(): number {
|
|
85
|
+
return this.response.status
|
|
86
|
+
}
|
|
87
|
+
get headers(): Headers {
|
|
88
|
+
return this.response.headers
|
|
89
|
+
}
|
|
90
|
+
async body(): Promise<string> {
|
|
91
|
+
this.text ??= await this.response.clone().text()
|
|
92
|
+
return this.text
|
|
93
|
+
}
|
|
94
|
+
async json<T = Record<string, unknown>>(): Promise<T> {
|
|
95
|
+
return JSON.parse(await this.body()) as T
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** The session data after this request (from the session cookie), including flashed values. */
|
|
99
|
+
async session(): Promise<Record<string, unknown>> {
|
|
100
|
+
const name = this.ctx.app.config<string | undefined>('session.cookie') ?? 'cslug_session'
|
|
101
|
+
const id = this.ctx.jar.cookies.get(name)
|
|
102
|
+
if (!id) return {}
|
|
103
|
+
const data = (await this.ctx.app.resolve(SessionStore).read(id)) ?? {}
|
|
104
|
+
const { _flash, ...rest } = data as Record<string, unknown> & { _flash?: Record<string, unknown> }
|
|
105
|
+
return { ...rest, ...(_flash ?? {}) }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
describe(): string {
|
|
109
|
+
return `${this.request.method} ${new URL(this.request.url).pathname} → ${this.status}`
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* A request being built; `await` runs it and every queued assertion:
|
|
115
|
+
*
|
|
116
|
+
* ```ts
|
|
117
|
+
* await t.post('/fr/trip-request').form({ … }).assertRedirect('/fr/trip-request/thanks').assertSessionHas('success')
|
|
118
|
+
* ```
|
|
119
|
+
*/
|
|
120
|
+
export class PendingRequest implements PromiseLike<TestResponse> {
|
|
121
|
+
private readonly hdrs = new Headers()
|
|
122
|
+
private body?: BodyInit
|
|
123
|
+
private readonly assertions: Assertion[] = []
|
|
124
|
+
private result?: Promise<TestResponse>
|
|
125
|
+
|
|
126
|
+
constructor(
|
|
127
|
+
private readonly method: string,
|
|
128
|
+
private readonly path: string | (() => Promise<string>),
|
|
129
|
+
private readonly ctx: {
|
|
130
|
+
app: Application
|
|
131
|
+
jar: CookieJar
|
|
132
|
+
handle: Handler
|
|
133
|
+
host: string
|
|
134
|
+
before: ((r: PendingRequest) => void | Promise<void>)[]
|
|
135
|
+
/** After each request (the test kit refreshes `t.auth` here). */
|
|
136
|
+
after?: (() => Promise<void>)[]
|
|
137
|
+
},
|
|
138
|
+
) {}
|
|
139
|
+
|
|
140
|
+
// ── building ─────────────────────────────────────────────────────────────────────────────────────
|
|
141
|
+
header(name: string, value: string): this {
|
|
142
|
+
this.hdrs.set(name, value)
|
|
143
|
+
return this
|
|
144
|
+
}
|
|
145
|
+
/** Several headers: `.headers(signWebhook('payments', payload))`. */
|
|
146
|
+
headers(headers: Record<string, string>): this {
|
|
147
|
+
for (const [k, v] of Object.entries(headers)) this.hdrs.set(k, v)
|
|
148
|
+
return this
|
|
149
|
+
}
|
|
150
|
+
private signIn?: { id: unknown }
|
|
151
|
+
/** Send this request as `user`, signed in through the session (needs @cslug/auth). */
|
|
152
|
+
actingAs(user: { id: unknown }): this {
|
|
153
|
+
this.signIn = user
|
|
154
|
+
return this
|
|
155
|
+
}
|
|
156
|
+
/** `Authorization: Bearer <token>`. */
|
|
157
|
+
withToken(token: string): this {
|
|
158
|
+
return this.header('authorization', `Bearer ${token}`)
|
|
159
|
+
}
|
|
160
|
+
/** A JSON body (also sets Accept: application/json). */
|
|
161
|
+
json(data: unknown): this {
|
|
162
|
+
this.jsonCsrf = true
|
|
163
|
+
this.hdrs.set('content-type', 'application/json')
|
|
164
|
+
if (!this.hdrs.has('accept')) this.hdrs.set('accept', 'application/json')
|
|
165
|
+
this.body = JSON.stringify(data, (_k, v) => (typeof v === 'bigint' ? v.toString() : v))
|
|
166
|
+
return this
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* An HTML form post, as a browser sends it: nested objects as `a[b]`, arrays as `a[]`, the session's CSRF
|
|
170
|
+
* token added automatically, a Referer (for redirect back) and `Accept: text/html`.
|
|
171
|
+
*/
|
|
172
|
+
form(data: Record<string, unknown>): this {
|
|
173
|
+
const params = new URLSearchParams()
|
|
174
|
+
const add = (key: string, value: unknown) => {
|
|
175
|
+
if (value === undefined || value === null) return
|
|
176
|
+
if (Array.isArray(value)) for (const v of value) add(`${key}[]`, v)
|
|
177
|
+
else if (typeof value === 'object' && !(value instanceof Date))
|
|
178
|
+
for (const [k, v] of Object.entries(value)) add(`${key}[${k}]`, v)
|
|
179
|
+
else params.append(key, value instanceof Date ? value.toISOString() : String(value))
|
|
180
|
+
}
|
|
181
|
+
for (const [k, v] of Object.entries(data)) add(k, v)
|
|
182
|
+
this.body = params
|
|
183
|
+
this.formCsrf = true
|
|
184
|
+
if (!this.hdrs.has('accept')) this.hdrs.set('accept', 'text/html')
|
|
185
|
+
return this
|
|
186
|
+
}
|
|
187
|
+
private formCsrf = false
|
|
188
|
+
/** JSON writes carry the session's CSRF token in `X-CSRF-Token`, as an island's `useForm` does. */
|
|
189
|
+
private jsonCsrf = false
|
|
190
|
+
|
|
191
|
+
// ── assertions (queued; run when awaited) ───────────────────────────────────────────────────────────
|
|
192
|
+
private assert(fn: Assertion): this {
|
|
193
|
+
this.assertions.push(fn)
|
|
194
|
+
return this
|
|
195
|
+
}
|
|
196
|
+
assertStatus(status: number) {
|
|
197
|
+
return this.assert(async (r) => expect(r.status, `${r.describe()}: ${await r.body()}`).toBe(status))
|
|
198
|
+
}
|
|
199
|
+
assertOk() {
|
|
200
|
+
return this.assertStatus(200)
|
|
201
|
+
}
|
|
202
|
+
assertCreated() {
|
|
203
|
+
return this.assertStatus(201)
|
|
204
|
+
}
|
|
205
|
+
assertNoContent() {
|
|
206
|
+
return this.assertStatus(204)
|
|
207
|
+
}
|
|
208
|
+
assertNotFound() {
|
|
209
|
+
return this.assertStatus(404)
|
|
210
|
+
}
|
|
211
|
+
assertForbidden() {
|
|
212
|
+
return this.assertStatus(403)
|
|
213
|
+
}
|
|
214
|
+
assertUnauthorized() {
|
|
215
|
+
return this.assertStatus(401)
|
|
216
|
+
}
|
|
217
|
+
/** 3xx, optionally to a location (a path matches the end of an absolute location). */
|
|
218
|
+
assertRedirect(to?: string) {
|
|
219
|
+
return this.assert((r) => {
|
|
220
|
+
expect(r.status >= 300 && r.status < 400, `${r.describe()} is not a redirect`).toBe(true)
|
|
221
|
+
if (to !== undefined) {
|
|
222
|
+
const location = r.headers.get('location') ?? ''
|
|
223
|
+
expect(location === to || location.endsWith(to) ? to : location).toBe(to)
|
|
224
|
+
}
|
|
225
|
+
})
|
|
226
|
+
}
|
|
227
|
+
/** A JSON body containing at least these fields (deep). */
|
|
228
|
+
assertJson(subset: unknown) {
|
|
229
|
+
return this.assert(async (r) => expect(await r.json()).toMatchObject(subset as object))
|
|
230
|
+
}
|
|
231
|
+
/** An RFC 9457 problem with this status and code. */
|
|
232
|
+
assertProblem(status: number, code: string) {
|
|
233
|
+
return this.assert(async (r) => {
|
|
234
|
+
expect(r.status, r.describe()).toBe(status)
|
|
235
|
+
expect((await r.json()).code).toBe(code)
|
|
236
|
+
})
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Validation errors, for JSON (422 `errors`) and for HTML forms (redirect back, errors flashed).
|
|
240
|
+
* Values are the expected message (or part of it) for each field.
|
|
241
|
+
*/
|
|
242
|
+
assertInvalid(errors: Record<string, string>) {
|
|
243
|
+
return this.assert(async (r) => {
|
|
244
|
+
const found: Record<string, string[]> =
|
|
245
|
+
r.status === 422
|
|
246
|
+
? ((await r.json()).errors as Record<string, string[]>)
|
|
247
|
+
: (((await r.session())._errors as Record<string, string[]>) ?? {})
|
|
248
|
+
for (const [field, message] of Object.entries(errors)) {
|
|
249
|
+
expect(found[field] ?? [], `no error for "${field}" (errors: ${JSON.stringify(found)})`).toEqual(
|
|
250
|
+
expect.arrayContaining([expect.stringContaining(message)]),
|
|
251
|
+
)
|
|
252
|
+
}
|
|
253
|
+
})
|
|
254
|
+
}
|
|
255
|
+
/** The old input flashed after a failed form post. */
|
|
256
|
+
assertOldInput(fields: Record<string, unknown>) {
|
|
257
|
+
return this.assert(async (r) => expect((await r.session())._old ?? {}).toMatchObject(fields))
|
|
258
|
+
}
|
|
259
|
+
/** A session key (or flashed key), optionally with a value. */
|
|
260
|
+
assertSessionHas(key: string, value?: unknown) {
|
|
261
|
+
return this.assert(async (r) => {
|
|
262
|
+
const session = await r.session()
|
|
263
|
+
expect(session, `session has no "${key}"`).toHaveProperty([key])
|
|
264
|
+
if (value !== undefined) expect(session[key]).toEqual(value)
|
|
265
|
+
})
|
|
266
|
+
}
|
|
267
|
+
assertSessionMissing(key: string) {
|
|
268
|
+
return this.assert(async (r) => expect(await r.session()).not.toHaveProperty([key]))
|
|
269
|
+
}
|
|
270
|
+
/** The page was rendered with `view(View, props)`; `fn` gets the props (use `expect` in it). */
|
|
271
|
+
assertView(view: unknown, fn?: (props: Record<string, unknown>) => unknown) {
|
|
272
|
+
return this.assert(async (r) => {
|
|
273
|
+
const found = r.views.find((v) => v.page === view)
|
|
274
|
+
const name = (v: unknown) =>
|
|
275
|
+
(v as { __name?: string; name?: string })?.__name ?? (v as { name?: string })?.name ?? 'a view'
|
|
276
|
+
expect(
|
|
277
|
+
found,
|
|
278
|
+
`expected ${name(view)} to be rendered; rendered: ${r.views.map((v) => name(v.page)).join(', ') || 'no view'}`,
|
|
279
|
+
).toBeDefined()
|
|
280
|
+
await fn?.((found as { props: Record<string, unknown> }).props)
|
|
281
|
+
})
|
|
282
|
+
}
|
|
283
|
+
/** An island `name` (`'todo-item'` or `'components/todo-item'`) is in the page, with at least these props (deep). */
|
|
284
|
+
assertIsland(name: string, props?: Record<string, unknown>) {
|
|
285
|
+
return this.assert(async (r) => {
|
|
286
|
+
const islands = (await r.islands()).filter((i) => i.id === name || i.id.endsWith(`/${name}`))
|
|
287
|
+
expect(
|
|
288
|
+
islands.length,
|
|
289
|
+
`no island ${name}; islands: ${(await r.islands()).map((i) => i.id).join(', ') || 'none'}`,
|
|
290
|
+
).toBeGreaterThan(0)
|
|
291
|
+
if (props)
|
|
292
|
+
expect(
|
|
293
|
+
islands.some((i) => matches(i.props, props)),
|
|
294
|
+
`no ${name} island with props ${JSON.stringify(props)}`,
|
|
295
|
+
).toBe(true)
|
|
296
|
+
})
|
|
297
|
+
}
|
|
298
|
+
assertSee(text: string) {
|
|
299
|
+
return this.assert(async (r) => expect(await r.body()).toContain(text))
|
|
300
|
+
}
|
|
301
|
+
assertDontSee(text: string) {
|
|
302
|
+
return this.assert(async (r) => expect(await r.body()).not.toContain(text))
|
|
303
|
+
}
|
|
304
|
+
assertHeader(name: string, value?: string) {
|
|
305
|
+
return this.assert((r) => {
|
|
306
|
+
expect(r.headers.has(name), `no "${name}" header`).toBe(true)
|
|
307
|
+
if (value !== undefined) expect(r.headers.get(name)).toBe(value)
|
|
308
|
+
})
|
|
309
|
+
}
|
|
310
|
+
assertCookie(name: string) {
|
|
311
|
+
return this.assert((r) =>
|
|
312
|
+
expect(
|
|
313
|
+
r.headers.getSetCookie().some((c) => c.startsWith(`${name}=`)),
|
|
314
|
+
`no "${name}" cookie set`,
|
|
315
|
+
).toBe(true),
|
|
316
|
+
)
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** Follow the redirect (GET, same cookies). */
|
|
320
|
+
follow(): PendingRequest {
|
|
321
|
+
return new PendingRequest(
|
|
322
|
+
'GET',
|
|
323
|
+
async () => {
|
|
324
|
+
const r = await this
|
|
325
|
+
const location = r.headers.get('location')
|
|
326
|
+
if (!location) throw new Error(`${r.describe()} is not a redirect`)
|
|
327
|
+
return location
|
|
328
|
+
},
|
|
329
|
+
this.ctx,
|
|
330
|
+
)
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// ── running ────────────────────────────────────────────────────────────────────────────────────────
|
|
334
|
+
private async run(): Promise<TestResponse> {
|
|
335
|
+
for (const hook of this.ctx.before) await hook(this)
|
|
336
|
+
if (this.signIn) await (await testSession(this.ctx.app, this.ctx.jar)).write({ 'auth.id': String(this.signIn.id) })
|
|
337
|
+
const path = typeof this.path === 'function' ? await this.path() : this.path
|
|
338
|
+
const url = new URL(path, `http://${this.ctx.host}`)
|
|
339
|
+
const cookie = this.ctx.jar.header()
|
|
340
|
+
if (cookie && !this.hdrs.has('cookie')) this.hdrs.set('cookie', cookie)
|
|
341
|
+
if (this.formCsrf) await this.addCsrf(url)
|
|
342
|
+
if (this.jsonCsrf && !['GET', 'HEAD'].includes(this.method) && !this.hdrs.has('x-csrf-token'))
|
|
343
|
+
this.hdrs.set('x-csrf-token', await this.csrfToken())
|
|
344
|
+
const marker = Bun.randomUUIDv7()
|
|
345
|
+
this.hdrs.set(TEST_REQUEST_HEADER, marker)
|
|
346
|
+
const request = new Request(url, {
|
|
347
|
+
method: this.method,
|
|
348
|
+
headers: this.hdrs,
|
|
349
|
+
body: this.method === 'GET' || this.method === 'HEAD' ? undefined : this.body,
|
|
350
|
+
})
|
|
351
|
+
const views: TestResponse['views'] = []
|
|
352
|
+
const stop = (await vueHooks())?.onView((page, props, ctx) => {
|
|
353
|
+
if (ctx.request.header(TEST_REQUEST_HEADER) === marker) views.push({ page, props })
|
|
354
|
+
})
|
|
355
|
+
let response: Response
|
|
356
|
+
try {
|
|
357
|
+
response = await this.ctx.handle(request)
|
|
358
|
+
} finally {
|
|
359
|
+
stop?.()
|
|
360
|
+
}
|
|
361
|
+
this.ctx.jar.store(response)
|
|
362
|
+
for (const hook of this.ctx.after ?? []) await hook()
|
|
363
|
+
const res = new TestResponse(response, request, this.ctx, views)
|
|
364
|
+
for (const a of this.assertions) await a(res)
|
|
365
|
+
return res
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** Put the session's CSRF token in the form (creating the session first if needed), and a Referer. */
|
|
369
|
+
private async addCsrf(url: URL): Promise<void> {
|
|
370
|
+
if (!this.hdrs.has('referer')) this.hdrs.set('referer', url.toString())
|
|
371
|
+
const params = this.body as URLSearchParams
|
|
372
|
+
if (params.has('_token')) return
|
|
373
|
+
params.set('_token', await this.csrfToken())
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** The session's CSRF token (the session and the token are created if needed). */
|
|
377
|
+
private async csrfToken(): Promise<string> {
|
|
378
|
+
const session = await testSession(this.ctx.app, this.ctx.jar)
|
|
379
|
+
this.hdrs.set('cookie', this.ctx.jar.header() ?? '')
|
|
380
|
+
let token = session.data._token as string | undefined
|
|
381
|
+
if (!token) {
|
|
382
|
+
token = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString('base64url')
|
|
383
|
+
await session.write({ _token: token })
|
|
384
|
+
}
|
|
385
|
+
return token
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
// biome-ignore lint/suspicious/noThenProperty: a PendingRequest is awaited to run it
|
|
389
|
+
then<A = TestResponse, B = never>(
|
|
390
|
+
onFulfilled?: ((value: TestResponse) => A | PromiseLike<A>) | null,
|
|
391
|
+
onRejected?: ((reason: unknown) => B | PromiseLike<B>) | null,
|
|
392
|
+
): Promise<A | B> {
|
|
393
|
+
this.result ??= this.run()
|
|
394
|
+
return this.result.then(onFulfilled, onRejected)
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/** Marks test requests so `assertView` sees only its own request's views. */
|
|
399
|
+
const TEST_REQUEST_HEADER = 'x-cslug-test-request'
|
|
400
|
+
|
|
401
|
+
type VueHooks = {
|
|
402
|
+
onView(
|
|
403
|
+
fn: (
|
|
404
|
+
page: unknown,
|
|
405
|
+
props: Record<string, unknown>,
|
|
406
|
+
ctx: { request: { header(n: string): string | undefined } },
|
|
407
|
+
) => void,
|
|
408
|
+
): () => void
|
|
409
|
+
}
|
|
410
|
+
let vue: Promise<VueHooks | undefined> | undefined
|
|
411
|
+
/** @cslug/vue's view hook, if installed. */
|
|
412
|
+
const vueHooks = () => {
|
|
413
|
+
vue ??= import('@cslug/vue').then((m) => m as unknown as VueHooks).catch(() => undefined)
|
|
414
|
+
return vue
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/** Deep subset match (arrays: every expected item matches some actual item at the same index). */
|
|
418
|
+
function matches(actual: unknown, expected: unknown): boolean {
|
|
419
|
+
if (expected === null || typeof expected !== 'object') return Object.is(actual, expected)
|
|
420
|
+
if (actual === null || typeof actual !== 'object') return false
|
|
421
|
+
return Object.entries(expected).every(([k, v]) => matches((actual as Record<string, unknown>)[k], v))
|
|
422
|
+
}
|
package/src/test-app.ts
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
import { afterAll, afterEach, beforeAll, beforeEach, expect } from 'bun:test'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import {
|
|
4
|
+
type Application,
|
|
5
|
+
type AuthUser,
|
|
6
|
+
Cache,
|
|
7
|
+
Clock,
|
|
8
|
+
FakeClock,
|
|
9
|
+
Lock,
|
|
10
|
+
MemoryCache,
|
|
11
|
+
MemoryLock,
|
|
12
|
+
MemoryRateLimiter,
|
|
13
|
+
MemorySessionStore,
|
|
14
|
+
RateLimiter,
|
|
15
|
+
type Resolved,
|
|
16
|
+
SessionStore,
|
|
17
|
+
type Token,
|
|
18
|
+
} from '@cslug/core'
|
|
19
|
+
import { loadFake, type TestFakes } from './fakes'
|
|
20
|
+
import { CookieJar, type Handler, PendingRequest, readSession, testSession } from './request'
|
|
21
|
+
|
|
22
|
+
type Db = {
|
|
23
|
+
value(q: unknown): Promise<unknown>
|
|
24
|
+
maybeOne(q: unknown): Promise<Record<string, unknown> | null>
|
|
25
|
+
exec(q: unknown): Promise<number>
|
|
26
|
+
pin(): Promise<{ release(): Promise<void> }>
|
|
27
|
+
pool: { unsafe(text: string): Promise<unknown> }
|
|
28
|
+
}
|
|
29
|
+
type DatabaseModule = typeof import('@cslug/database')
|
|
30
|
+
|
|
31
|
+
export type TestAppOptions = {
|
|
32
|
+
/** Build the app; default: `createApp()` from `<cwd>/bootstrap/app.ts`. */
|
|
33
|
+
create?: () => Application | Promise<Application>
|
|
34
|
+
/** Config overrides, by dotted path: `{ 'payments.driver': 'fake' }`. */
|
|
35
|
+
config?: Record<string, unknown>
|
|
36
|
+
/** Fakes to install for every test: `'events'`, and those packages add (`'queue'`, `'mail'`, …). */
|
|
37
|
+
fakes?: readonly (keyof TestFakes | (string & {}))[]
|
|
38
|
+
/**
|
|
39
|
+
* Database isolation per test. `'transaction'` (default): every test runs in a transaction that is rolled
|
|
40
|
+
* back. `'truncate'`: real commits, tables truncated after each test (for concurrency, locks, after-commit
|
|
41
|
+
* across connections). `false`: nothing.
|
|
42
|
+
*/
|
|
43
|
+
database?: 'transaction' | 'truncate' | false
|
|
44
|
+
/** Run migrations once before the tests (default true when a database is configured). */
|
|
45
|
+
migrate?: boolean
|
|
46
|
+
/** Host used for requests (default: the host of `app.url`, else `localhost`). */
|
|
47
|
+
host?: string
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** What `testApp()` returns: the app, an HTTP client without a port, database helpers, the clock, fakes. */
|
|
51
|
+
export type TestApp = {
|
|
52
|
+
readonly app: Application
|
|
53
|
+
readonly clock: FakeClock
|
|
54
|
+
readonly fakes: Partial<TestFakes>
|
|
55
|
+
resolve<K extends Token>(token: K): Resolved<K>
|
|
56
|
+
swap<T>(token: Token<T>, value: T): void
|
|
57
|
+
get(path: string): PendingRequest
|
|
58
|
+
post(path: string): PendingRequest
|
|
59
|
+
put(path: string): PendingRequest
|
|
60
|
+
patch(path: string): PendingRequest
|
|
61
|
+
delete(path: string): PendingRequest
|
|
62
|
+
/** Run something before each request of this test (the auth package uses it for `actingAs`). */
|
|
63
|
+
beforeRequest(hook: (r: PendingRequest) => void | Promise<void>): void
|
|
64
|
+
/** Requests of this test run as `user` (signed in through the session, like `auth.login`). Needs @cslug/auth. */
|
|
65
|
+
actingAs(user: { id: unknown }): void
|
|
66
|
+
/** Who is signed in after the last request (through the session). Needs @cslug/auth. */
|
|
67
|
+
readonly auth: { check(): boolean; user(): AuthUser | null }
|
|
68
|
+
/** API tokens (@cslug/auth): `const { plainText } = await t.tokens.create(user, { abilities: ['todos:read'] })`. */
|
|
69
|
+
readonly tokens: {
|
|
70
|
+
create(
|
|
71
|
+
user: { id: unknown },
|
|
72
|
+
options?: { abilities?: string[]; name?: string; expiresIn?: string | number },
|
|
73
|
+
): Promise<{ plainText: string }>
|
|
74
|
+
}
|
|
75
|
+
readonly db: {
|
|
76
|
+
/** `count('ledger_entries', { bookingId })`: camelCase keys, snake_case columns. */
|
|
77
|
+
count(table: string, where?: Record<string, unknown>): Promise<number>
|
|
78
|
+
find(table: string, id: unknown): Promise<Record<string, unknown> | null>
|
|
79
|
+
}
|
|
80
|
+
/** The scheduler (needs @cslug/queue's ScheduleProvider): `runDue()` runs what is due at the fake clock's time. */
|
|
81
|
+
readonly schedule: {
|
|
82
|
+
runDue(): Promise<import('@cslug/queue').ScheduleRun[]>
|
|
83
|
+
}
|
|
84
|
+
assertDatabaseHas(table: string, where: Record<string, unknown>): Promise<void>
|
|
85
|
+
assertDatabaseMissing(table: string, where: Record<string, unknown>): Promise<void>
|
|
86
|
+
} & Partial<TestFakes>
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Set up an app for a test file: built and started once, isolated per test (database, cookies, fakes, clock,
|
|
90
|
+
* swaps). Call it at the top of the file:
|
|
91
|
+
*
|
|
92
|
+
* ```ts
|
|
93
|
+
* const t = testApp({ fakes: ['events'] })
|
|
94
|
+
* test('…', async () => { await t.get('/todos').assertOk() })
|
|
95
|
+
* ```
|
|
96
|
+
*/
|
|
97
|
+
export function testApp<const F extends readonly string[] = []>(
|
|
98
|
+
options: TestAppOptions & { fakes?: F } = {},
|
|
99
|
+
): TestApp & Pick<TestFakes, Extract<F[number], keyof TestFakes>> {
|
|
100
|
+
let app: Application | undefined
|
|
101
|
+
let db: Db | undefined
|
|
102
|
+
let dbModule: DatabaseModule | undefined
|
|
103
|
+
let pin: { release(): Promise<void> } | undefined
|
|
104
|
+
let clock = new FakeClock()
|
|
105
|
+
const jar = new CookieJar()
|
|
106
|
+
const hooks: ((r: PendingRequest) => void | Promise<void>)[] = []
|
|
107
|
+
let signedIn: AuthUser | null = null
|
|
108
|
+
/** After each request: who the session says is signed in. */
|
|
109
|
+
const after = [
|
|
110
|
+
async () => {
|
|
111
|
+
const a = need()
|
|
112
|
+
const id = (await readSession(a, jar))?.['auth.id']
|
|
113
|
+
if (id === undefined || id === null) {
|
|
114
|
+
signedIn = null
|
|
115
|
+
return
|
|
116
|
+
}
|
|
117
|
+
const { userSource } = await authModule()
|
|
118
|
+
signedIn = ((await (await userSource(a)).find(id)) as AuthUser | null) ?? null
|
|
119
|
+
},
|
|
120
|
+
]
|
|
121
|
+
const fakes: Record<string, unknown> = {}
|
|
122
|
+
let handle: Handler | undefined
|
|
123
|
+
|
|
124
|
+
const need = (): Application => {
|
|
125
|
+
if (!app)
|
|
126
|
+
throw new Error('testApp(): the app is not started yet (use it inside test(), beforeEach() or afterEach())')
|
|
127
|
+
return app
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
beforeAll(async () => {
|
|
131
|
+
app = options.create ? await options.create() : await defaultApp()
|
|
132
|
+
for (const [path, value] of Object.entries(options.config ?? {})) app.setConfig(path, value)
|
|
133
|
+
await app.start()
|
|
134
|
+
try {
|
|
135
|
+
dbModule = await import('@cslug/database')
|
|
136
|
+
if (app.has(dbModule.Database) && app.config('database.url')) db = app.resolve(dbModule.Database) as unknown as Db
|
|
137
|
+
} catch {
|
|
138
|
+
// @cslug/database not installed
|
|
139
|
+
}
|
|
140
|
+
if (db && dbModule && options.migrate !== false) {
|
|
141
|
+
await new dbModule.Migrator(db as never, {
|
|
142
|
+
paths: [join(app.rootDir, 'database/migrations')],
|
|
143
|
+
env: 'test',
|
|
144
|
+
}).migrate()
|
|
145
|
+
}
|
|
146
|
+
try {
|
|
147
|
+
const http = await import('@cslug/http')
|
|
148
|
+
if (app.has(http.HttpKernel)) {
|
|
149
|
+
const kernel = app.resolve(http.HttpKernel)
|
|
150
|
+
handle = (req) => kernel.handle(req, { ip: '127.0.0.1' })
|
|
151
|
+
}
|
|
152
|
+
} catch {
|
|
153
|
+
// @cslug/http not installed
|
|
154
|
+
}
|
|
155
|
+
})
|
|
156
|
+
|
|
157
|
+
beforeEach(async () => {
|
|
158
|
+
const a = need()
|
|
159
|
+
jar.clear()
|
|
160
|
+
hooks.length = 0
|
|
161
|
+
signedIn = null
|
|
162
|
+
clock = new FakeClock(a.config<string | undefined>('app.timezone') ?? 'UTC')
|
|
163
|
+
a.swap(Clock, clock)
|
|
164
|
+
// in-memory stores start empty in every test (rate limits, locks, cache, sessions); Redis ones are left alone
|
|
165
|
+
for (const [contract, Memory] of MEMORY_DRIVERS)
|
|
166
|
+
if (a.resolve(contract as Token<unknown>) instanceof Memory) a.swap(contract as Token<unknown>, new Memory())
|
|
167
|
+
for (const name of options.fakes ?? []) {
|
|
168
|
+
const install = await loadFake(String(name))
|
|
169
|
+
if (!install) throw new Error(`testApp(): no fake named "${String(name)}" (is its package installed?)`)
|
|
170
|
+
fakes[String(name)] = install(a)
|
|
171
|
+
}
|
|
172
|
+
if (db && (options.database ?? 'transaction') === 'transaction') pin = await db.pin()
|
|
173
|
+
})
|
|
174
|
+
|
|
175
|
+
afterEach(async () => {
|
|
176
|
+
await pin?.release()
|
|
177
|
+
pin = undefined
|
|
178
|
+
if (db && options.database === 'truncate') {
|
|
179
|
+
await db.pool.unsafe(`do $$ declare r record; begin
|
|
180
|
+
for r in select tablename from pg_tables where schemaname = 'public' and tablename <> 'cslug_migrations' loop
|
|
181
|
+
execute 'truncate table ' || quote_ident(r.tablename) || ' restart identity cascade';
|
|
182
|
+
end loop; end $$;`)
|
|
183
|
+
}
|
|
184
|
+
app?.restoreSwaps()
|
|
185
|
+
for (const k of Object.keys(fakes)) delete fakes[k]
|
|
186
|
+
})
|
|
187
|
+
|
|
188
|
+
afterAll(async () => {
|
|
189
|
+
await app?.shutdown()
|
|
190
|
+
})
|
|
191
|
+
|
|
192
|
+
const request = (method: string) => (path: string) => {
|
|
193
|
+
const a = need()
|
|
194
|
+
if (!handle) throw new Error('testApp(): HTTP requests need @cslug/http and HttpProvider')
|
|
195
|
+
const host = options.host ?? hostOf(a.config<string | undefined>('app.url'))
|
|
196
|
+
return new PendingRequest(method, path, { app: a, jar, handle, host, before: hooks, after })
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const whereSql = (sqlTag: DatabaseModule['sql'], where: Record<string, unknown>) => {
|
|
200
|
+
const parts = Object.entries(where).map(([k, v]) => {
|
|
201
|
+
const column = sqlTag.ident(k.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`))
|
|
202
|
+
if (v === null) return sqlTag`${column} is null`
|
|
203
|
+
// operators from @cslug/database: { remindedAt: notNull() }, { dueOn: lte('2027-03-01') }
|
|
204
|
+
if (dbModule && v instanceof dbModule.Op) return v.render(column)
|
|
205
|
+
return sqlTag`${column} = ${v}`
|
|
206
|
+
})
|
|
207
|
+
return parts.length ? sqlTag` where ${sqlTag.join(parts, sqlTag` and `)}` : sqlTag``
|
|
208
|
+
}
|
|
209
|
+
const dbOrFail = () => {
|
|
210
|
+
if (!db || !dbModule) throw new Error('testApp(): no database configured (config database.url)')
|
|
211
|
+
return { db, sql: dbModule.sql }
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const api = {
|
|
215
|
+
get app() {
|
|
216
|
+
return need()
|
|
217
|
+
},
|
|
218
|
+
get clock() {
|
|
219
|
+
return clock
|
|
220
|
+
},
|
|
221
|
+
fakes: fakes as Partial<TestFakes>,
|
|
222
|
+
resolve: <K extends Token>(token: K) => need().resolve(token) as Resolved<K>,
|
|
223
|
+
swap: <T>(token: Token<T>, value: T) => {
|
|
224
|
+
need().swap(token, value)
|
|
225
|
+
},
|
|
226
|
+
get: request('GET'),
|
|
227
|
+
post: request('POST'),
|
|
228
|
+
put: request('PUT'),
|
|
229
|
+
patch: request('PATCH'),
|
|
230
|
+
delete: request('DELETE'),
|
|
231
|
+
actingAs: (user: { id: unknown }) => {
|
|
232
|
+
hooks.push(async () => {
|
|
233
|
+
const session = await testSession(need(), jar)
|
|
234
|
+
await session.write({ 'auth.id': String(user.id) }) // @cslug/auth's SESSION_KEY
|
|
235
|
+
})
|
|
236
|
+
},
|
|
237
|
+
beforeRequest: (hook: (r: PendingRequest) => void | Promise<void>) => {
|
|
238
|
+
hooks.push(hook)
|
|
239
|
+
},
|
|
240
|
+
auth: {
|
|
241
|
+
check: () => signedIn !== null,
|
|
242
|
+
user: () => signedIn,
|
|
243
|
+
},
|
|
244
|
+
tokens: {
|
|
245
|
+
async create(
|
|
246
|
+
user: { id: unknown },
|
|
247
|
+
options: { abilities?: string[]; name?: string; expiresIn?: string | number } = {},
|
|
248
|
+
) {
|
|
249
|
+
const { Tokens } = await authModule()
|
|
250
|
+
const { plainText } = await need()
|
|
251
|
+
.resolve(Tokens)
|
|
252
|
+
.create(user, {
|
|
253
|
+
name: options.name ?? 'test',
|
|
254
|
+
abilities: options.abilities,
|
|
255
|
+
expiresIn: options.expiresIn,
|
|
256
|
+
})
|
|
257
|
+
return { plainText }
|
|
258
|
+
},
|
|
259
|
+
},
|
|
260
|
+
schedule: {
|
|
261
|
+
async runDue() {
|
|
262
|
+
const a = need()
|
|
263
|
+
const { Scheduler } = await import('@cslug/queue')
|
|
264
|
+
if (!a.has(Scheduler)) throw new Error('testApp(): t.schedule needs ScheduleProvider (@cslug/queue)')
|
|
265
|
+
// no once-per-tick lock: tests replay the same tick
|
|
266
|
+
return a.resolve(Scheduler).runDue(clock.now(), { exclusive: false })
|
|
267
|
+
},
|
|
268
|
+
},
|
|
269
|
+
db: {
|
|
270
|
+
async count(table: string, where: Record<string, unknown> = {}) {
|
|
271
|
+
const { db, sql } = dbOrFail()
|
|
272
|
+
return Number(await db.value(sql`select count(*)::int from ${sql.ident(table)}${whereSql(sql, where)}`))
|
|
273
|
+
},
|
|
274
|
+
async find(table: string, id: unknown) {
|
|
275
|
+
const { db, sql } = dbOrFail()
|
|
276
|
+
return db.maybeOne(sql`select * from ${sql.ident(table)} where id = ${id}`)
|
|
277
|
+
},
|
|
278
|
+
},
|
|
279
|
+
async assertDatabaseHas(table: string, where: Record<string, unknown>) {
|
|
280
|
+
expect(
|
|
281
|
+
await api.db.count(table, where),
|
|
282
|
+
`no row in ${table} matching ${JSON.stringify(where, bigintSafe)}`,
|
|
283
|
+
).toBeGreaterThan(0)
|
|
284
|
+
},
|
|
285
|
+
async assertDatabaseMissing(table: string, where: Record<string, unknown>) {
|
|
286
|
+
expect(await api.db.count(table, where), `a row in ${table} matches ${JSON.stringify(where, bigintSafe)}`).toBe(0)
|
|
287
|
+
},
|
|
288
|
+
}
|
|
289
|
+
return new Proxy(api, {
|
|
290
|
+
get(target, key, receiver) {
|
|
291
|
+
if (typeof key === 'string' && key in fakes) return fakes[key]
|
|
292
|
+
return Reflect.get(target, key, receiver)
|
|
293
|
+
},
|
|
294
|
+
}) as unknown as TestApp & Pick<TestFakes, Extract<F[number], keyof TestFakes>>
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
const MEMORY_DRIVERS = [
|
|
298
|
+
[Cache, MemoryCache],
|
|
299
|
+
[Lock, MemoryLock],
|
|
300
|
+
[RateLimiter, MemoryRateLimiter],
|
|
301
|
+
[SessionStore, MemorySessionStore],
|
|
302
|
+
] as const
|
|
303
|
+
|
|
304
|
+
const bigintSafe = (_k: string, v: unknown) => (typeof v === 'bigint' ? `${v}n` : v)
|
|
305
|
+
const hostOf = (url: string | undefined) => {
|
|
306
|
+
try {
|
|
307
|
+
return url ? new URL(url).host : 'localhost'
|
|
308
|
+
} catch {
|
|
309
|
+
return 'localhost'
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
async function defaultApp(): Promise<Application> {
|
|
314
|
+
const path = join(process.cwd(), 'bootstrap/app.ts')
|
|
315
|
+
const mod = (await import(path)) as { createApp?: () => Application }
|
|
316
|
+
if (typeof mod.createApp !== 'function')
|
|
317
|
+
throw new Error(`testApp(): ${path} must export createApp(), or pass testApp({ create })`)
|
|
318
|
+
return mod.createApp()
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* @cslug/auth, loaded at runtime with a local type: importing its types here would load a second copy of its
|
|
323
|
+
* `HttpContext` augmentation when the workspace is reachable through two paths.
|
|
324
|
+
*/
|
|
325
|
+
type AuthModule = {
|
|
326
|
+
userSource(app: Application): Promise<{ find(id: unknown): Promise<object | null> }>
|
|
327
|
+
Tokens: Token<{
|
|
328
|
+
create(
|
|
329
|
+
user: unknown,
|
|
330
|
+
options: { name: string; abilities?: string[]; expiresIn?: string | number },
|
|
331
|
+
): Promise<{ plainText: string }>
|
|
332
|
+
}>
|
|
333
|
+
}
|
|
334
|
+
const AUTH_PACKAGE: string = '@cslug/auth'
|
|
335
|
+
const authModule = async (): Promise<AuthModule> => {
|
|
336
|
+
try {
|
|
337
|
+
return (await import(AUTH_PACKAGE)) as AuthModule
|
|
338
|
+
} catch {
|
|
339
|
+
throw new Error('testApp(): t.auth and t.tokens need @cslug/auth')
|
|
340
|
+
}
|
|
341
|
+
}
|