@cslug/testing 0.0.0-stage → 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/README.md +6 -2
- package/docs/README.md +27 -0
- package/docs/api.md +46 -0
- package/package.json +85 -4
- package/src/fakes.ts +63 -0
- package/src/index.ts +7 -0
- package/src/request.ts +323 -0
- package/src/test-app.ts +256 -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
|
+
More assertions arrive with their packages: `actingAs` (auth), `assertQueued` (queue), `assertView` /
|
|
27
|
+
`assertIsland` (vue), `assertSent` (mail). See [api.md](api.md).
|
package/docs/api.md
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
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'`, plus those packages register |
|
|
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), and
|
|
16
|
+
each installed fake as `t.<name>`.
|
|
17
|
+
|
|
18
|
+
## Requests (`PendingRequest`, awaited to run)
|
|
19
|
+
|
|
20
|
+
Building: `header`, `headers({…})`, `withToken`, `actingAs(user)` (signed in through the session, with
|
|
21
|
+
@cslug/auth), `json(data)`, `form(data)` (nested keys, CSRF, Referer).
|
|
22
|
+
|
|
23
|
+
Assertions (queued, run in order): `assertStatus`, `assertOk`, `assertCreated`, `assertNoContent`,
|
|
24
|
+
`assertNotFound`, `assertForbidden`, `assertUnauthorized`, `assertRedirect(to?)`, `assertJson(subset)`,
|
|
25
|
+
`assertProblem(status, code)`, `assertInvalid({ field: 'part of message' })` (JSON 422 or flashed),
|
|
26
|
+
`assertOldInput`, `assertSessionHas(key, value?)`, `assertSessionMissing`, `assertSee`, `assertDontSee`,
|
|
27
|
+
`assertHeader`, `assertCookie`. `follow()` makes the GET to the redirect location with the same cookies.
|
|
28
|
+
|
|
29
|
+
The awaited value is a `TestResponse`: `status`, `headers`, `body()`, `json()`, `session()`.
|
|
30
|
+
|
|
31
|
+
## Fakes
|
|
32
|
+
|
|
33
|
+
`EventFake` (`'events'`): `emitted`, `of(Event)`, `assertEmitted(Event, predicate?)`, `assertNotEmitted`,
|
|
34
|
+
`assertNothingEmitted`.
|
|
35
|
+
|
|
36
|
+
Packages add theirs:
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
registerFake('queue', (app) => { const fake = new QueueFake(); app.swap(Queue, fake); return fake })
|
|
40
|
+
declare module '@cslug/testing' { interface TestFakes { queue: QueueFake } }
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Database isolation
|
|
44
|
+
|
|
45
|
+
`Database.pin()` (from `@cslug/database`) holds one transaction for the test; queries without their own
|
|
46
|
+
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.1.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.1.0",
|
|
32
|
+
"@cslug/validation": "0.1.0",
|
|
33
|
+
"@cslug/http": "0.1.0",
|
|
34
|
+
"@cslug/vue": "0.1.0",
|
|
35
|
+
"@cslug/database": "0.1.0",
|
|
36
|
+
"@cslug/redis": "0.1.0",
|
|
37
|
+
"@cslug/queue": "0.1.0",
|
|
38
|
+
"@cslug/auth": "0.1.0",
|
|
39
|
+
"@cslug/mail": "0.1.0",
|
|
40
|
+
"@cslug/notification": "0.1.0",
|
|
41
|
+
"@cslug/storage": "0.1.0",
|
|
42
|
+
"@cslug/webhook": "0.1.0",
|
|
43
|
+
"@cslug/ai": "0.1.0",
|
|
44
|
+
"@cslug/cli": "0.1.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,63 @@
|
|
|
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
|
+
type Recorded = { event: AnyEventClass; payload: unknown }
|
|
18
|
+
|
|
19
|
+
/** Records emitted events instead of running listeners. */
|
|
20
|
+
export class EventFake extends EventBus {
|
|
21
|
+
readonly emitted: Recorded[] = []
|
|
22
|
+
|
|
23
|
+
constructor(app: Application) {
|
|
24
|
+
super(app, Logger.null())
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
override async emit<P>(event: EventClass<P>, payload: P): Promise<void> {
|
|
28
|
+
this.emitted.push({ event, payload })
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Emitted events of one class (payloads). */
|
|
32
|
+
of<P>(event: EventClass<P>): P[] {
|
|
33
|
+
return this.emitted.filter((e) => e.event === event).map((e) => e.payload as P)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
assertEmitted<P>(event: EventClass<P>, predicate?: (e: { payload: P }) => boolean): void {
|
|
37
|
+
const matching = this.of(event).filter((payload) => !predicate || predicate({ payload }))
|
|
38
|
+
expect(
|
|
39
|
+
matching.length,
|
|
40
|
+
`expected ${event.eventName} to be emitted${predicate ? ' (matching the predicate)' : ''}`,
|
|
41
|
+
).toBeGreaterThan(0)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
assertNotEmitted<P>(event: EventClass<P>): void {
|
|
45
|
+
expect(this.of(event).length, `expected ${event.eventName} not to be emitted`).toBe(0)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
assertNothingEmitted(): void {
|
|
49
|
+
expect(this.emitted.map((e) => e.event.eventName)).toEqual([])
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
registerFake('events', (app) => {
|
|
54
|
+
const fake = new EventFake(app)
|
|
55
|
+
app.swap(EventBus, fake)
|
|
56
|
+
return fake
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
declare module './fakes' {
|
|
60
|
+
interface TestFakes {
|
|
61
|
+
events: EventFake
|
|
62
|
+
}
|
|
63
|
+
}
|
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,323 @@
|
|
|
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
|
+
export async function testSession(app: Application, jar: CookieJar) {
|
|
10
|
+
const name = app.config<string | undefined>('session.cookie') ?? 'cslug_session'
|
|
11
|
+
const store = app.resolve(SessionStore)
|
|
12
|
+
let id = jar.cookies.get(name)
|
|
13
|
+
let data = id ? await store.read(id) : undefined
|
|
14
|
+
if (!id || !data) {
|
|
15
|
+
id = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString('base64url')
|
|
16
|
+
data = {}
|
|
17
|
+
jar.cookies.set(name, id)
|
|
18
|
+
}
|
|
19
|
+
const sessionId = id
|
|
20
|
+
const current = data
|
|
21
|
+
return {
|
|
22
|
+
data: current,
|
|
23
|
+
async write(values: Record<string, unknown>) {
|
|
24
|
+
Object.assign(current, values)
|
|
25
|
+
await store.write(sessionId, current, '1h')
|
|
26
|
+
},
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Cookies kept between the requests of one test (like a browser). */
|
|
31
|
+
export class CookieJar {
|
|
32
|
+
readonly cookies = new Map<string, string>()
|
|
33
|
+
header(): string | undefined {
|
|
34
|
+
return this.cookies.size ? [...this.cookies].map(([k, v]) => `${k}=${v}`).join('; ') : undefined
|
|
35
|
+
}
|
|
36
|
+
store(res: Response): void {
|
|
37
|
+
for (const c of res.headers.getSetCookie()) {
|
|
38
|
+
const [pair, ...attrs] = c.split(';')
|
|
39
|
+
const i = (pair ?? '').indexOf('=')
|
|
40
|
+
if (i < 0) continue
|
|
41
|
+
const name = (pair as string).slice(0, i).trim()
|
|
42
|
+
const value = (pair as string).slice(i + 1).trim()
|
|
43
|
+
const expired = attrs.some((a) => /max-age=0\b/i.test(a.trim()))
|
|
44
|
+
if (expired || value === '') this.cookies.delete(name)
|
|
45
|
+
else this.cookies.set(name, value)
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
clear(): void {
|
|
49
|
+
this.cookies.clear()
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** A finished request, with assertions (also usable directly on a PendingRequest). */
|
|
54
|
+
export class TestResponse {
|
|
55
|
+
private text?: string
|
|
56
|
+
|
|
57
|
+
constructor(
|
|
58
|
+
readonly response: Response,
|
|
59
|
+
readonly request: Request,
|
|
60
|
+
private readonly ctx: { app: Application; jar: CookieJar },
|
|
61
|
+
) {}
|
|
62
|
+
|
|
63
|
+
get status(): number {
|
|
64
|
+
return this.response.status
|
|
65
|
+
}
|
|
66
|
+
get headers(): Headers {
|
|
67
|
+
return this.response.headers
|
|
68
|
+
}
|
|
69
|
+
async body(): Promise<string> {
|
|
70
|
+
this.text ??= await this.response.clone().text()
|
|
71
|
+
return this.text
|
|
72
|
+
}
|
|
73
|
+
async json<T = Record<string, unknown>>(): Promise<T> {
|
|
74
|
+
return JSON.parse(await this.body()) as T
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The session data after this request (from the session cookie), including flashed values. */
|
|
78
|
+
async session(): Promise<Record<string, unknown>> {
|
|
79
|
+
const name = this.ctx.app.config<string | undefined>('session.cookie') ?? 'cslug_session'
|
|
80
|
+
const id = this.ctx.jar.cookies.get(name)
|
|
81
|
+
if (!id) return {}
|
|
82
|
+
const data = (await this.ctx.app.resolve(SessionStore).read(id)) ?? {}
|
|
83
|
+
const { _flash, ...rest } = data as Record<string, unknown> & { _flash?: Record<string, unknown> }
|
|
84
|
+
return { ...rest, ...(_flash ?? {}) }
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
describe(): string {
|
|
88
|
+
return `${this.request.method} ${new URL(this.request.url).pathname} → ${this.status}`
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* A request being built; `await` runs it and every queued assertion:
|
|
94
|
+
*
|
|
95
|
+
* ```ts
|
|
96
|
+
* await t.post('/fr/trip-request').form({ … }).assertRedirect('/fr/trip-request/thanks').assertSessionHas('success')
|
|
97
|
+
* ```
|
|
98
|
+
*/
|
|
99
|
+
export class PendingRequest implements PromiseLike<TestResponse> {
|
|
100
|
+
private readonly hdrs = new Headers()
|
|
101
|
+
private body?: BodyInit
|
|
102
|
+
private readonly assertions: Assertion[] = []
|
|
103
|
+
private result?: Promise<TestResponse>
|
|
104
|
+
|
|
105
|
+
constructor(
|
|
106
|
+
private readonly method: string,
|
|
107
|
+
private readonly path: string | (() => Promise<string>),
|
|
108
|
+
private readonly ctx: {
|
|
109
|
+
app: Application
|
|
110
|
+
jar: CookieJar
|
|
111
|
+
handle: Handler
|
|
112
|
+
host: string
|
|
113
|
+
before: ((r: PendingRequest) => void | Promise<void>)[]
|
|
114
|
+
},
|
|
115
|
+
) {}
|
|
116
|
+
|
|
117
|
+
// ── building ─────────────────────────────────────────────────────────────────────────────────────
|
|
118
|
+
header(name: string, value: string): this {
|
|
119
|
+
this.hdrs.set(name, value)
|
|
120
|
+
return this
|
|
121
|
+
}
|
|
122
|
+
/** Several headers: `.headers(signWebhook('payments', payload))`. */
|
|
123
|
+
headers(headers: Record<string, string>): this {
|
|
124
|
+
for (const [k, v] of Object.entries(headers)) this.hdrs.set(k, v)
|
|
125
|
+
return this
|
|
126
|
+
}
|
|
127
|
+
private signIn?: { id: unknown }
|
|
128
|
+
/** Send this request as `user`, signed in through the session (needs @cslug/auth). */
|
|
129
|
+
actingAs(user: { id: unknown }): this {
|
|
130
|
+
this.signIn = user
|
|
131
|
+
return this
|
|
132
|
+
}
|
|
133
|
+
/** `Authorization: Bearer <token>`. */
|
|
134
|
+
withToken(token: string): this {
|
|
135
|
+
return this.header('authorization', `Bearer ${token}`)
|
|
136
|
+
}
|
|
137
|
+
/** A JSON body (also sets Accept: application/json). */
|
|
138
|
+
json(data: unknown): this {
|
|
139
|
+
this.hdrs.set('content-type', 'application/json')
|
|
140
|
+
if (!this.hdrs.has('accept')) this.hdrs.set('accept', 'application/json')
|
|
141
|
+
this.body = JSON.stringify(data, (_k, v) => (typeof v === 'bigint' ? v.toString() : v))
|
|
142
|
+
return this
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* An HTML form post, as a browser sends it: nested objects as `a[b]`, arrays as `a[]`, the session's CSRF
|
|
146
|
+
* token added automatically, a Referer (for redirect back) and `Accept: text/html`.
|
|
147
|
+
*/
|
|
148
|
+
form(data: Record<string, unknown>): this {
|
|
149
|
+
const params = new URLSearchParams()
|
|
150
|
+
const add = (key: string, value: unknown) => {
|
|
151
|
+
if (value === undefined || value === null) return
|
|
152
|
+
if (Array.isArray(value)) for (const v of value) add(`${key}[]`, v)
|
|
153
|
+
else if (typeof value === 'object' && !(value instanceof Date))
|
|
154
|
+
for (const [k, v] of Object.entries(value)) add(`${key}[${k}]`, v)
|
|
155
|
+
else params.append(key, value instanceof Date ? value.toISOString() : String(value))
|
|
156
|
+
}
|
|
157
|
+
for (const [k, v] of Object.entries(data)) add(k, v)
|
|
158
|
+
this.body = params
|
|
159
|
+
this.formCsrf = true
|
|
160
|
+
if (!this.hdrs.has('accept')) this.hdrs.set('accept', 'text/html')
|
|
161
|
+
return this
|
|
162
|
+
}
|
|
163
|
+
private formCsrf = false
|
|
164
|
+
|
|
165
|
+
// ── assertions (queued; run when awaited) ───────────────────────────────────────────────────────────
|
|
166
|
+
private assert(fn: Assertion): this {
|
|
167
|
+
this.assertions.push(fn)
|
|
168
|
+
return this
|
|
169
|
+
}
|
|
170
|
+
assertStatus(status: number) {
|
|
171
|
+
return this.assert(async (r) => expect(r.status, `${r.describe()}: ${await r.body()}`).toBe(status))
|
|
172
|
+
}
|
|
173
|
+
assertOk() {
|
|
174
|
+
return this.assertStatus(200)
|
|
175
|
+
}
|
|
176
|
+
assertCreated() {
|
|
177
|
+
return this.assertStatus(201)
|
|
178
|
+
}
|
|
179
|
+
assertNoContent() {
|
|
180
|
+
return this.assertStatus(204)
|
|
181
|
+
}
|
|
182
|
+
assertNotFound() {
|
|
183
|
+
return this.assertStatus(404)
|
|
184
|
+
}
|
|
185
|
+
assertForbidden() {
|
|
186
|
+
return this.assertStatus(403)
|
|
187
|
+
}
|
|
188
|
+
assertUnauthorized() {
|
|
189
|
+
return this.assertStatus(401)
|
|
190
|
+
}
|
|
191
|
+
/** 3xx, optionally to a location (a path matches the end of an absolute location). */
|
|
192
|
+
assertRedirect(to?: string) {
|
|
193
|
+
return this.assert((r) => {
|
|
194
|
+
expect(r.status >= 300 && r.status < 400, `${r.describe()} is not a redirect`).toBe(true)
|
|
195
|
+
if (to !== undefined) {
|
|
196
|
+
const location = r.headers.get('location') ?? ''
|
|
197
|
+
expect(location === to || location.endsWith(to) ? to : location).toBe(to)
|
|
198
|
+
}
|
|
199
|
+
})
|
|
200
|
+
}
|
|
201
|
+
/** A JSON body containing at least these fields (deep). */
|
|
202
|
+
assertJson(subset: unknown) {
|
|
203
|
+
return this.assert(async (r) => expect(await r.json()).toMatchObject(subset as object))
|
|
204
|
+
}
|
|
205
|
+
/** An RFC 9457 problem with this status and code. */
|
|
206
|
+
assertProblem(status: number, code: string) {
|
|
207
|
+
return this.assert(async (r) => {
|
|
208
|
+
expect(r.status, r.describe()).toBe(status)
|
|
209
|
+
expect((await r.json()).code).toBe(code)
|
|
210
|
+
})
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Validation errors, for JSON (422 `errors`) and for HTML forms (redirect back, errors flashed).
|
|
214
|
+
* Values are the expected message (or part of it) for each field.
|
|
215
|
+
*/
|
|
216
|
+
assertInvalid(errors: Record<string, string>) {
|
|
217
|
+
return this.assert(async (r) => {
|
|
218
|
+
const found: Record<string, string[]> =
|
|
219
|
+
r.status === 422
|
|
220
|
+
? ((await r.json()).errors as Record<string, string[]>)
|
|
221
|
+
: (((await r.session())._errors as Record<string, string[]>) ?? {})
|
|
222
|
+
for (const [field, message] of Object.entries(errors)) {
|
|
223
|
+
expect(found[field] ?? [], `no error for "${field}" (errors: ${JSON.stringify(found)})`).toEqual(
|
|
224
|
+
expect.arrayContaining([expect.stringContaining(message)]),
|
|
225
|
+
)
|
|
226
|
+
}
|
|
227
|
+
})
|
|
228
|
+
}
|
|
229
|
+
/** The old input flashed after a failed form post. */
|
|
230
|
+
assertOldInput(fields: Record<string, unknown>) {
|
|
231
|
+
return this.assert(async (r) => expect((await r.session())._old ?? {}).toMatchObject(fields))
|
|
232
|
+
}
|
|
233
|
+
/** A session key (or flashed key), optionally with a value. */
|
|
234
|
+
assertSessionHas(key: string, value?: unknown) {
|
|
235
|
+
return this.assert(async (r) => {
|
|
236
|
+
const session = await r.session()
|
|
237
|
+
expect(session, `session has no "${key}"`).toHaveProperty([key])
|
|
238
|
+
if (value !== undefined) expect(session[key]).toEqual(value)
|
|
239
|
+
})
|
|
240
|
+
}
|
|
241
|
+
assertSessionMissing(key: string) {
|
|
242
|
+
return this.assert(async (r) => expect(await r.session()).not.toHaveProperty([key]))
|
|
243
|
+
}
|
|
244
|
+
assertSee(text: string) {
|
|
245
|
+
return this.assert(async (r) => expect(await r.body()).toContain(text))
|
|
246
|
+
}
|
|
247
|
+
assertDontSee(text: string) {
|
|
248
|
+
return this.assert(async (r) => expect(await r.body()).not.toContain(text))
|
|
249
|
+
}
|
|
250
|
+
assertHeader(name: string, value?: string) {
|
|
251
|
+
return this.assert((r) => {
|
|
252
|
+
expect(r.headers.has(name), `no "${name}" header`).toBe(true)
|
|
253
|
+
if (value !== undefined) expect(r.headers.get(name)).toBe(value)
|
|
254
|
+
})
|
|
255
|
+
}
|
|
256
|
+
assertCookie(name: string) {
|
|
257
|
+
return this.assert((r) =>
|
|
258
|
+
expect(
|
|
259
|
+
r.headers.getSetCookie().some((c) => c.startsWith(`${name}=`)),
|
|
260
|
+
`no "${name}" cookie set`,
|
|
261
|
+
).toBe(true),
|
|
262
|
+
)
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** Follow the redirect (GET, same cookies). */
|
|
266
|
+
follow(): PendingRequest {
|
|
267
|
+
return new PendingRequest(
|
|
268
|
+
'GET',
|
|
269
|
+
async () => {
|
|
270
|
+
const r = await this
|
|
271
|
+
const location = r.headers.get('location')
|
|
272
|
+
if (!location) throw new Error(`${r.describe()} is not a redirect`)
|
|
273
|
+
return location
|
|
274
|
+
},
|
|
275
|
+
this.ctx,
|
|
276
|
+
)
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// ── running ────────────────────────────────────────────────────────────────────────────────────────
|
|
280
|
+
private async run(): Promise<TestResponse> {
|
|
281
|
+
for (const hook of this.ctx.before) await hook(this)
|
|
282
|
+
if (this.signIn) await (await testSession(this.ctx.app, this.ctx.jar)).write({ 'auth.id': String(this.signIn.id) })
|
|
283
|
+
const path = typeof this.path === 'function' ? await this.path() : this.path
|
|
284
|
+
const url = new URL(path, `http://${this.ctx.host}`)
|
|
285
|
+
const cookie = this.ctx.jar.header()
|
|
286
|
+
if (cookie && !this.hdrs.has('cookie')) this.hdrs.set('cookie', cookie)
|
|
287
|
+
if (this.formCsrf) await this.addCsrf(url)
|
|
288
|
+
const request = new Request(url, {
|
|
289
|
+
method: this.method,
|
|
290
|
+
headers: this.hdrs,
|
|
291
|
+
body: this.method === 'GET' || this.method === 'HEAD' ? undefined : this.body,
|
|
292
|
+
})
|
|
293
|
+
const response = await this.ctx.handle(request)
|
|
294
|
+
this.ctx.jar.store(response)
|
|
295
|
+
const res = new TestResponse(response, request, this.ctx)
|
|
296
|
+
for (const a of this.assertions) await a(res)
|
|
297
|
+
return res
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** Put the session's CSRF token in the form (creating the session first if needed), and a Referer. */
|
|
301
|
+
private async addCsrf(url: URL): Promise<void> {
|
|
302
|
+
if (!this.hdrs.has('referer')) this.hdrs.set('referer', url.toString())
|
|
303
|
+
const params = this.body as URLSearchParams
|
|
304
|
+
if (params.has('_token')) return
|
|
305
|
+
const session = await testSession(this.ctx.app, this.ctx.jar)
|
|
306
|
+
this.hdrs.set('cookie', this.ctx.jar.header() ?? '')
|
|
307
|
+
let token = session.data._token as string | undefined
|
|
308
|
+
if (!token) {
|
|
309
|
+
token = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString('base64url')
|
|
310
|
+
await session.write({ _token: token })
|
|
311
|
+
}
|
|
312
|
+
params.set('_token', token)
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// biome-ignore lint/suspicious/noThenProperty: a PendingRequest is awaited to run it
|
|
316
|
+
then<A = TestResponse, B = never>(
|
|
317
|
+
onFulfilled?: ((value: TestResponse) => A | PromiseLike<A>) | null,
|
|
318
|
+
onRejected?: ((reason: unknown) => B | PromiseLike<B>) | null,
|
|
319
|
+
): Promise<A | B> {
|
|
320
|
+
this.result ??= this.run()
|
|
321
|
+
return this.result.then(onFulfilled, onRejected)
|
|
322
|
+
}
|
|
323
|
+
}
|
package/src/test-app.ts
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import { afterAll, afterEach, beforeAll, beforeEach, expect } from 'bun:test'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import {
|
|
4
|
+
type Application,
|
|
5
|
+
Cache,
|
|
6
|
+
Clock,
|
|
7
|
+
FakeClock,
|
|
8
|
+
Lock,
|
|
9
|
+
MemoryCache,
|
|
10
|
+
MemoryLock,
|
|
11
|
+
MemoryRateLimiter,
|
|
12
|
+
MemorySessionStore,
|
|
13
|
+
RateLimiter,
|
|
14
|
+
type Resolved,
|
|
15
|
+
SessionStore,
|
|
16
|
+
type Token,
|
|
17
|
+
} from '@cslug/core'
|
|
18
|
+
import { fakeInstaller, type TestFakes } from './fakes'
|
|
19
|
+
import { CookieJar, type Handler, PendingRequest, testSession } from './request'
|
|
20
|
+
|
|
21
|
+
type Db = {
|
|
22
|
+
value(q: unknown): Promise<unknown>
|
|
23
|
+
maybeOne(q: unknown): Promise<Record<string, unknown> | null>
|
|
24
|
+
exec(q: unknown): Promise<number>
|
|
25
|
+
pin(): Promise<{ release(): Promise<void> }>
|
|
26
|
+
pool: { unsafe(text: string): Promise<unknown> }
|
|
27
|
+
}
|
|
28
|
+
type DatabaseModule = typeof import('@cslug/database')
|
|
29
|
+
|
|
30
|
+
export type TestAppOptions = {
|
|
31
|
+
/** Build the app; default: `createApp()` from `<cwd>/bootstrap/app.ts`. */
|
|
32
|
+
create?: () => Application | Promise<Application>
|
|
33
|
+
/** Config overrides, by dotted path: `{ 'payments.driver': 'fake' }`. */
|
|
34
|
+
config?: Record<string, unknown>
|
|
35
|
+
/** Fakes to install for every test: `'events'`, and those packages add (`'queue'`, `'mail'`, …). */
|
|
36
|
+
fakes?: (keyof TestFakes | string)[]
|
|
37
|
+
/**
|
|
38
|
+
* Database isolation per test. `'transaction'` (default): every test runs in a transaction that is rolled
|
|
39
|
+
* back. `'truncate'`: real commits, tables truncated after each test (for concurrency, locks, after-commit
|
|
40
|
+
* across connections). `false`: nothing.
|
|
41
|
+
*/
|
|
42
|
+
database?: 'transaction' | 'truncate' | false
|
|
43
|
+
/** Run migrations once before the tests (default true when a database is configured). */
|
|
44
|
+
migrate?: boolean
|
|
45
|
+
/** Host used for requests (default: the host of `app.url`, else `localhost`). */
|
|
46
|
+
host?: string
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** What `testApp()` returns: the app, an HTTP client without a port, database helpers, the clock, fakes. */
|
|
50
|
+
export type TestApp = {
|
|
51
|
+
readonly app: Application
|
|
52
|
+
readonly clock: FakeClock
|
|
53
|
+
readonly fakes: Partial<TestFakes>
|
|
54
|
+
resolve<K extends Token>(token: K): Resolved<K>
|
|
55
|
+
swap<T>(token: Token<T>, value: T): void
|
|
56
|
+
get(path: string): PendingRequest
|
|
57
|
+
post(path: string): PendingRequest
|
|
58
|
+
put(path: string): PendingRequest
|
|
59
|
+
patch(path: string): PendingRequest
|
|
60
|
+
delete(path: string): PendingRequest
|
|
61
|
+
/** Run something before each request of this test (the auth package uses it for `actingAs`). */
|
|
62
|
+
beforeRequest(hook: (r: PendingRequest) => void | Promise<void>): void
|
|
63
|
+
/** Requests of this test run as `user` (signed in through the session, like `auth.login`). Needs @cslug/auth. */
|
|
64
|
+
actingAs(user: { id: unknown }): void
|
|
65
|
+
readonly db: {
|
|
66
|
+
/** `count('ledger_entries', { bookingId })`: camelCase keys, snake_case columns. */
|
|
67
|
+
count(table: string, where?: Record<string, unknown>): Promise<number>
|
|
68
|
+
find(table: string, id: unknown): Promise<Record<string, unknown> | null>
|
|
69
|
+
}
|
|
70
|
+
assertDatabaseHas(table: string, where: Record<string, unknown>): Promise<void>
|
|
71
|
+
assertDatabaseMissing(table: string, where: Record<string, unknown>): Promise<void>
|
|
72
|
+
} & Partial<TestFakes>
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Set up an app for a test file: built and started once, isolated per test (database, cookies, fakes, clock,
|
|
76
|
+
* swaps). Call it at the top of the file:
|
|
77
|
+
*
|
|
78
|
+
* ```ts
|
|
79
|
+
* const t = testApp({ fakes: ['events'] })
|
|
80
|
+
* test('…', async () => { await t.get('/todos').assertOk() })
|
|
81
|
+
* ```
|
|
82
|
+
*/
|
|
83
|
+
export function testApp(options: TestAppOptions = {}): TestApp {
|
|
84
|
+
let app: Application | undefined
|
|
85
|
+
let db: Db | undefined
|
|
86
|
+
let dbModule: DatabaseModule | undefined
|
|
87
|
+
let pin: { release(): Promise<void> } | undefined
|
|
88
|
+
let clock = new FakeClock()
|
|
89
|
+
const jar = new CookieJar()
|
|
90
|
+
const hooks: ((r: PendingRequest) => void | Promise<void>)[] = []
|
|
91
|
+
const fakes: Record<string, unknown> = {}
|
|
92
|
+
let handle: Handler | undefined
|
|
93
|
+
|
|
94
|
+
const need = (): Application => {
|
|
95
|
+
if (!app)
|
|
96
|
+
throw new Error('testApp(): the app is not started yet (use it inside test(), beforeEach() or afterEach())')
|
|
97
|
+
return app
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
beforeAll(async () => {
|
|
101
|
+
app = options.create ? await options.create() : await defaultApp()
|
|
102
|
+
for (const [path, value] of Object.entries(options.config ?? {})) app.setConfig(path, value)
|
|
103
|
+
await app.start()
|
|
104
|
+
try {
|
|
105
|
+
dbModule = await import('@cslug/database')
|
|
106
|
+
if (app.has(dbModule.Database) && app.config('database.url')) db = app.resolve(dbModule.Database) as unknown as Db
|
|
107
|
+
} catch {
|
|
108
|
+
// @cslug/database not installed
|
|
109
|
+
}
|
|
110
|
+
if (db && dbModule && options.migrate !== false) {
|
|
111
|
+
await new dbModule.Migrator(db as never, {
|
|
112
|
+
paths: [join(app.rootDir, 'database/migrations')],
|
|
113
|
+
env: 'test',
|
|
114
|
+
}).migrate()
|
|
115
|
+
}
|
|
116
|
+
try {
|
|
117
|
+
const http = await import('@cslug/http')
|
|
118
|
+
if (app.has(http.HttpKernel)) {
|
|
119
|
+
const kernel = app.resolve(http.HttpKernel)
|
|
120
|
+
handle = (req) => kernel.handle(req, { ip: '127.0.0.1' })
|
|
121
|
+
}
|
|
122
|
+
} catch {
|
|
123
|
+
// @cslug/http not installed
|
|
124
|
+
}
|
|
125
|
+
})
|
|
126
|
+
|
|
127
|
+
beforeEach(async () => {
|
|
128
|
+
const a = need()
|
|
129
|
+
jar.clear()
|
|
130
|
+
hooks.length = 0
|
|
131
|
+
clock = new FakeClock(a.config<string | undefined>('app.timezone') ?? 'UTC')
|
|
132
|
+
a.swap(Clock, clock)
|
|
133
|
+
// in-memory stores start empty in every test (rate limits, locks, cache, sessions); Redis ones are left alone
|
|
134
|
+
for (const [contract, Memory] of MEMORY_DRIVERS)
|
|
135
|
+
if (a.resolve(contract as Token<unknown>) instanceof Memory) a.swap(contract as Token<unknown>, new Memory())
|
|
136
|
+
for (const name of options.fakes ?? []) {
|
|
137
|
+
const install = fakeInstaller(String(name))
|
|
138
|
+
if (!install) throw new Error(`testApp(): no fake named "${String(name)}" (is its package installed?)`)
|
|
139
|
+
fakes[String(name)] = install(a)
|
|
140
|
+
}
|
|
141
|
+
if (db && (options.database ?? 'transaction') === 'transaction') pin = await db.pin()
|
|
142
|
+
})
|
|
143
|
+
|
|
144
|
+
afterEach(async () => {
|
|
145
|
+
await pin?.release()
|
|
146
|
+
pin = undefined
|
|
147
|
+
if (db && options.database === 'truncate') {
|
|
148
|
+
await db.pool.unsafe(`do $$ declare r record; begin
|
|
149
|
+
for r in select tablename from pg_tables where schemaname = 'public' and tablename <> 'cslug_migrations' loop
|
|
150
|
+
execute 'truncate table ' || quote_ident(r.tablename) || ' restart identity cascade';
|
|
151
|
+
end loop; end $$;`)
|
|
152
|
+
}
|
|
153
|
+
app?.restoreSwaps()
|
|
154
|
+
for (const k of Object.keys(fakes)) delete fakes[k]
|
|
155
|
+
})
|
|
156
|
+
|
|
157
|
+
afterAll(async () => {
|
|
158
|
+
await app?.shutdown()
|
|
159
|
+
})
|
|
160
|
+
|
|
161
|
+
const request = (method: string) => (path: string) => {
|
|
162
|
+
const a = need()
|
|
163
|
+
if (!handle) throw new Error('testApp(): HTTP requests need @cslug/http and HttpProvider')
|
|
164
|
+
const host = options.host ?? hostOf(a.config<string | undefined>('app.url'))
|
|
165
|
+
return new PendingRequest(method, path, { app: a, jar, handle, host, before: hooks })
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const whereSql = (sqlTag: DatabaseModule['sql'], where: Record<string, unknown>) => {
|
|
169
|
+
const parts = Object.entries(where).map(([k, v]) => {
|
|
170
|
+
const column = sqlTag.ident(k.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`))
|
|
171
|
+
return v === null ? sqlTag`${column} is null` : sqlTag`${column} = ${v}`
|
|
172
|
+
})
|
|
173
|
+
return parts.length ? sqlTag` where ${sqlTag.join(parts, sqlTag` and `)}` : sqlTag``
|
|
174
|
+
}
|
|
175
|
+
const dbOrFail = () => {
|
|
176
|
+
if (!db || !dbModule) throw new Error('testApp(): no database configured (config database.url)')
|
|
177
|
+
return { db, sql: dbModule.sql }
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const api = {
|
|
181
|
+
get app() {
|
|
182
|
+
return need()
|
|
183
|
+
},
|
|
184
|
+
get clock() {
|
|
185
|
+
return clock
|
|
186
|
+
},
|
|
187
|
+
fakes: fakes as Partial<TestFakes>,
|
|
188
|
+
resolve: <K extends Token>(token: K) => need().resolve(token) as Resolved<K>,
|
|
189
|
+
swap: <T>(token: Token<T>, value: T) => {
|
|
190
|
+
need().swap(token, value)
|
|
191
|
+
},
|
|
192
|
+
get: request('GET'),
|
|
193
|
+
post: request('POST'),
|
|
194
|
+
put: request('PUT'),
|
|
195
|
+
patch: request('PATCH'),
|
|
196
|
+
delete: request('DELETE'),
|
|
197
|
+
actingAs: (user: { id: unknown }) => {
|
|
198
|
+
hooks.push(async () => {
|
|
199
|
+
const session = await testSession(need(), jar)
|
|
200
|
+
await session.write({ 'auth.id': String(user.id) }) // @cslug/auth's SESSION_KEY
|
|
201
|
+
})
|
|
202
|
+
},
|
|
203
|
+
beforeRequest: (hook: (r: PendingRequest) => void | Promise<void>) => {
|
|
204
|
+
hooks.push(hook)
|
|
205
|
+
},
|
|
206
|
+
db: {
|
|
207
|
+
async count(table: string, where: Record<string, unknown> = {}) {
|
|
208
|
+
const { db, sql } = dbOrFail()
|
|
209
|
+
return Number(await db.value(sql`select count(*)::int from ${sql.ident(table)}${whereSql(sql, where)}`))
|
|
210
|
+
},
|
|
211
|
+
async find(table: string, id: unknown) {
|
|
212
|
+
const { db, sql } = dbOrFail()
|
|
213
|
+
return db.maybeOne(sql`select * from ${sql.ident(table)} where id = ${id}`)
|
|
214
|
+
},
|
|
215
|
+
},
|
|
216
|
+
async assertDatabaseHas(table: string, where: Record<string, unknown>) {
|
|
217
|
+
expect(
|
|
218
|
+
await api.db.count(table, where),
|
|
219
|
+
`no row in ${table} matching ${JSON.stringify(where, bigintSafe)}`,
|
|
220
|
+
).toBeGreaterThan(0)
|
|
221
|
+
},
|
|
222
|
+
async assertDatabaseMissing(table: string, where: Record<string, unknown>) {
|
|
223
|
+
expect(await api.db.count(table, where), `a row in ${table} matches ${JSON.stringify(where, bigintSafe)}`).toBe(0)
|
|
224
|
+
},
|
|
225
|
+
}
|
|
226
|
+
return new Proxy(api, {
|
|
227
|
+
get(target, key, receiver) {
|
|
228
|
+
if (typeof key === 'string' && key in fakes) return fakes[key]
|
|
229
|
+
return Reflect.get(target, key, receiver)
|
|
230
|
+
},
|
|
231
|
+
}) as unknown as TestApp
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const MEMORY_DRIVERS = [
|
|
235
|
+
[Cache, MemoryCache],
|
|
236
|
+
[Lock, MemoryLock],
|
|
237
|
+
[RateLimiter, MemoryRateLimiter],
|
|
238
|
+
[SessionStore, MemorySessionStore],
|
|
239
|
+
] as const
|
|
240
|
+
|
|
241
|
+
const bigintSafe = (_k: string, v: unknown) => (typeof v === 'bigint' ? `${v}n` : v)
|
|
242
|
+
const hostOf = (url: string | undefined) => {
|
|
243
|
+
try {
|
|
244
|
+
return url ? new URL(url).host : 'localhost'
|
|
245
|
+
} catch {
|
|
246
|
+
return 'localhost'
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
async function defaultApp(): Promise<Application> {
|
|
251
|
+
const path = join(process.cwd(), 'bootstrap/app.ts')
|
|
252
|
+
const mod = (await import(path)) as { createApp?: () => Application }
|
|
253
|
+
if (typeof mod.createApp !== 'function')
|
|
254
|
+
throw new Error(`testApp(): ${path} must export createApp(), or pass testApp({ create })`)
|
|
255
|
+
return mod.createApp()
|
|
256
|
+
}
|