vitecompose 0.1.2 → 0.3.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.
Files changed (3) hide show
  1. package/README.md +176 -37
  2. package/dist/index.mjs +9 -4
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -4,24 +4,18 @@
4
4
 
5
5
  Sister project to [vitekube](https://github.com/vitekube/vitekube), built for multi-container Docker Compose stacks without needing Kubernetes.
6
6
 
7
- Write a normal Vitest test. Run it against a real Compose stack. Rerun it, and only the images and stages you changed run again.
7
+ Write a normal Vitest test. Run it against a real Compose stack. Rerun it, and the stack is already up: only the images and stages you changed run again.
8
8
 
9
9
  ```ts
10
10
  import { test } from "vitecompose";
11
11
  import { expect } from "vitest";
12
12
 
13
- test("the web server answers and survives a restart", async ({ compose, evidence }) => {
14
- evidence.watchServices(["web"]);
15
-
13
+ test("the web server answers", async ({ compose }) => {
14
+ // Waits until the service answers 2xx, then returns its URL on the host's randomly assigned port.
16
15
  const url = await compose.waitForHttp("web", 80);
16
+
17
17
  expect((await fetch(url)).status).toBe(200);
18
18
  expect(await compose.inspect("web")).toBeContainerHealthy();
19
-
20
- await using outage = await compose.stopTemporarily("web");
21
- expect(await compose.inspect("web")).toHaveContainerState("exited");
22
- await outage.restore();
23
-
24
- expect((await fetch(await compose.url("web", 80))).status).toBe(200);
25
19
  });
26
20
  ```
27
21
 
@@ -35,15 +29,9 @@ test("the web server answers and survives a restart", async ({ compose, evidence
35
29
  | Rebuilding everything for a small edit | Content-hashed `stages` skip unchanged dependencies and seeds. |
36
30
  | Port collisions across parallel worktrees | Publish `"0:<port>"` and resolve dynamically with `compose.url(service, port)`. |
37
31
  | Rerunning everything to check one test | `npx vitest run -t "exact test name"`. It's still just Vitest. |
38
- | Digging for logs after teardown deleted them | Container summaries and logs print right next to the failure. |
32
+ | Digging for logs after teardown deleted them | Container states and logs print right next to the failure. |
39
33
  | Maintaining brittle shell runners | Declare your Compose stack, images and stages once in TypeScript. |
40
34
 
41
- And it is careful with everything else:
42
-
43
- - **It won't harm a stack it doesn't own.** Every managed service is stamped with `com.vitecompose.managed=true`. Pre-existing Compose projects without that label are refused.
44
- - **No concurrent collisions.** A lock with heartbeat and PID liveness prevents two runs from stepping on the same project. Use `VITECOMPOSE_PROJECT=<worktree>` to run stacks side by side.
45
- - **Secrets stay out of failure output.** `evidence.markSensitive(secret)` strips raw, base64 and JSON-escaped forms from all captured output; `evidence.restrict()` drops log sections altogether.
46
-
47
35
  ## Quick start
48
36
 
49
37
  You need [Docker](https://docs.docker.com/get-docker/) (with Docker Compose v2+), Vitest 5 and Node `^22.18`, `^24.11` or `>=26`.
@@ -52,21 +40,47 @@ You need [Docker](https://docs.docker.com/get-docker/) (with Docker Compose v2+)
52
40
  npm install --save-dev vitest vitecompose
53
41
  ```
54
42
 
55
- **1. Configure your stack** in `compose.setup.ts`:
43
+ You'll add four files. A complete copy lives in [`examples/quick-start`](examples/quick-start).
44
+
45
+ ### 1. A Compose file
46
+
47
+ Use your existing one, or start with this `docker-compose.yaml`:
48
+
49
+ ```yaml
50
+ services:
51
+ web:
52
+ image: nginx:1.29-alpine
53
+ ports:
54
+ - "0:80" # 0 = let Docker pick a free host port; tests look it up
55
+ healthcheck:
56
+ test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:80/ >/dev/null 2>&1 || exit 1"]
57
+ interval: 2s
58
+ retries: 15
59
+ ```
60
+
61
+ Publishing on host port `0` means two runs (or two worktrees) never fight over a port. Tests find the real port with `compose.url("web", 80)` or `compose.port("web", 80)`.
62
+
63
+ ### 2. Tell vitecompose about the stack
64
+
65
+ `compose.setup.ts`:
56
66
 
57
67
  ```ts
58
68
  import { defineComposeGlobalSetup } from "vitecompose/node";
59
69
 
60
70
  export default defineComposeGlobalSetup({
61
71
  stack: {
62
- name: "my-app-tests",
72
+ name: "my-app-tests", // the Compose project name
63
73
  composeFile: "./docker-compose.yaml",
64
- reuse: true,
74
+ reuse: true, // keep the stack running between runs
65
75
  },
66
76
  });
67
77
  ```
68
78
 
69
- **2. Connect it to Vitest** in `vitest.config.ts`:
79
+ Before the tests run, this starts the stack with `docker compose up` and waits for healthchecks to pass. With `reuse: true` the stack stays up afterwards, so the next run starts in under a second. Without it, every run gets a fresh stack that is deleted when the run ends.
80
+
81
+ ### 3. Connect it to Vitest
82
+
83
+ `vitest.config.ts`:
70
84
 
71
85
  ```ts
72
86
  import { ComposeReporter } from "vitecompose/node";
@@ -74,18 +88,95 @@ import { defineConfig } from "vitest/config";
74
88
 
75
89
  export default defineConfig({
76
90
  test: {
77
- globalSetup: ["./compose.setup.ts"],
78
- reporters: [new ComposeReporter()],
79
- fileParallelism: false,
80
- testTimeout: 120_000,
91
+ globalSetup: ["./compose.setup.ts"], // starts the stack before any test
92
+ reporters: [new ComposeReporter()], // optional: readable durations, fails a `-t` that matches nothing
93
+ fileParallelism: false, // test files share one stack, so run them one at a time
94
+ testTimeout: 120_000, // containers are slower than functions
81
95
  teardownTimeout: 60_000,
82
96
  },
83
97
  });
84
98
  ```
85
99
 
86
- **3. Write your tests** with `test` from `"vitecompose"`, and compose domain fixtures with `.extend(...)`:
100
+ ### 4. Write a test
101
+
102
+ `web.test.ts`:
103
+
104
+ ```ts
105
+ import { test } from "vitecompose"; // Vitest's `test`, plus Compose fixtures
106
+ import { expect } from "vitest";
107
+
108
+ test("the web server answers", async ({ compose }) => {
109
+ const url = await compose.waitForHttp("web", 80);
110
+ expect((await fetch(url)).status).toBe(200);
111
+ });
112
+ ```
113
+
114
+ ### 5. Run it
115
+
116
+ ```sh
117
+ npx vitest run
118
+ ```
119
+
120
+ ```text
121
+ [vitecompose] starting Compose stack my-app-tests
122
+ [vitecompose] stack my-app-tests ready in 2.8s
123
+ [vitecompose] inspect the stack with: docker compose -p my-app-tests ps
124
+ ✓ web.test.ts (1 test)
125
+ ✓ the web server answers
126
+ ```
127
+
128
+ Run it again and the stack is reused:
129
+
130
+ ```text
131
+ [vitecompose] reusing Compose stack my-app-tests
132
+ [vitecompose] stack my-app-tests ready in 595ms
133
+ ```
134
+
135
+ ## When a test fails: `evidence`
136
+
137
+ By default a failing test shows only Vitest's usual assertion error. By then you usually want to know what the containers were doing, and the stack may be torn down before you can look.
138
+
139
+ `evidence.watchServices([...])` fixes that. It means: **if this test fails, print these services' container state and their last 100 log lines next to the failure.** On a passing test it does nothing, and costs nothing.
140
+
141
+ ```ts
142
+ test("missing pages return 404", async ({ compose, evidence }) => {
143
+ evidence.watchServices(["web"]); // only used if the test fails
144
+
145
+ const res = await fetch(await compose.url("web", 80, { path: "/missing" }));
146
+ expect(res.status).toBe(200); // oops
147
+ });
148
+ ```
149
+
150
+ ```text
151
+ --- containers for web
152
+ web/my-app-tests-web-1 {"name":"my-app-tests-web-1","service":"web","state":"running","status":"Up 2 seconds (healthy)","health":"healthy"}
153
+ --- logs for web
154
+ web:
155
+ ...
156
+ 192.168.148.1 - - [27/Nov/2026:21:56:29 +0000] "GET /missing HTTP/1.1" 404 153 "-" "node" "-"
157
+ 2026/11/27 21:56:29 [error] 29#29: *2 open() "/usr/share/nginx/html/missing" failed (2: No such file or directory)
158
+
159
+ FAIL web.test.ts > missing pages return 404
160
+ AssertionError: expected 404 to be 200
161
+ ```
162
+
163
+ The output is collected right after the test fails, before any fixture cleanup, so you see the state that caused the failure.
164
+
165
+ | Call | What it does |
166
+ | ------------------------------------------------- | --------------------------------------------------------------------------------- |
167
+ | `evidence.watchServices(["api", "db"])` | On failure, print state and logs for these services |
168
+ | `evidence.watchServices()` | Same, for every container in the stack |
169
+ | `evidence.watchServices({ services, tailLines })` | Choose how many log lines to keep (default 100) |
170
+ | `evidence.add(title, async () => text)` | On failure, also print anything else you can collect (a DB row, an API response) |
171
+ | `evidence.markSensitive(secret)` | Replace this value with `***` everywhere, including base64 and JSON-escaped forms |
172
+ | `evidence.restrict()` | Drop logs entirely for this test, keeping only container state |
173
+
174
+ ## Reusable fixtures
175
+
176
+ When several tests need the same setup, wrap it in a fixture with `.extend(...)`. It's Vitest's own [test context](https://vitest.dev/guide/test-context) mechanism:
87
177
 
88
178
  ```ts
179
+ // fixtures.ts
89
180
  import { test as base } from "vitecompose";
90
181
 
91
182
  export const test = base.extend("api", async ({ compose, evidence }) => {
@@ -97,26 +188,63 @@ export const test = base.extend("api", async ({ compose, evidence }) => {
97
188
  });
98
189
  ```
99
190
 
100
- ## What `test` gives you
191
+ ```ts
192
+ // users.test.ts
193
+ import { expect } from "vitest";
194
+ import { test } from "./fixtures.ts";
195
+
196
+ test("lists users", async ({ api }) => {
197
+ const res = await api.get("/users");
198
+ expect(res.status).toBe(200);
199
+ });
200
+ ```
101
201
 
102
- | Fixture | What it gives you |
103
- | ------------------- | ------------------------------------------------------------------------------------------------ |
104
- | `compose` | A Compose client for this stack, canceled when the test times out |
105
- | `fileCompose` | An unsignaled client shared by a whole file, for file-scoped fixtures and cleanup |
106
- | `scope` | Cleanup functions run in reverse order, each with its own timeout |
107
- | `evidence` | Failure-time container summaries, logs (`watchServices`), custom collectors and secret redaction |
108
- | `markStackUnusable` | Stops later tests with a reason when shared state could not be restored |
202
+ Every test that uses `api` now waits for the API to be ready and prints the API and database logs if it fails.
203
+
204
+ ## Simulating outages
205
+
206
+ `stopTemporarily` and `pauseTemporarily` take a service down and bring it back when the block ends, even if an assertion throws. Restoring waits for the service to be healthy again (or just running, if it has no healthcheck), so the next test gets a working stack.
207
+
208
+ ```ts
209
+ test("the web server survives a restart", async ({ compose }) => {
210
+ {
211
+ await using outage = await compose.stopTemporarily("web"); // or { kill: true } for SIGKILL
212
+ expect(await compose.inspect("web")).toHaveContainerState("exited");
213
+ } // restored here
214
+
215
+ expect((await fetch(await compose.url("web", 80))).status).toBe(200);
216
+ });
217
+ ```
218
+
219
+ Call `await outage.restore()` to bring it back earlier. If a restore fails, the stack is marked unusable and the remaining tests stop with that reason instead of failing in confusing ways.
220
+
221
+ ## Reference
222
+
223
+ ### Test fixtures
224
+
225
+ Everything `test` from `"vitecompose"` adds to the test context:
226
+
227
+ | Fixture | What it gives you |
228
+ | ------------------- | ------------------------------------------------------------------------------------------------------ |
229
+ | `compose` | A Compose client for this stack. Its commands and waits are canceled when the test times out |
230
+ | `evidence` | Extra output printed when the test fails (see [above](#when-a-test-fails-evidence)) |
231
+ | `scope` | `scope.defer(fn)` registers cleanup, run in reverse order after the test, each with its own timeout |
232
+ | `fileCompose` | A Compose client shared by the whole file and not tied to one test, for file-scoped fixtures |
233
+ | `markStackUnusable` | `markStackUnusable(reason)` stops later tests when your test changed shared state and couldn't undo it |
109
234
 
110
235
  ### The `compose` client
111
236
 
112
237
  - **Lifecycle:** `up`, `down`, `start`, `stop`, `kill`, `restart`, `pause`, `unpause`
113
238
  - **Inspect & connect:** `ps`, `inspect`, `port`, `url`, `exec`, `run`, `logs`
114
239
  - **Waits:** `waitForRunning`, `waitForHealthy`, `waitForStopped`, `waitForExit`, `waitForLogs`, `waitForHttp`
115
- - **Outage simulation (`await using`):** `stopTemporarily(service, { kill?: boolean })`, `pauseTemporarily(service)`
240
+ - **Outages:** `stopTemporarily(service, { kill? })`, `pauseTemporarily(service)`
116
241
 
117
242
  ### Matchers
118
243
 
244
+ Registered automatically when you import `test` from `"vitecompose"`. They take the container returned by `compose.inspect(service)`:
245
+
119
246
  ```ts
247
+ const container = await compose.inspect("web");
120
248
  expect(container).toBeContainerRunning();
121
249
  expect(container).toBeContainerHealthy();
122
250
  expect(container).toHaveContainerState("exited");
@@ -125,7 +253,7 @@ expect(container).toHaveExitedWith(0);
125
253
 
126
254
  ## Staged environments
127
255
 
128
- For multi-service systems with custom images, migrations or seed scripts, declare `environment` in `compose.setup.ts`:
256
+ Real stacks need more than `docker compose up`: images to build, migrations to run, data to seed. Declare those as `environment` in `compose.setup.ts` and vitecompose remembers what it did last time:
129
257
 
130
258
  ```ts
131
259
  export default defineComposeGlobalSetup({
@@ -133,7 +261,9 @@ export default defineComposeGlobalSetup({
133
261
  environment: {
134
262
  images: [{ name: "my-api", dockerfile: "api/Dockerfile", context: "." }],
135
263
  stages: [
264
+ // Start postgres and wait for it to be healthy.
136
265
  { name: "db", services: ["postgres"], waitFor: ["postgres"] },
266
+ // Run your own code. Reruns only when a file matching `inputs` changes.
137
267
  {
138
268
  name: "migrations",
139
269
  dependsOn: ["db"],
@@ -143,13 +273,14 @@ export default defineComposeGlobalSetup({
143
273
  await migrate(`postgres://postgres:postgres@${host}:${port}/app`);
144
274
  },
145
275
  },
276
+ // Rebuild and restart the API only when its image changed.
146
277
  { name: "api", dependsOn: ["migrations"], images: ["my-api"], services: ["api"], waitFor: ["api"] },
147
278
  ],
148
279
  },
149
280
  });
150
281
  ```
151
282
 
152
- A stage reruns only when its images, Compose files, `inputs`, or an upstream dependency changed.
283
+ A stage reruns only when its images, Compose files, `inputs`, or an upstream stage changed. Edit a migration and only `migrations` and `api` rerun; edit a test and nothing does. See [`examples/environment`](examples/environment).
153
284
 
154
285
  ## Commands
155
286
 
@@ -161,6 +292,14 @@ A stage reruns only when its images, Compose files, `inputs`, or an upstream dep
161
292
  | `VITECOMPOSE_PROJECT=wt-1 npx vitest run` | Run against an isolated Compose project (e.g. per worktree) |
162
293
  | `VITECOMPOSE_KEEP_ON_FAILURE=1 npx vitest run` | Keep a fresh stack running after a failure for inspection |
163
294
 
295
+ To remove a reused stack: `docker compose -p my-app-tests down -v`.
296
+
297
+ ## Safety
298
+
299
+ - **It won't touch a stack it doesn't own.** Every managed service is labeled `com.vitecompose.managed=true`. If a Compose project with the same name exists without that label, vitecompose refuses to use it.
300
+ - **Two runs can't collide.** A lock with heartbeat and PID liveness stops two runs from using the same project at once. Set `VITECOMPOSE_PROJECT=<name>` to run stacks side by side.
301
+ - **Secrets stay out of failure output**, with `evidence.markSensitive` and `evidence.restrict` (see [above](#when-a-test-fails-evidence)).
302
+
164
303
  ## Development
165
304
 
166
305
  ```sh
package/dist/index.mjs CHANGED
@@ -112,13 +112,18 @@ expect.extend({
112
112
  toHaveContainerState,
113
113
  toHaveExitedWith
114
114
  });
115
- /** Reports a forgotten setup clearly, instead of a TypeError from the Compose client. */
115
+ /** Reports a forgotten (or never loaded) setup clearly, instead of a TypeError from deeper inside. */
116
+ const missingSetupError = () => /* @__PURE__ */ new Error("No Compose stack: add a file that exports defineComposeGlobalSetup() to `globalSetup` in your Vitest config. If it is already there, check that Vitest loaded that config: run it from the config's directory or pass `--config`.");
116
117
  const stackTarget = () => {
117
118
  const target = inject("vitecomposeTarget");
118
- if (!target) throw new Error("No Compose stack: add a file that exports defineComposeGlobalSetup() to `globalSetup` in your Vitest config.");
119
+ if (!target) throw missingSetupError();
119
120
  return target;
120
121
  };
121
- const stateStore = () => createStackStateStore(inject("vitecomposeStateDir"));
122
+ const stateStore = () => {
123
+ const stateDir = inject("vitecomposeStateDir");
124
+ if (!stateDir) throw missingSetupError();
125
+ return createStackStateStore(stateDir);
126
+ };
122
127
  const test = test$1.extend("environmentGuard", { auto: true }, async () => {
123
128
  const state = await stateStore().read();
124
129
  if (state?.unusable) throw new Error(`The Compose stack is marked unusable: ${state.unusable}`);
@@ -134,7 +139,7 @@ const test = test$1.extend("environmentGuard", { auto: true }, async () => {
134
139
  onCleanup(() => scope.dispose());
135
140
  return scope;
136
141
  }).extend("evidence", ({ fileCompose }) => createEvidence(fileCompose)).extend("markStackUnusable", () => (reason) => stateStore().markUnusable(reason));
137
- test.afterEach(async ({ task, evidence }) => {
142
+ if (inject("vitecomposeStateDir") && inject("vitecomposeTarget")) test.afterEach(async ({ task, evidence }) => {
138
143
  if (task.result?.state === "fail") {
139
144
  await stateStore().markFailed().catch(() => {});
140
145
  const output = await evidence.capture();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vitecompose",
3
- "version": "0.1.2",
3
+ "version": "0.3.0",
4
4
  "description": "Vitest on real Docker Compose stacks. Write integration tests that feel like unit tests.",
5
5
  "keywords": [
6
6
  "docker",