@zigordev/test 0.0.0-stage → 1.15.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 +145 -2
- package/dist/app.d.ts +36 -0
- package/dist/app.d.ts.map +1 -0
- package/dist/app.js +52 -0
- package/dist/app.js.map +1 -0
- package/dist/postgres.d.ts +27 -0
- package/dist/postgres.d.ts.map +1 -0
- package/dist/postgres.js +95 -0
- package/dist/postgres.js.map +1 -0
- package/package.json +46 -3
package/README.md
CHANGED
|
@@ -1,3 +1,146 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @zigordev/test
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Test helpers for the services of the platform. It starts a real PostgreSQL for a test run, gives every test file its own migrated copy of the database, and builds an app for the API tests.
|
|
4
|
+
|
|
5
|
+
## What it is
|
|
6
|
+
|
|
7
|
+
Two entry points. `@zigordev/test/postgres` gives a real database:
|
|
8
|
+
|
|
9
|
+
| Export | What it is |
|
|
10
|
+
| ---------------------------------- | ------------------------------------------------------------------------------------------------------- |
|
|
11
|
+
| `postgresGlobalSetup(options?)` | The global setup of a Vitest project: one PostgreSQL container for the whole run, with a template ready |
|
|
12
|
+
| `useTestDatabase()` | In a test file: a copy of the template for this file, made before its tests and dropped after them |
|
|
13
|
+
| `startPostgres(options?)` | The same start without Vitest: a container, a prepared template and a `stop()` |
|
|
14
|
+
| `createTestDatabase(templateUrl)` | The same copy without Vitest: a `url` and a `drop()` |
|
|
15
|
+
| `databaseUrl(serverUrl, database)` | The address of another database on the same server, with the same sign-in |
|
|
16
|
+
| `postgresImage` | `postgres:18-alpine`, the image used when none is given |
|
|
17
|
+
|
|
18
|
+
`@zigordev/test/app` gives the harness for API tests:
|
|
19
|
+
|
|
20
|
+
| Export | What it is |
|
|
21
|
+
| ----------------------------------- | ------------------------------------------------------------------------------------------------- |
|
|
22
|
+
| `useApp(build)` | In a test file: the app, built once before its tests and closed after them |
|
|
23
|
+
| `captureLogs()` | A place for the logger to write to, which keeps every line and finds the events in it |
|
|
24
|
+
| `expectProblem(response, expected)` | Checks that an answer is an error in the platform's format, with the status and the code expected |
|
|
25
|
+
|
|
26
|
+
A template database is a database that PostgreSQL copies to make a new one. Copying a migrated template takes milliseconds. Running the migrations again for every test file would take seconds.
|
|
27
|
+
|
|
28
|
+
## Why we have it
|
|
29
|
+
|
|
30
|
+
The platform's test rules ask for two things that are slow or hard to get right alone:
|
|
31
|
+
|
|
32
|
+
- **A real database.** A test runs against PostgreSQL 18, the version production runs, never against a stand-in. A stand-in hides the bugs that matter: a constraint, a lock, a query that sorts differently.
|
|
33
|
+
- **Tests that never see each other's data.** Every test file gets its own copy of the migrated database. Test files run at the same time, and none of them can break another.
|
|
34
|
+
|
|
35
|
+
Without this package, every service would write its own container start, its own copies and its own clean-up, and each one would differ a little.
|
|
36
|
+
|
|
37
|
+
## How it works here
|
|
38
|
+
|
|
39
|
+
Testcontainers starts the container. It is a library that runs throwaway containers for tests through Docker, and removes them when the run ends, even after a crash.
|
|
40
|
+
|
|
41
|
+
```mermaid
|
|
42
|
+
flowchart LR
|
|
43
|
+
setup["Global setup: start PostgreSQL 18"] --> prepare["prepare: migrate the template"]
|
|
44
|
+
prepare --> lock["Close the template to clients"]
|
|
45
|
+
lock --> fileA["File A: CREATE DATABASE ... TEMPLATE"]
|
|
46
|
+
lock --> fileB["File B: CREATE DATABASE ... TEMPLATE"]
|
|
47
|
+
fileA --> dropA["Drop A's copy"]
|
|
48
|
+
fileB --> dropB["Drop B's copy"]
|
|
49
|
+
dropA --> stop["Stop the container"]
|
|
50
|
+
dropB --> stop
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
- One container serves the whole run of a Vitest project. Its server runs with `fsync` off, because nothing in a test database has to survive a crash.
|
|
54
|
+
- `prepare` receives the template's address, usually to run the migrations. After it, the template refuses new clients, and any client that `prepare` left open is closed, so a copy never waits.
|
|
55
|
+
- `useTestDatabase` makes the copy in a `beforeAll` and drops it in an `afterAll`. The tests of one file share it, in order.
|
|
56
|
+
- Tests that need a container sit in files named `*.db.test.ts`, in a Vitest project of their own, named `<name>:db`. `pnpm check` runs them. `pnpm check:quick`, which the push hook runs, leaves them out, so a push never waits for Docker.
|
|
57
|
+
|
|
58
|
+
## How to use it
|
|
59
|
+
|
|
60
|
+
Install it beside Vitest:
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
pnpm add --save-dev @zigordev/test
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
A repo that installs it also needs these three lines under `allowBuilds` in its `pnpm-workspace.yaml`. Testcontainers brings three packages with install scripts that it does not need, and pnpm stops the install with `ERR_PNPM_IGNORED_BUILDS` until each one is named:
|
|
67
|
+
|
|
68
|
+
```yaml
|
|
69
|
+
allowBuilds:
|
|
70
|
+
cpu-features: false
|
|
71
|
+
protobufjs: false
|
|
72
|
+
ssh2: false
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Until Testcontainers stops bringing `archiver`, a repo also needs this line under `overrides`. Testcontainers 12.2.2 brings `glob` 10.5.0 through `archiver-utils`, with a known flaw, [GHSA-3g3m-2fjr-6pw4](https://github.com/advisories/GHSA-3g3m-2fjr-6pw4), and the Dependencies job fails on it. [Record 0033](../../docs/adr/0033-a-flawed-dependency-of-a-dependency-is-replaced-by-an-override.md) says how such a flaw is handled:
|
|
76
|
+
|
|
77
|
+
```yaml
|
|
78
|
+
overrides:
|
|
79
|
+
archiver-utils>glob: 14.0.6
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
The line goes when a release of Testcontainers drops `archiver`, which [testcontainers-node#1652](https://github.com/testcontainers/testcontainers-node/pull/1652) does. `glob` 14 is a new major version, first released on 2026-10-27, so the one-month rule would have kept the line out until 2026-11-27. The owner allowed it on 2026-11-23 as an exception, in their words "Merge it now". The risk is low: Testcontainers uses `glob` only to copy files into a container, which these helpers never do, and every test passes with it.
|
|
83
|
+
|
|
84
|
+
An app keeps its database tests in a second Vitest project, `vitest.db.config.ts` beside its `vitest.config.ts`:
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
import { defineProject } from 'vitest/config';
|
|
88
|
+
|
|
89
|
+
export default defineProject({
|
|
90
|
+
test: {
|
|
91
|
+
name: 'notes-api:db',
|
|
92
|
+
include: ['src/**/*.db.test.ts'],
|
|
93
|
+
globalSetup: ['global-setup.ts'],
|
|
94
|
+
hookTimeout: 60_000,
|
|
95
|
+
testTimeout: 60_000,
|
|
96
|
+
},
|
|
97
|
+
});
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
`global-setup.ts` starts PostgreSQL and migrates the template:
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
import { postgresGlobalSetup } from '@zigordev/test/postgres';
|
|
104
|
+
import { migrate } from './src/db/migrate.ts';
|
|
105
|
+
|
|
106
|
+
export const setup = postgresGlobalSetup({ prepare: migrate });
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
A test file takes its own database and builds the app on it:
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
import { createLogger } from '@zigordev/otel';
|
|
113
|
+
import { captureLogs, expectProblem, useApp } from '@zigordev/test/app';
|
|
114
|
+
import { useTestDatabase } from '@zigordev/test/postgres';
|
|
115
|
+
import { expect, it } from 'vitest';
|
|
116
|
+
import { buildApp } from './app.ts';
|
|
117
|
+
import { readConfig } from './config.ts';
|
|
118
|
+
|
|
119
|
+
const database = useTestDatabase();
|
|
120
|
+
const logs = captureLogs();
|
|
121
|
+
const server = useApp(() =>
|
|
122
|
+
buildApp({
|
|
123
|
+
config: readConfig({ OTEL_SERVICE_NAME: 'notes-api', DATABASE_URL: database.url }),
|
|
124
|
+
logger: createLogger({ service: 'notes-api', destination: logs }),
|
|
125
|
+
})
|
|
126
|
+
);
|
|
127
|
+
|
|
128
|
+
it('answers 404 for a note that does not exist', async () => {
|
|
129
|
+
const url = '/api/v1/notes/0190d4c2-0000-7000-8000-000000000000';
|
|
130
|
+
const response = await server.app.inject({ method: 'GET', url });
|
|
131
|
+
|
|
132
|
+
expectProblem(response, { status: 404, code: 'not_found' });
|
|
133
|
+
expect(logs.events()).toEqual([]);
|
|
134
|
+
});
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
- Call `useTestDatabase()` before `useApp()`. Hooks run in the order they are written, so the database exists when the app is built, and the app closes before the database is dropped.
|
|
138
|
+
- `expectProblem` checks the status, the media type `application/problem+json`, the code, and that the body holds exactly the fields of the platform's error format: `type`, `title`, `status`, `detail`, `instance`, `code` and `params`. It returns the body, for checks on `params`.
|
|
139
|
+
- `startPostgres({ image })` takes another image. A product passes the one its `compose.yaml` runs.
|
|
140
|
+
|
|
141
|
+
## How to check that it works
|
|
142
|
+
|
|
143
|
+
- `pnpm exec vitest run --project test --project test:db` in `toolkit` runs this package's own tests. The database tests ask the server for its version, and fail on anything but PostgreSQL 18.
|
|
144
|
+
- A database test that fails with `Could not find a working container runtime strategy` means Docker is not running. Start Docker Desktop and run it again.
|
|
145
|
+
- A test that hangs in its `beforeAll` while it makes the copy usually holds a client open on the template. `prepare` has to close what it opens. The package closes what is left, but only once, right after `prepare`.
|
|
146
|
+
- Containers that a crashed run left behind are removed by Testcontainers' own clean-up container, `testcontainers/ryuk`, within seconds.
|
package/dist/app.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export type LogLine = Readonly<Record<string, unknown>>;
|
|
2
|
+
export interface CapturedLogs {
|
|
3
|
+
write(line: string): void;
|
|
4
|
+
readonly lines: readonly LogLine[];
|
|
5
|
+
events(): string[];
|
|
6
|
+
find(event: string): LogLine[];
|
|
7
|
+
clear(): void;
|
|
8
|
+
}
|
|
9
|
+
export declare function captureLogs(): CapturedLogs;
|
|
10
|
+
export interface Closable {
|
|
11
|
+
close(): unknown;
|
|
12
|
+
}
|
|
13
|
+
export declare function useApp<T extends Closable>(build: () => T | Promise<T>): {
|
|
14
|
+
readonly app: T;
|
|
15
|
+
};
|
|
16
|
+
export interface InjectedResponse {
|
|
17
|
+
readonly statusCode: number;
|
|
18
|
+
readonly headers: Readonly<Record<string, unknown>>;
|
|
19
|
+
json(): unknown;
|
|
20
|
+
}
|
|
21
|
+
export interface ExpectedProblem {
|
|
22
|
+
readonly status: number;
|
|
23
|
+
readonly code: string;
|
|
24
|
+
readonly instance?: string;
|
|
25
|
+
}
|
|
26
|
+
export interface Problem {
|
|
27
|
+
readonly type: string;
|
|
28
|
+
readonly title: string;
|
|
29
|
+
readonly status: number;
|
|
30
|
+
readonly detail: string;
|
|
31
|
+
readonly instance: string;
|
|
32
|
+
readonly code: string;
|
|
33
|
+
readonly params: Readonly<Record<string, unknown>>;
|
|
34
|
+
}
|
|
35
|
+
export declare function expectProblem(response: InjectedResponse, expected: ExpectedProblem): Problem;
|
|
36
|
+
//# sourceMappingURL=app.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"app.d.ts","sourceRoot":"","sources":["../src/app.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,OAAO,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;AAExD,MAAM,WAAW,YAAY;IAC3B,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,QAAQ,CAAC,KAAK,EAAE,SAAS,OAAO,EAAE,CAAC;IACnC,MAAM,IAAI,MAAM,EAAE,CAAC;IACnB,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,EAAE,CAAC;IAC/B,KAAK,IAAI,IAAI,CAAC;CACf;AAED,wBAAgB,WAAW,IAAI,YAAY,CAiB1C;AAED,MAAM,WAAW,QAAQ;IACvB,KAAK,IAAI,OAAO,CAAC;CAClB;AAED,wBAAgB,MAAM,CAAC,CAAC,SAAS,QAAQ,EAAE,KAAK,EAAE,MAAM,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,GAAG;IAAE,QAAQ,CAAC,GAAG,EAAE,CAAC,CAAA;CAAE,CAkB3F;AAED,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;IACpD,IAAI,IAAI,OAAO,CAAC;CACjB;AAED,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED,MAAM,WAAW,OAAO;IACtB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;CACpD;AAED,wBAAgB,aAAa,CAAC,QAAQ,EAAE,gBAAgB,EAAE,QAAQ,EAAE,eAAe,GAAG,OAAO,CAc5F"}
|
package/dist/app.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { afterAll, beforeAll, expect } from 'vitest';
|
|
2
|
+
export function captureLogs() {
|
|
3
|
+
const lines = [];
|
|
4
|
+
return {
|
|
5
|
+
write(line) {
|
|
6
|
+
for (const text of line.split('\n')) {
|
|
7
|
+
if (text.trim() !== '') {
|
|
8
|
+
lines.push(JSON.parse(text));
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
},
|
|
12
|
+
lines,
|
|
13
|
+
events: () => lines.flatMap((line) => (typeof line.event === 'string' ? [line.event] : [])),
|
|
14
|
+
find: (event) => lines.filter((line) => line.event === event),
|
|
15
|
+
clear: () => {
|
|
16
|
+
lines.length = 0;
|
|
17
|
+
},
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
export function useApp(build) {
|
|
21
|
+
let app;
|
|
22
|
+
beforeAll(async () => {
|
|
23
|
+
app = await build();
|
|
24
|
+
});
|
|
25
|
+
afterAll(async () => {
|
|
26
|
+
await app?.close();
|
|
27
|
+
});
|
|
28
|
+
return {
|
|
29
|
+
get app() {
|
|
30
|
+
if (app === undefined) {
|
|
31
|
+
throw new Error('useApp gives its app only to tests and hooks that run after its beforeAll');
|
|
32
|
+
}
|
|
33
|
+
return app;
|
|
34
|
+
},
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
export function expectProblem(response, expected) {
|
|
38
|
+
expect(response.statusCode).toBe(expected.status);
|
|
39
|
+
expect(String(response.headers['content-type'])).toMatch(/^application\/problem\+json/);
|
|
40
|
+
const body = response.json();
|
|
41
|
+
expect(body).toEqual({
|
|
42
|
+
type: expect.any(String),
|
|
43
|
+
title: expect.any(String),
|
|
44
|
+
status: expected.status,
|
|
45
|
+
detail: expect.any(String),
|
|
46
|
+
instance: expected.instance ?? expect.any(String),
|
|
47
|
+
code: expected.code,
|
|
48
|
+
params: expect.any(Object),
|
|
49
|
+
});
|
|
50
|
+
return body;
|
|
51
|
+
}
|
|
52
|
+
//# sourceMappingURL=app.js.map
|
package/dist/app.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"app.js","sourceRoot":"","sources":["../src/app.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAYrD,MAAM,UAAU,WAAW;IACzB,MAAM,KAAK,GAAc,EAAE,CAAC;IAC5B,OAAO;QACL,KAAK,CAAC,IAAI;YACR,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;gB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MAAM,CAAC,CAAC;IAClD,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,6BAA6B,CAAC,CAAC;IACxF,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAI,EAAE,CAAC;IAC7B,MAAM,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC;QACnB,IAAI,EAAE,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC;QACxB,KAAK,EAAE,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC;QACzB,MAAM,EAAE,QAAQ,CAAC,MAAM;QACvB,MAAM,EAAE,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC;QAC1B,QAAQ,EAAE,QAAQ,CAAC,QAAQ,IAAI,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC;QACjD,IAAI,EAAE,QAAQ,CAAC,IAAI;QACnB,MAAM,EAAE,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC;KAC3B,CAAC,CAAC;IACH,OAAO,IAAe,CAAC;AACzB,CAAC"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { TestProject } from 'vitest/node';
|
|
2
|
+
declare module 'vitest' {
|
|
3
|
+
interface ProvidedContext {
|
|
4
|
+
postgresTemplateUrl: string;
|
|
5
|
+
}
|
|
6
|
+
}
|
|
7
|
+
export declare const postgresImage = "postgres:18-alpine";
|
|
8
|
+
export interface StartPostgresOptions {
|
|
9
|
+
readonly image?: string;
|
|
10
|
+
readonly prepare?: (templateUrl: string) => Promise<void>;
|
|
11
|
+
}
|
|
12
|
+
export interface PostgresServer {
|
|
13
|
+
readonly templateUrl: string;
|
|
14
|
+
stop(): Promise<void>;
|
|
15
|
+
}
|
|
16
|
+
export interface TestDatabase {
|
|
17
|
+
readonly url: string;
|
|
18
|
+
drop(): Promise<void>;
|
|
19
|
+
}
|
|
20
|
+
export declare function databaseUrl(serverUrl: string, database: string): string;
|
|
21
|
+
export declare function startPostgres(options?: StartPostgresOptions): Promise<PostgresServer>;
|
|
22
|
+
export declare function createTestDatabase(templateUrl: string): Promise<TestDatabase>;
|
|
23
|
+
export declare function postgresGlobalSetup(options?: StartPostgresOptions): (project: TestProject) => Promise<() => Promise<void>>;
|
|
24
|
+
export declare function useTestDatabase(): {
|
|
25
|
+
readonly url: string;
|
|
26
|
+
};
|
|
27
|
+
//# sourceMappingURL=postgres.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"postgres.d.ts","sourceRoot":"","sources":["../src/postgres.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE/C,OAAO,QAAQ,QAAQ,CAAC;IACtB,UAAiB,eAAe;QAC9B,mBAAmB,EAAE,MAAM,CAAC;KAC7B;CACF;AAED,eAAO,MAAM,aAAa,uBAAuB,CAAC;AAElD,MAAM,WAAW,oBAAoB;IACnC,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC,WAAW,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAC3D;AAED,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACvB;AAED,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACvB;AAQD,wBAAgB,WAAW,CAAC,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAIvE;AAgBD,wBAAsB,aAAa,CAAC,OAAO,GAAE,oBAAyB,GAAG,OAAO,CAAC,cAAc,CAAC,CAmC/F;AAED,wBAAsB,kBAAkB,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC,CAgBnF;AAED,wBAAgB,mBAAmB,CACjC,OAAO,GAAE,oBAAyB,GACjC,CAAC,OAAO,EAAE,WAAW,KAAK,OAAO,CAAC,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,CAMxD;AAED,wBAAgB,eAAe,IAAI;IAAE,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAkB1D"}
|
package/dist/postgres.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { PostgreSqlContainer } from '@testcontainers/postgresql';
|
|
3
|
+
import pg from 'pg';
|
|
4
|
+
import { afterAll, beforeAll, inject } from 'vitest';
|
|
5
|
+
export const postgresImage = 'postgres:18-alpine';
|
|
6
|
+
const templateDatabase = 'app_template';
|
|
7
|
+
function identifier(name) {
|
|
8
|
+
return `"${name.replaceAll('"', '""')}"`;
|
|
9
|
+
}
|
|
10
|
+
export function databaseUrl(serverUrl, database) {
|
|
11
|
+
const url = new URL(serverUrl);
|
|
12
|
+
url.pathname = `/${encodeURIComponent(database)}`;
|
|
13
|
+
return url.toString();
|
|
14
|
+
}
|
|
15
|
+
function databaseName(url) {
|
|
16
|
+
return decodeURIComponent(new URL(url).pathname.slice(1));
|
|
17
|
+
}
|
|
18
|
+
async function withClient(url, work) {
|
|
19
|
+
const client = new pg.Client({ connectionString: url });
|
|
20
|
+
await client.connect();
|
|
21
|
+
try {
|
|
22
|
+
return await work(client);
|
|
23
|
+
}
|
|
24
|
+
finally {
|
|
25
|
+
await client.end();
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
export async function startPostgres(options = {}) {
|
|
29
|
+
const container = await new PostgreSqlContainer(options.image ?? postgresImage)
|
|
30
|
+
.withDatabase(templateDatabase)
|
|
31
|
+
.withCommand([
|
|
32
|
+
'postgres',
|
|
33
|
+
'-c',
|
|
34
|
+
'fsync=off',
|
|
35
|
+
'-c',
|
|
36
|
+
'synchronous_commit=off',
|
|
37
|
+
'-c',
|
|
38
|
+
'full_page_writes=off',
|
|
39
|
+
])
|
|
40
|
+
.start();
|
|
41
|
+
const templateUrl = container.getConnectionUri();
|
|
42
|
+
try {
|
|
43
|
+
await options.prepare?.(templateUrl);
|
|
44
|
+
await withClient(databaseUrl(templateUrl, 'postgres'), async (client) => {
|
|
45
|
+
await client.query(`ALTER DATABASE ${identifier(templateDatabase)} WITH ALLOW_CONNECTIONS false`);
|
|
46
|
+
await client.query('SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = $1 AND pid <> pg_backend_pid()', [templateDatabase]);
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
await container.stop();
|
|
51
|
+
throw error;
|
|
52
|
+
}
|
|
53
|
+
return {
|
|
54
|
+
templateUrl,
|
|
55
|
+
stop: async () => {
|
|
56
|
+
await container.stop();
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
export async function createTestDatabase(templateUrl) {
|
|
61
|
+
const name = `test_${randomUUID().replaceAll('-', '')}`;
|
|
62
|
+
const maintenanceUrl = databaseUrl(templateUrl, 'postgres');
|
|
63
|
+
await withClient(maintenanceUrl, (client) => client.query(`CREATE DATABASE ${identifier(name)} TEMPLATE ${identifier(databaseName(templateUrl))}`));
|
|
64
|
+
return {
|
|
65
|
+
url: databaseUrl(templateUrl, name),
|
|
66
|
+
drop: async () => {
|
|
67
|
+
await withClient(maintenanceUrl, (client) => client.query(`DROP DATABASE IF EXISTS ${identifier(name)} WITH (FORCE)`));
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
export function postgresGlobalSetup(options = {}) {
|
|
72
|
+
return async (project) => {
|
|
73
|
+
const server = await startPostgres(options);
|
|
74
|
+
project.provide('postgresTemplateUrl', server.templateUrl);
|
|
75
|
+
return () => server.stop();
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
export function useTestDatabase() {
|
|
79
|
+
let database;
|
|
80
|
+
beforeAll(async () => {
|
|
81
|
+
database = await createTestDatabase(inject('postgresTemplateUrl'));
|
|
82
|
+
});
|
|
83
|
+
afterAll(async () => {
|
|
84
|
+
await database?.drop();
|
|
85
|
+
});
|
|
86
|
+
return {
|
|
87
|
+
get url() {
|
|
88
|
+
if (database === undefined) {
|
|
89
|
+
throw new Error('useTestDatabase gives its database only to tests and hooks that run after its beforeAll');
|
|
90
|
+
}
|
|
91
|
+
return database.url;
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
//# sourceMappingURL=postgres.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"postgres.js","sourceRoot":"","sources":["../src/postgres.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AASrD,MAAM,CAAC,MAAM,aAAa,GAAG,oBAAoB,CAAC;AAiBlD,MAAM,gBAAgB,GAAG,cAAc,CAAC;AAExC,SAAS,UAAU,CAAC,IAAY;IAC9B,OAAO,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC;AAC3C,CAAC;AAED,MAAM,UAAU,WAAW,CAAC,SAAiB,EAAE,QAAgB;IAC7D,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,SAAS,CAAC,CAAC;IAC/B,GAAG,CAAC,QAAQ,GAAG,IAAI,kBAAkB,CAAC,QAAQ,CAAC,EAAE,CAAC;IAClD,OAAO,GAAG,CAAC,QAAQ,EAAE,CAAC;AACxB,CAAC;AAED,SAAS,YAAY,CAAC,GAAW;IAC/B,OAAO,kBAAkB,CAAC,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC,QAAQ,C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AAS,CAAC,KAAK,IAAI,EAAE;QACnB,QAAQ,GAAG,MAAM,kBAAkB,CAAC,MAAM,CAAC,qBAAqB,CAAC,CAAC,CAAC;IACrE,CAAC,CAAC,CAAC;IACH,QAAQ,CAAC,KAAK,IAAI,EAAE;QAClB,MAAM,QAAQ,EAAE,IAAI,EAAE,CAAC;IACzB,CAAC,CAAC,CAAC;IACH,OAAO;QACL,IAAI,GAAG;YACL,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;gBAC3B,MAAM,IAAI,KAAK,CACb,yFAAyF,CAC1F,CAAC;YACJ,CAAC;YACD,OAAO,QAAQ,CAAC,GAAG,CAAC;QACtB,CAAC;KACF,CAAC;AACJ,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zigordev/test",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.15.0",
|
|
4
|
+
"description": "Test helpers for zigordev services: a real PostgreSQL with one migrated copy per test file, and the harness that builds an app for API tests",
|
|
5
|
+
"license": "UNLICENSED",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=26"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"dist"
|
|
12
|
+
],
|
|
13
|
+
"exports": {
|
|
14
|
+
"./postgres": {
|
|
15
|
+
"types": "./dist/postgres.d.ts",
|
|
16
|
+
"default": "./dist/postgres.js"
|
|
17
|
+
},
|
|
18
|
+
"./app": {
|
|
19
|
+
"types": "./dist/app.d.ts",
|
|
20
|
+
"default": "./dist/app.js"
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"@testcontainers/postgresql": "12.2.2",
|
|
25
|
+
"pg": "8.23.1"
|
|
26
|
+
},
|
|
27
|
+
"peerDependencies": {
|
|
28
|
+
"vitest": "^5.1.0"
|
|
29
|
+
},
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"@types/node": "26.6.6",
|
|
32
|
+
"@types/pg": "8.23.1",
|
|
33
|
+
"@zigordev/dev": "1.15.0",
|
|
34
|
+
"typescript": "7.0.2",
|
|
35
|
+
"vitest": "5.1.1"
|
|
36
|
+
},
|
|
37
|
+
"publishConfig": {
|
|
38
|
+
"access": "public"
|
|
39
|
+
},
|
|
40
|
+
"repository": {
|
|
41
|
+
"type": "git",
|
|
42
|
+
"url": "git+https://github.com/zigordev/toolkit.git",
|
|
43
|
+
"directory": "packages/test"
|
|
44
|
+
},
|
|
45
|
+
"scripts": {
|
|
46
|
+
"build": "tsc -p tsconfig.build.json",
|
|
47
|
+
"typecheck": "tsc -p tsconfig.json"
|
|
48
|
+
}
|
|
6
49
|
}
|