vitecompose 0.0.0-stage → 0.1.2
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/LICENSE +21 -0
- package/README.md +180 -2
- package/dist/core/index.d.mts +4 -0
- package/dist/core/index.mjs +3 -0
- package/dist/duration-BRZrZK6s.mjs +13 -0
- package/dist/index.d.mts +62 -0
- package/dist/index.mjs +144 -0
- package/dist/node.d.mts +108 -0
- package/dist/node.mjs +587 -0
- package/dist/provided-CnoC64M0.d.mts +8 -0
- package/dist/scope-B1yisv2y.d.mts +292 -0
- package/dist/scope-BT1dmBGo.mjs +670 -0
- package/dist/state-B-aMt5sE.mjs +152 -0
- package/package.json +51 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dragan Bajcic
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,181 @@
|
|
|
1
|
-
#
|
|
1
|
+
# vitecompose
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Real Docker Compose tests that feel like unit tests.**
|
|
4
|
+
|
|
5
|
+
Sister project to [vitekube](https://github.com/vitekube/vitekube), built for multi-container Docker Compose stacks without needing Kubernetes.
|
|
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.
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { test } from "vitecompose";
|
|
11
|
+
import { expect } from "vitest";
|
|
12
|
+
|
|
13
|
+
test("the web server answers and survives a restart", async ({ compose, evidence }) => {
|
|
14
|
+
evidence.watchServices(["web"]);
|
|
15
|
+
|
|
16
|
+
const url = await compose.waitForHttp("web", 80);
|
|
17
|
+
expect((await fetch(url)).status).toBe(200);
|
|
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
|
+
});
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
> **Status:** early. A community project, not affiliated with Vitest, Vite, or Docker.
|
|
29
|
+
|
|
30
|
+
## Why you'll like it
|
|
31
|
+
|
|
32
|
+
| Time sink | With vitecompose |
|
|
33
|
+
| -------------------------------------------- | ------------------------------------------------------------------------------- |
|
|
34
|
+
| Recreating the stack on every run | Set `reuse: true`. The next run starts straight away. |
|
|
35
|
+
| Rebuilding everything for a small edit | Content-hashed `stages` skip unchanged dependencies and seeds. |
|
|
36
|
+
| Port collisions across parallel worktrees | Publish `"0:<port>"` and resolve dynamically with `compose.url(service, port)`. |
|
|
37
|
+
| 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. |
|
|
39
|
+
| Maintaining brittle shell runners | Declare your Compose stack, images and stages once in TypeScript. |
|
|
40
|
+
|
|
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
|
+
## Quick start
|
|
48
|
+
|
|
49
|
+
You need [Docker](https://docs.docker.com/get-docker/) (with Docker Compose v2+), Vitest 5 and Node `^22.18`, `^24.11` or `>=26`.
|
|
50
|
+
|
|
51
|
+
```sh
|
|
52
|
+
npm install --save-dev vitest vitecompose
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
**1. Configure your stack** in `compose.setup.ts`:
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
import { defineComposeGlobalSetup } from "vitecompose/node";
|
|
59
|
+
|
|
60
|
+
export default defineComposeGlobalSetup({
|
|
61
|
+
stack: {
|
|
62
|
+
name: "my-app-tests",
|
|
63
|
+
composeFile: "./docker-compose.yaml",
|
|
64
|
+
reuse: true,
|
|
65
|
+
},
|
|
66
|
+
});
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
**2. Connect it to Vitest** in `vitest.config.ts`:
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
import { ComposeReporter } from "vitecompose/node";
|
|
73
|
+
import { defineConfig } from "vitest/config";
|
|
74
|
+
|
|
75
|
+
export default defineConfig({
|
|
76
|
+
test: {
|
|
77
|
+
globalSetup: ["./compose.setup.ts"],
|
|
78
|
+
reporters: [new ComposeReporter()],
|
|
79
|
+
fileParallelism: false,
|
|
80
|
+
testTimeout: 120_000,
|
|
81
|
+
teardownTimeout: 60_000,
|
|
82
|
+
},
|
|
83
|
+
});
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
**3. Write your tests** with `test` from `"vitecompose"`, and compose domain fixtures with `.extend(...)`:
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
import { test as base } from "vitecompose";
|
|
90
|
+
|
|
91
|
+
export const test = base.extend("api", async ({ compose, evidence }) => {
|
|
92
|
+
evidence.watchServices(["api", "db"]);
|
|
93
|
+
const baseUrl = await compose.waitForHttp("api", 8080, { path: "/health" });
|
|
94
|
+
return {
|
|
95
|
+
get: (path: string) => fetch(new URL(path, baseUrl)),
|
|
96
|
+
};
|
|
97
|
+
});
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
## What `test` gives you
|
|
101
|
+
|
|
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 |
|
|
109
|
+
|
|
110
|
+
### The `compose` client
|
|
111
|
+
|
|
112
|
+
- **Lifecycle:** `up`, `down`, `start`, `stop`, `kill`, `restart`, `pause`, `unpause`
|
|
113
|
+
- **Inspect & connect:** `ps`, `inspect`, `port`, `url`, `exec`, `run`, `logs`
|
|
114
|
+
- **Waits:** `waitForRunning`, `waitForHealthy`, `waitForStopped`, `waitForExit`, `waitForLogs`, `waitForHttp`
|
|
115
|
+
- **Outage simulation (`await using`):** `stopTemporarily(service, { kill?: boolean })`, `pauseTemporarily(service)`
|
|
116
|
+
|
|
117
|
+
### Matchers
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
expect(container).toBeContainerRunning();
|
|
121
|
+
expect(container).toBeContainerHealthy();
|
|
122
|
+
expect(container).toHaveContainerState("exited");
|
|
123
|
+
expect(container).toHaveExitedWith(0);
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
## Staged environments
|
|
127
|
+
|
|
128
|
+
For multi-service systems with custom images, migrations or seed scripts, declare `environment` in `compose.setup.ts`:
|
|
129
|
+
|
|
130
|
+
```ts
|
|
131
|
+
export default defineComposeGlobalSetup({
|
|
132
|
+
stack: { name: "my-app-tests", composeFile: "./docker-compose.yaml", reuse: true },
|
|
133
|
+
environment: {
|
|
134
|
+
images: [{ name: "my-api", dockerfile: "api/Dockerfile", context: "." }],
|
|
135
|
+
stages: [
|
|
136
|
+
{ name: "db", services: ["postgres"], waitFor: ["postgres"] },
|
|
137
|
+
{
|
|
138
|
+
name: "migrations",
|
|
139
|
+
dependsOn: ["db"],
|
|
140
|
+
inputs: ["db/migrations/**"],
|
|
141
|
+
run: async ({ compose }) => {
|
|
142
|
+
const { host, port } = await compose.port("postgres", 5432);
|
|
143
|
+
await migrate(`postgres://postgres:postgres@${host}:${port}/app`);
|
|
144
|
+
},
|
|
145
|
+
},
|
|
146
|
+
{ name: "api", dependsOn: ["migrations"], images: ["my-api"], services: ["api"], waitFor: ["api"] },
|
|
147
|
+
],
|
|
148
|
+
},
|
|
149
|
+
});
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
A stage reruns only when its images, Compose files, `inputs`, or an upstream dependency changed.
|
|
153
|
+
|
|
154
|
+
## Commands
|
|
155
|
+
|
|
156
|
+
| Command | What it does |
|
|
157
|
+
| ---------------------------------------------- | ----------------------------------------------------------- |
|
|
158
|
+
| `npx vitest run` | Run all tests, reusing the stack when `reuse: true` |
|
|
159
|
+
| `npx vitest run -t "name"` | Run matching tests (fails if nothing matches) |
|
|
160
|
+
| `VITECOMPOSE_REBUILD=1 npx vitest run` | Force rebuild of all images and stages |
|
|
161
|
+
| `VITECOMPOSE_PROJECT=wt-1 npx vitest run` | Run against an isolated Compose project (e.g. per worktree) |
|
|
162
|
+
| `VITECOMPOSE_KEEP_ON_FAILURE=1 npx vitest run` | Keep a fresh stack running after a failure for inspection |
|
|
163
|
+
|
|
164
|
+
## Development
|
|
165
|
+
|
|
166
|
+
```sh
|
|
167
|
+
vp install
|
|
168
|
+
vp pack
|
|
169
|
+
vp check
|
|
170
|
+
vp test
|
|
171
|
+
pnpm run e2e # contract tests (requires Docker)
|
|
172
|
+
pnpm run e2e:smoke # quick-start example (requires Docker)
|
|
173
|
+
pnpm run e2e:environment # staged environment example (requires Docker)
|
|
174
|
+
pnpm run e2e:all # full contract suite + all examples
|
|
175
|
+
pnpm run e2e:tarball # packed tarball install & run outside workspace
|
|
176
|
+
pnpm run e2e:clean # remove stacks created by this repo's tests
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
## License
|
|
180
|
+
|
|
181
|
+
[MIT](LICENSE)
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { A as waitFor, B as runChecked, C as createComposeClient, D as WaitForOptions, E as summarizeContainer, F as CommandTimeoutError, I as RunOptions, L as RunResult, M as CommandCanceledError, N as CommandFailedError, O as WaitOptions, P as CommandStartError, R as killOwnedChildren, S as composeBaseArgs, T as parseComposePsJson, V as startBackground, _ as ContainerHealthName, a as withScope, b as StopTemporarilyOptions, c as ComposeContainer, d as ComposeExecOptions, f as ComposeLogsOptions, g as ComposeUpOptions, h as ComposeTarget, i as createScope, j as BackgroundProcess, k as WaitTimeoutError, l as ComposeContainerSummary, m as ComposeRunOptions, n as DisposalError, o as ComposeClient, p as ComposePublisher, r as Scope, s as ComposeClientOptions, t as DeferOptions, u as ComposeDownOptions, v as ContainerStateName, w as parseComposePort, x as TemporaryOutage, y as PauseTemporarilyOptions, z as run } from "../scope-B1yisv2y.mjs";
|
|
2
|
+
/** `450ms`, `38.2s`, `4m 6s`, `1h 2m 3s`. Rounds first, so 59,999ms reads `1m 0s` and never `60.0s`. */
|
|
3
|
+
export declare const formatDuration: (milliseconds: number) => string;
|
|
4
|
+
export { BackgroundProcess, CommandCanceledError, CommandFailedError, CommandStartError, CommandTimeoutError, ComposeClient, ComposeClientOptions, ComposeContainer, ComposeContainerSummary, ComposeDownOptions, ComposeExecOptions, ComposeLogsOptions, ComposePublisher, ComposeRunOptions, ComposeTarget, ComposeUpOptions, ContainerHealthName, ContainerStateName, DeferOptions, DisposalError, PauseTemporarilyOptions, RunOptions, RunResult, Scope, StopTemporarilyOptions, TemporaryOutage, WaitForOptions, WaitOptions, WaitTimeoutError, composeBaseArgs, createComposeClient, createScope, killOwnedChildren, parseComposePort, parseComposePsJson, run, runChecked, startBackground, summarizeContainer, waitFor, withScope };
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { _ as runChecked, a as createComposeClient, c as summarizeContainer, d as CommandCanceledError, f as CommandFailedError, g as run, h as killOwnedChildren, i as composeBaseArgs, l as WaitTimeoutError, m as CommandTimeoutError, n as createScope, o as parseComposePort, p as CommandStartError, r as withScope, s as parseComposePsJson, t as DisposalError, u as waitFor, v as startBackground } from "../scope-BT1dmBGo.mjs";
|
|
2
|
+
import { t as formatDuration } from "../duration-BRZrZK6s.mjs";
|
|
3
|
+
export { CommandCanceledError, CommandFailedError, CommandStartError, CommandTimeoutError, DisposalError, WaitTimeoutError, composeBaseArgs, createComposeClient, createScope, formatDuration, killOwnedChildren, parseComposePort, parseComposePsJson, run, runChecked, startBackground, summarizeContainer, waitFor, withScope };
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// src/core/duration.ts
|
|
2
|
+
/** `450ms`, `38.2s`, `4m 6s`, `1h 2m 3s`. Rounds first, so 59,999ms reads `1m 0s` and never `60.0s`. */
|
|
3
|
+
const formatDuration = (milliseconds) => {
|
|
4
|
+
if (milliseconds < 999.5) return `${Math.round(milliseconds)}ms`;
|
|
5
|
+
const tenths = Math.round(milliseconds / 100);
|
|
6
|
+
if (tenths < 600) return `${(tenths / 10).toFixed(1)}s`;
|
|
7
|
+
const totalSeconds = Math.round(milliseconds / 1e3);
|
|
8
|
+
const hours = Math.floor(totalSeconds / 3600);
|
|
9
|
+
const minutes = Math.floor(totalSeconds % 3600 / 60);
|
|
10
|
+
const seconds = totalSeconds % 60;
|
|
11
|
+
return hours > 0 ? `${hours}h ${minutes}m ${seconds}s` : `${minutes}m ${seconds}s`;
|
|
12
|
+
};
|
|
13
|
+
export { formatDuration as t };
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { o as ComposeClient, r as Scope, v as ContainerStateName } from "./scope-B1yisv2y.mjs";
|
|
2
|
+
import "./provided-CnoC64M0.mjs";
|
|
3
|
+
type ServiceEvidenceOptions = {
|
|
4
|
+
/** Compose services to inspect. When omitted, collects every container in the stack. */
|
|
5
|
+
services?: readonly string[];
|
|
6
|
+
/** Lines per service log. Defaults to 100. */
|
|
7
|
+
tailLines?: number;
|
|
8
|
+
};
|
|
9
|
+
type EvidenceSectionOptions = {
|
|
10
|
+
/** Output that can contain application data, such as logs. Dropped when the test is restricted. */
|
|
11
|
+
mayContainSensitiveData?: boolean;
|
|
12
|
+
};
|
|
13
|
+
type Evidence = {
|
|
14
|
+
/** Removes this value from everything captured, including its base64 and JSON-escaped forms. */
|
|
15
|
+
markSensitive: (value: string) => void;
|
|
16
|
+
/**
|
|
17
|
+
* Captures only metadata for this test. For tests whose secrets could appear in a form `markSensitive`
|
|
18
|
+
* cannot recognize, such as a value split across log lines.
|
|
19
|
+
*/
|
|
20
|
+
restrict: () => void;
|
|
21
|
+
/** Registers something to collect if the test fails. Register as soon as the thing to inspect is known. */
|
|
22
|
+
add: (title: string, collect: () => Promise<string>, options?: EvidenceSectionOptions) => void;
|
|
23
|
+
/** Collects container summaries and service logs on failure. */
|
|
24
|
+
watchServices: (services?: readonly string[] | ServiceEvidenceOptions) => void;
|
|
25
|
+
/** Runs every collector. A failing collector reports its failure and never hides the test's own. */
|
|
26
|
+
capture: () => Promise<string>;
|
|
27
|
+
};
|
|
28
|
+
type ComposeMatchers<R = unknown> = {
|
|
29
|
+
toBeContainerRunning: () => R;
|
|
30
|
+
toBeContainerHealthy: () => R;
|
|
31
|
+
toHaveContainerState: (state: ContainerStateName) => R;
|
|
32
|
+
toHaveExitedWith: (code: number) => R;
|
|
33
|
+
};
|
|
34
|
+
declare module "vitest" {
|
|
35
|
+
interface Matchers<R, T> extends ComposeMatchers<R> {}
|
|
36
|
+
}
|
|
37
|
+
export declare const test: import("vitest").TestAPI<Omit<Omit<Omit<Omit<Omit<Omit<object, "$__test"> & Record<"environmentGuard", void> & {
|
|
38
|
+
readonly $__worker?: object | undefined;
|
|
39
|
+
readonly $__file?: object | undefined;
|
|
40
|
+
readonly $__test?: (object & Record<"environmentGuard", void>) | undefined;
|
|
41
|
+
}, "$__file"> & Record<"fileCompose", ComposeClient> & {
|
|
42
|
+
readonly $__worker?: object | undefined;
|
|
43
|
+
readonly $__file?: (object & Record<"fileCompose", ComposeClient>) | undefined;
|
|
44
|
+
readonly $__test?: (object & Record<"environmentGuard", void>) | undefined;
|
|
45
|
+
}, "$__test"> & Record<"compose", ComposeClient> & {
|
|
46
|
+
readonly $__worker?: object | undefined;
|
|
47
|
+
readonly $__file?: (object & Record<"fileCompose", ComposeClient>) | undefined;
|
|
48
|
+
readonly $__test?: (object & Record<"environmentGuard", void> & Record<"compose", ComposeClient>) | undefined;
|
|
49
|
+
}, "$__test"> & Record<"scope", Scope> & {
|
|
50
|
+
readonly $__worker?: object | undefined;
|
|
51
|
+
readonly $__file?: (object & Record<"fileCompose", ComposeClient>) | undefined;
|
|
52
|
+
readonly $__test?: (object & Record<"environmentGuard", void> & Record<"compose", ComposeClient> & Record<"scope", Scope>) | undefined;
|
|
53
|
+
}, "$__test"> & Record<"evidence", Evidence> & {
|
|
54
|
+
readonly $__worker?: object | undefined;
|
|
55
|
+
readonly $__file?: (object & Record<"fileCompose", ComposeClient>) | undefined;
|
|
56
|
+
readonly $__test?: (object & Record<"environmentGuard", void> & Record<"compose", ComposeClient> & Record<"scope", Scope> & Record<"evidence", Evidence>) | undefined;
|
|
57
|
+
}, "$__test"> & Record<"markStackUnusable", (reason: string) => Promise<void>> & {
|
|
58
|
+
readonly $__worker?: object | undefined;
|
|
59
|
+
readonly $__file?: (object & Record<"fileCompose", ComposeClient>) | undefined;
|
|
60
|
+
readonly $__test?: (object & Record<"environmentGuard", void> & Record<"compose", ComposeClient> & Record<"scope", Scope> & Record<"evidence", Evidence> & Record<"markStackUnusable", (reason: string) => Promise<void>>) | undefined;
|
|
61
|
+
}>;
|
|
62
|
+
export type { Evidence, EvidenceSectionOptions, ServiceEvidenceOptions };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { a as createComposeClient, c as summarizeContainer, n as createScope } from "./scope-BT1dmBGo.mjs";
|
|
2
|
+
import { t as createStackStateStore } from "./state-B-aMt5sE.mjs";
|
|
3
|
+
import { expect, inject, test as test$1 } from "vitest";
|
|
4
|
+
// src/vitest/service-evidence.ts
|
|
5
|
+
/** Registers lazy collectors, so they inspect the failed state before fixture cleanup. */
|
|
6
|
+
const addServiceEvidence = (evidence, client, options = {}) => {
|
|
7
|
+
const { services, tailLines = 100 } = options;
|
|
8
|
+
const description = services && services.length > 0 ? `for ${services.join(", ")}` : "in stack";
|
|
9
|
+
const containers = () => client.ps({
|
|
10
|
+
services,
|
|
11
|
+
all: true
|
|
12
|
+
});
|
|
13
|
+
evidence.add(`containers ${description}`, async () => {
|
|
14
|
+
const list = await containers();
|
|
15
|
+
if (list.length === 0) return "(no containers)";
|
|
16
|
+
return list.map((container) => `${container.service}/${container.name} ${JSON.stringify(summarizeContainer(container))}`).join("\n");
|
|
17
|
+
});
|
|
18
|
+
evidence.add(`logs ${description}`, async () => {
|
|
19
|
+
const targetServices = services && services.length > 0 ? [...services] : [...new Set((await containers()).map((c) => c.service))];
|
|
20
|
+
if (targetServices.length === 0) return "(no services)";
|
|
21
|
+
return (await Promise.all(targetServices.map(async (service) => {
|
|
22
|
+
return `${service}:\n${await client.logs(service, { tailLines }).catch((error) => `could not read: ${String(error)}`)}`;
|
|
23
|
+
}))).join("\n");
|
|
24
|
+
}, { mayContainSensitiveData: true });
|
|
25
|
+
};
|
|
26
|
+
// src/vitest/evidence.ts
|
|
27
|
+
const REDACTED = "***";
|
|
28
|
+
const MAX_SECTION_CHARS = 2e4;
|
|
29
|
+
const COLLECTOR_TIMEOUT_MS = 8e3;
|
|
30
|
+
const formsOf = (value) => [
|
|
31
|
+
value,
|
|
32
|
+
Buffer.from(value).toString("base64"),
|
|
33
|
+
JSON.stringify(value).slice(1, -1)
|
|
34
|
+
];
|
|
35
|
+
/** Longest first, so that a value containing another is removed whole. */
|
|
36
|
+
const sanitize = (text, sensitive) => {
|
|
37
|
+
return sensitive.filter((value) => value.length > 0).flatMap(formsOf).sort((left, right) => right.length - left.length).reduce((current, form) => current.replaceAll(form, REDACTED), text);
|
|
38
|
+
};
|
|
39
|
+
const withinLimit = async (collect) => {
|
|
40
|
+
const { promise: expired, reject } = Promise.withResolvers();
|
|
41
|
+
const timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`timed out after ${COLLECTOR_TIMEOUT_MS}ms`)), COLLECTOR_TIMEOUT_MS);
|
|
42
|
+
try {
|
|
43
|
+
return await Promise.race([collect(), expired]);
|
|
44
|
+
} finally {
|
|
45
|
+
clearTimeout(timer);
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
/** The end of a section is kept, because that is where a failure usually shows. */
|
|
49
|
+
const bounded = (text) => text.length > MAX_SECTION_CHARS ? `[earlier output removed]\n${text.slice(-2e4)}` : text;
|
|
50
|
+
const createEvidence = (client) => {
|
|
51
|
+
const sensitive = [];
|
|
52
|
+
const sections = [];
|
|
53
|
+
let restricted = false;
|
|
54
|
+
const evidence = {
|
|
55
|
+
markSensitive: (value) => {
|
|
56
|
+
sensitive.push(value);
|
|
57
|
+
},
|
|
58
|
+
restrict: () => {
|
|
59
|
+
restricted = true;
|
|
60
|
+
},
|
|
61
|
+
add: (title, collect, options = {}) => {
|
|
62
|
+
sections.push({
|
|
63
|
+
title,
|
|
64
|
+
collect,
|
|
65
|
+
mayContainSensitiveData: options.mayContainSensitiveData ?? false
|
|
66
|
+
});
|
|
67
|
+
},
|
|
68
|
+
watchServices: (input) => {
|
|
69
|
+
addServiceEvidence(evidence, client, Array.isArray(input) ? { services: input } : input ?? {});
|
|
70
|
+
},
|
|
71
|
+
capture: async () => {
|
|
72
|
+
const included = sections.filter((section) => !(restricted && section.mayContainSensitiveData));
|
|
73
|
+
const bodies = await Promise.all(included.map(({ collect }) => withinLimit(collect).catch((error) => `could not collect: ${String(error)}`)));
|
|
74
|
+
return included.map(({ title }, index) => sanitize(`--- ${title}\n${bounded(bodies[index] ?? "")}`, sensitive)).join("\n");
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
return evidence;
|
|
78
|
+
};
|
|
79
|
+
// src/vitest/matchers.ts
|
|
80
|
+
const labelOf = (container) => {
|
|
81
|
+
if (!container) return "container (absent)";
|
|
82
|
+
return container.service ? `service ${container.service} (${container.name || container.id})` : container.name || "container";
|
|
83
|
+
};
|
|
84
|
+
const toBeContainerRunning = (received) => {
|
|
85
|
+
return {
|
|
86
|
+
pass: Boolean(received && received.state === "running"),
|
|
87
|
+
message: () => `expected ${labelOf(received)} to be running, but its state is ${received?.state ?? "absent"}${received?.status ? ` (${received.status})` : ""}`
|
|
88
|
+
};
|
|
89
|
+
};
|
|
90
|
+
const toBeContainerHealthy = (received) => {
|
|
91
|
+
return {
|
|
92
|
+
pass: Boolean(received && received.state === "running" && (received.health === "healthy" || received.health === "" || received.health === "none")),
|
|
93
|
+
message: () => `expected ${labelOf(received)} to be healthy, but its state is ${received?.state ?? "absent"} and health is ${received?.health || "none"}${received?.status ? ` (${received.status})` : ""}`
|
|
94
|
+
};
|
|
95
|
+
};
|
|
96
|
+
const toHaveContainerState = (received, expected) => {
|
|
97
|
+
return {
|
|
98
|
+
pass: Boolean(received && received.state === expected),
|
|
99
|
+
message: () => `expected ${labelOf(received)} to have state ${expected}, but it is ${received?.state ?? "absent"}${received?.status ? ` (${received.status})` : ""}`
|
|
100
|
+
};
|
|
101
|
+
};
|
|
102
|
+
const toHaveExitedWith = (received, code) => {
|
|
103
|
+
return {
|
|
104
|
+
pass: Boolean(received && received.state === "exited" && received.exitCode === code),
|
|
105
|
+
message: () => `expected ${labelOf(received)} to have exited with code ${code}, but state is ${received?.state ?? "absent"}${received?.state === "exited" ? ` (exitCode=${received.exitCode})` : ""}`
|
|
106
|
+
};
|
|
107
|
+
};
|
|
108
|
+
// src/vitest/test.ts
|
|
109
|
+
expect.extend({
|
|
110
|
+
toBeContainerRunning,
|
|
111
|
+
toBeContainerHealthy,
|
|
112
|
+
toHaveContainerState,
|
|
113
|
+
toHaveExitedWith
|
|
114
|
+
});
|
|
115
|
+
/** Reports a forgotten setup clearly, instead of a TypeError from the Compose client. */
|
|
116
|
+
const stackTarget = () => {
|
|
117
|
+
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
|
+
return target;
|
|
120
|
+
};
|
|
121
|
+
const stateStore = () => createStackStateStore(inject("vitecomposeStateDir"));
|
|
122
|
+
const test = test$1.extend("environmentGuard", { auto: true }, async () => {
|
|
123
|
+
const state = await stateStore().read();
|
|
124
|
+
if (state?.unusable) throw new Error(`The Compose stack is marked unusable: ${state.unusable}`);
|
|
125
|
+
}).extend("fileCompose", { scope: "file" }, ({}) => createComposeClient(stackTarget(), {
|
|
126
|
+
rootDir: inject("vitecomposeRoot"),
|
|
127
|
+
onEnvironmentDamaged: (reason) => stateStore().markUnusable(reason)
|
|
128
|
+
})).extend("compose", ({ signal }) => createComposeClient(stackTarget(), {
|
|
129
|
+
rootDir: inject("vitecomposeRoot"),
|
|
130
|
+
onEnvironmentDamaged: (reason) => stateStore().markUnusable(reason),
|
|
131
|
+
signal
|
|
132
|
+
})).extend("scope", async ({}, { onCleanup }) => {
|
|
133
|
+
const scope = createScope();
|
|
134
|
+
onCleanup(() => scope.dispose());
|
|
135
|
+
return scope;
|
|
136
|
+
}).extend("evidence", ({ fileCompose }) => createEvidence(fileCompose)).extend("markStackUnusable", () => (reason) => stateStore().markUnusable(reason));
|
|
137
|
+
test.afterEach(async ({ task, evidence }) => {
|
|
138
|
+
if (task.result?.state === "fail") {
|
|
139
|
+
await stateStore().markFailed().catch(() => {});
|
|
140
|
+
const output = await evidence.capture();
|
|
141
|
+
if (output) console.error(output);
|
|
142
|
+
}
|
|
143
|
+
});
|
|
144
|
+
export { test };
|
package/dist/node.d.mts
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { h as ComposeTarget, o as ComposeClient, r as Scope } from "./scope-B1yisv2y.mjs";
|
|
2
|
+
import "./provided-CnoC64M0.mjs";
|
|
3
|
+
import { ProvidedContext } from "vitest";
|
|
4
|
+
import { DefaultReporter, Reporter, TestModule, TestProject, Vitest } from "vitest/node";
|
|
5
|
+
type ImageSpec = {
|
|
6
|
+
name: string;
|
|
7
|
+
/** Defaults to `local`. Compose services then point at this same image reference. */
|
|
8
|
+
tag?: string;
|
|
9
|
+
dockerfile: string;
|
|
10
|
+
context: string;
|
|
11
|
+
/** Optional `--target` stage for multi-stage Dockerfiles. */
|
|
12
|
+
target?: string;
|
|
13
|
+
buildArgs?: Record<string, string>;
|
|
14
|
+
};
|
|
15
|
+
type StageContext = {
|
|
16
|
+
compose: ComposeClient;
|
|
17
|
+
target: ComposeTarget;
|
|
18
|
+
rootDir: string;
|
|
19
|
+
};
|
|
20
|
+
type StageSpec = {
|
|
21
|
+
name: string;
|
|
22
|
+
/** Stages this one needs. They must be declared earlier, and when one runs, this one does too. */
|
|
23
|
+
dependsOn?: readonly string[];
|
|
24
|
+
/** Images this stage deploys. A changed image reruns the stage and recreates its services. */
|
|
25
|
+
images?: readonly string[];
|
|
26
|
+
/** Files or globs that `run` reads, relative to `rootDir`. Compose files are tracked automatically. */
|
|
27
|
+
inputs?: readonly string[];
|
|
28
|
+
/** Compose services to start in this stage. */
|
|
29
|
+
services?: readonly string[];
|
|
30
|
+
/** Compose profiles enabled when starting `services`. */
|
|
31
|
+
profiles?: readonly string[];
|
|
32
|
+
/** Services that must report running/healthy after starting. Defaults to `services`. */
|
|
33
|
+
waitFor?: readonly string[];
|
|
34
|
+
/** Build services using Compose's own `build:` blocks when running this stage. */
|
|
35
|
+
build?: boolean;
|
|
36
|
+
/** For anything a declaration cannot express (migrations, seeding, etc.). Runs last in the stage. */
|
|
37
|
+
run?: (context: StageContext) => Promise<void>;
|
|
38
|
+
};
|
|
39
|
+
type EnvironmentSpec = {
|
|
40
|
+
/** The base of every path here, relative to Vitest's root. Defaults to Vitest's root. */
|
|
41
|
+
rootDir?: string;
|
|
42
|
+
images?: readonly ImageSpec[];
|
|
43
|
+
stages: readonly StageSpec[];
|
|
44
|
+
};
|
|
45
|
+
type ManagedStackOptions = {
|
|
46
|
+
/** The VITECOMPOSE_PROJECT environment variable overrides this, for example to use one stack per worktree. */
|
|
47
|
+
name: string;
|
|
48
|
+
/** Path(s) to Docker Compose YAML file(s), relative to Vitest's root. */
|
|
49
|
+
composeFile: string | readonly string[];
|
|
50
|
+
/** Optional `.env` file passed via `--env-file`, relative to Vitest's root. */
|
|
51
|
+
envFile?: string;
|
|
52
|
+
/** Optional working directory for Compose commands. Defaults to the first Compose file's directory. */
|
|
53
|
+
cwd?: string;
|
|
54
|
+
/** Keep the stack between runs and reuse it. Otherwise each run gets a fresh stack and deletes it afterward. */
|
|
55
|
+
reuse?: boolean;
|
|
56
|
+
/**
|
|
57
|
+
* Default services to start when no `environment.stages` are declared.
|
|
58
|
+
* Omit to start all non-profiled services in the Compose file.
|
|
59
|
+
*/
|
|
60
|
+
services?: readonly string[];
|
|
61
|
+
/** Default Compose profiles to enable when no `environment.stages` are declared. */
|
|
62
|
+
profiles?: readonly string[];
|
|
63
|
+
/** Pass `--build` on `docker compose up` when no `environment.stages` are declared. */
|
|
64
|
+
build?: boolean;
|
|
65
|
+
/** Wait for healthy services on startup when no `environment.stages` are declared. Defaults to `true`. */
|
|
66
|
+
wait?: boolean;
|
|
67
|
+
};
|
|
68
|
+
type ComposeSetupContext = {
|
|
69
|
+
compose: ComposeClient;
|
|
70
|
+
target: ComposeTarget;
|
|
71
|
+
/** Disposed at the end of the run, for long-lived per-run resources. */
|
|
72
|
+
scope: Scope;
|
|
73
|
+
/** Passes a JSON-serializable value to tests, read there with Vitest's `inject`. */
|
|
74
|
+
provide: <K extends keyof ProvidedContext & string>(key: K, value: ProvidedContext[K]) => void;
|
|
75
|
+
};
|
|
76
|
+
type ComposeGlobalSetupOptions = {
|
|
77
|
+
stack: ManagedStackOptions;
|
|
78
|
+
/** What the stack contains: images and ordered stages. Reruns do only the work whose inputs changed. */
|
|
79
|
+
environment?: EnvironmentSpec;
|
|
80
|
+
/** Runs on every run, after the environment is ready. For per-run resources and `provide()` values. */
|
|
81
|
+
setup?: (context: ComposeSetupContext) => Promise<void>;
|
|
82
|
+
/** How long to wait for another run on the same stack. Defaults to failing immediately. */
|
|
83
|
+
lockWaitMs?: number;
|
|
84
|
+
};
|
|
85
|
+
/** Provisions the Docker Compose stack for a run and cleans up after it. Use as default export of a globalSetup file. */
|
|
86
|
+
export declare const defineComposeGlobalSetup: (options: ComposeGlobalSetupOptions) => (project: TestProject) => Promise<(() => Promise<void>) | undefined>;
|
|
87
|
+
/**
|
|
88
|
+
* Vitest's default output, with times people can read at a glance: `38.2s` instead of `38196ms`.
|
|
89
|
+
* It also fails a run whose `-t` filter matched nothing, like `RequireMatchingTests`.
|
|
90
|
+
*/
|
|
91
|
+
export declare class ComposeReporter extends DefaultReporter {
|
|
92
|
+
private readonly filterCheck;
|
|
93
|
+
private startedAt;
|
|
94
|
+
constructor(...args: ConstructorParameters<typeof DefaultReporter>);
|
|
95
|
+
onInit(vitest: Vitest): void;
|
|
96
|
+
onTestRunEnd(...args: Parameters<DefaultReporter["onTestRunEnd"]>): void;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Vitest exits 0 when `-t` matches nothing, so a typo in a filter looks like a pass after a full provision.
|
|
100
|
+
* This reporter fails that run. Runs without a name filter are unaffected, so a suite that is
|
|
101
|
+
* entirely `test.skip` still passes.
|
|
102
|
+
*/
|
|
103
|
+
export declare class RequireMatchingTests implements Reporter {
|
|
104
|
+
private vitest;
|
|
105
|
+
onInit(vitest: Vitest): void;
|
|
106
|
+
onTestRunEnd(testModules: readonly TestModule[]): void;
|
|
107
|
+
}
|
|
108
|
+
export type { ComposeGlobalSetupOptions, ComposeSetupContext, EnvironmentSpec, ImageSpec, ManagedStackOptions, StageContext, StageSpec };
|