Skip to content

Commit 1ceaad1

Browse files
committed
test: harden vitest no-isolate coverage
1 parent 719bfb4 commit 1ceaad1

39 files changed

Lines changed: 827 additions & 295 deletions

‎docs/help/testing.md‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -68,18 +68,20 @@ Think of the suites as “increasing realism” (and increasing flakiness/cost):
6868
through the real `run.ts` / `compact.ts` paths; helper-only tests are not a
6969
sufficient substitute for those integration paths.
7070
- Pool note:
71-
- OpenClaw uses Vitest `vmForks` on Node 22, 23, and 24 for faster unit shards.
72-
- On Node 25+, OpenClaw automatically falls back to regular `forks` until the repo is re-validated there.
73-
- Override manually with `OPENCLAW_TEST_VM_FORKS=0` (force `forks`) or `OPENCLAW_TEST_VM_FORKS=1` (force `vmForks`).
71+
- OpenClaw uses Vitest `forks` by default for unit shards.
72+
- `pnpm test` also defaults to `--isolate=false` at the wrapper level for faster file startup.
73+
- Opt back into Vitest file isolation with `OPENCLAW_TEST_ISOLATE=1 pnpm test`.
74+
- `OPENCLAW_TEST_NO_ISOLATE=0` or `OPENCLAW_TEST_NO_ISOLATE=false` also force isolated runs.
75+
- `OPENCLAW_TEST_VM_FORKS=1` remains an opt-in experiment on Node 22, 23, and 24 only.
7476

7577
### E2E (gateway smoke)
7678

7779
- Command: `pnpm test:e2e`
7880
- Config: `vitest.e2e.config.ts`
7981
- Files: `src/**/*.e2e.test.ts`, `test/**/*.e2e.test.ts`
8082
- Runtime defaults:
81-
- Uses Vitest `vmForks` for faster file startup.
82-
- Uses adaptive workers (CI: 2-4, local: 4-8).
83+
- Uses Vitest `forks` for deterministic cross-file isolation.
84+
- Uses adaptive workers (CI: up to 2, local: 1 by default).
8385
- Runs in silent mode by default to reduce console I/O overhead.
8486
- Useful overrides:
8587
- `OPENCLAW_E2E_WORKERS=<n>` to force worker count (capped at 16).

‎extensions/github-copilot/models.test.ts‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,15 @@
11
import { describe, expect, it, vi } from "vitest";
22

3-
vi.mock("@mariozechner/pi-ai/oauth", () => ({
4-
getOAuthApiKey: vi.fn(),
5-
getOAuthProviders: vi.fn(() => []),
6-
}));
3+
vi.mock("@mariozechner/pi-ai/oauth", async () => {
4+
const actual = await vi.importActual<typeof import("@mariozechner/pi-ai/oauth")>(
5+
"@mariozechner/pi-ai/oauth",
6+
);
7+
return {
8+
...actual,
9+
getOAuthApiKey: vi.fn(),
10+
getOAuthProviders: vi.fn(() => []),
11+
};
12+
});
713

814
vi.mock("openclaw/plugin-sdk/provider-models", () => ({
915
normalizeModelCompat: (model: Record<string, unknown>) => model,

‎scripts/test-parallel.mjs‎

Lines changed: 50 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,12 @@ const isMacMiniProfile = testProfile === "macmini";
9494
// Preserve OPENCLAW_TEST_VM_FORKS=1 as the explicit override/debug escape hatch.
9595
const supportsVmForks = Number.isFinite(nodeMajor) ? nodeMajor <= 24 : true;
9696
const useVmForks = process.env.OPENCLAW_TEST_VM_FORKS === "1" && supportsVmForks;
97-
const disableIsolation = process.env.OPENCLAW_TEST_NO_ISOLATE === "1";
97+
const forceIsolation =
98+
process.env.OPENCLAW_TEST_ISOLATE === "1" || process.env.OPENCLAW_TEST_ISOLATE === "true";
99+
const disableIsolation =
100+
!forceIsolation &&
101+
process.env.OPENCLAW_TEST_NO_ISOLATE !== "0" &&
102+
process.env.OPENCLAW_TEST_NO_ISOLATE !== "false";
98103
const includeGatewaySuite = process.env.OPENCLAW_TEST_INCLUDE_GATEWAY === "1";
99104
const includeExtensionsSuite = process.env.OPENCLAW_TEST_INCLUDE_EXTENSIONS === "1";
100105
// Even on low-memory hosts, keep the isolated lane split so files like
@@ -699,10 +704,40 @@ const createTargetedEntry = (owner, isolated, filters) => {
699704
],
700705
};
701706
};
707+
const formatPerFileEntryName = (owner, file) => {
708+
const baseName = path
709+
.basename(file)
710+
.replace(/\.live\.test\.ts$/u, "")
711+
.replace(/\.e2e\.test\.ts$/u, "")
712+
.replace(/\.test\.ts$/u, "");
713+
return `${owner}-${baseName}`;
714+
};
715+
const createPerFileTargetedEntry = (file) => {
716+
const target = inferTarget(file);
717+
const owner = isThreadSingletonUnitFile(file)
718+
? "unit-threads"
719+
: isVmForkSingletonUnitFile(file)
720+
? "unit-vmforks"
721+
: target.owner;
722+
return {
723+
...createTargetedEntry(owner, target.isolated, [file]),
724+
name: formatPerFileEntryName(owner, file),
725+
};
726+
};
702727
const targetedEntries = (() => {
703728
if (passthroughFileFilters.length === 0) {
704729
return [];
705730
}
731+
if (disableIsolation) {
732+
const matchedFiles = passthroughFileFilters.flatMap((fileFilter) => {
733+
const resolved = resolveFilterMatches(fileFilter);
734+
if (resolved.length > 0) {
735+
return resolved;
736+
}
737+
return [normalizeRepoPath(fileFilter)];
738+
});
739+
return [...new Set(matchedFiles)].map((file) => createPerFileTargetedEntry(file));
740+
}
706741
const groups = passthroughFileFilters.reduce((acc, fileFilter) => {
707742
const matchedFiles = resolveFilterMatches(fileFilter);
708743
if (matchedFiles.length === 0) {
@@ -738,15 +773,27 @@ const targetedEntries = (() => {
738773
return createTargetedEntry(owner, mode === "isolated", [...new Set(filters)]);
739774
});
740775
})();
776+
if (disableIsolation && passthroughFileFilters.length === 0) {
777+
runs = allKnownUnitFiles.map((file) => createPerFileTargetedEntry(file));
778+
}
741779
// Node 25 local runs still show cross-process worker shutdown contention even
742780
// after moving the known heavy files into singleton lanes.
743781
const topLevelParallelEnabled =
744782
testProfile !== "low" &&
745783
testProfile !== "serial" &&
746784
!(!isCI && nodeMajor >= 25) &&
747785
!isMacMiniProfile;
748-
const defaultTopLevelParallelLimit =
749-
testProfile === "serial"
786+
const defaultTopLevelParallelLimit = disableIsolation
787+
? isCI
788+
? isWindows
789+
? 2
790+
: 4
791+
: highMemLocalHost
792+
? Math.min(16, hostCpuCount)
793+
: lowMemLocalHost
794+
? Math.min(8, hostCpuCount)
795+
: Math.min(12, hostCpuCount)
796+
: testProfile === "serial"
750797
? 1
751798
: testProfile === "low"
752799
? lowMemLocalHost

‎src/acp/control-plane/manager.test.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { setTimeout as scheduleNativeTimeout } from "node:timers";
2+
import { setTimeout as sleep } from "node:timers/promises";
13
import { beforeEach, describe, expect, it, vi } from "vitest";
24
import type { OpenClawConfig } from "../../config/config.js";
35
import type { AcpSessionRuntimeOptions, SessionAcpMeta } from "../../config/sessions/types.js";
@@ -148,6 +150,7 @@ function extractRuntimeOptionsFromUpserts(): Array<AcpSessionRuntimeOptions | un
148150

149151
describe("AcpSessionManager", () => {
150152
beforeEach(() => {
153+
vi.useRealTimers();
151154
hoisted.listAcpSessionEntriesMock.mockReset().mockResolvedValue([]);
152155
hoisted.readAcpSessionEntryMock.mockReset();
153156
hoisted.upsertAcpSessionMetaMock.mockReset().mockResolvedValue(null);
@@ -240,7 +243,7 @@ describe("AcpSessionManager", () => {
240243
inFlight += 1;
241244
maxInFlight = Math.max(maxInFlight, inFlight);
242245
try {
243-
await new Promise((resolve) => setTimeout(resolve, 10));
246+
await sleep(10);
244247
yield { type: "done" };
245248
} finally {
246249
inFlight -= 1;
@@ -321,7 +324,7 @@ describe("AcpSessionManager", () => {
321324
(error) => ({ status: "rejected" as const, error }),
322325
),
323326
new Promise<{ status: "pending" }>((resolve) => {
324-
setTimeout(() => resolve({ status: "pending" }), 100);
327+
scheduleNativeTimeout(() => resolve({ status: "pending" }), 100);
325328
}),
326329
]);
327330

@@ -538,7 +541,7 @@ describe("AcpSessionManager", () => {
538541
inFlight += 1;
539542
maxInFlight = Math.max(maxInFlight, inFlight);
540543
try {
541-
await new Promise((resolve) => setTimeout(resolve, 15));
544+
await sleep(15);
542545
yield { type: "done" as const };
543546
} finally {
544547
inFlight -= 1;

‎src/agents/anthropic-vertex-stream.test.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,10 @@ const hoisted = vi.hoisted(() => {
1313
};
1414
});
1515

16-
vi.mock("@mariozechner/pi-ai", () => {
16+
vi.mock("@mariozechner/pi-ai", async (importOriginal) => {
17+
const original = await importOriginal<typeof import("@mariozechner/pi-ai")>();
1718
return {
19+
...original,
1820
streamAnthropic: (model: unknown, context: unknown, options: unknown) =>
1921
hoisted.streamAnthropicMock(model, context, options),
2022
};

‎src/agents/auth-profiles/oauth.openai-codex-refresh-fallback.test.ts‎

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,19 @@ const {
2929
buildProviderAuthDoctorHintWithPluginMock: vi.fn(async () => undefined),
3030
}));
3131

32-
vi.mock("@mariozechner/pi-ai/oauth", () => ({
33-
getOAuthApiKey: getOAuthApiKeyMock,
34-
getOAuthProviders: () => [
35-
{ id: "openai-codex", envApiKey: "OPENAI_API_KEY", oauthTokenEnv: "OPENAI_OAUTH_TOKEN" }, // pragma: allowlist secret
36-
{ id: "anthropic", envApiKey: "ANTHROPIC_API_KEY", oauthTokenEnv: "ANTHROPIC_OAUTH_TOKEN" }, // pragma: allowlist secret
37-
],
38-
}));
32+
vi.mock("@mariozechner/pi-ai/oauth", async () => {
33+
const actual = await vi.importActual<typeof import("@mariozechner/pi-ai/oauth")>(
34+
"@mariozechner/pi-ai/oauth",
35+
);
36+
return {
37+
...actual,
38+
getOAuthApiKey: getOAuthApiKeyMock,
39+
getOAuthProviders: () => [
40+
{ id: "openai-codex", envApiKey: "OPENAI_API_KEY", oauthTokenEnv: "OPENAI_OAUTH_TOKEN" }, // pragma: allowlist secret
41+
{ id: "anthropic", envApiKey: "ANTHROPIC_API_KEY", oauthTokenEnv: "ANTHROPIC_OAUTH_TOKEN" }, // pragma: allowlist secret
42+
],
43+
};
44+
});
3945

4046
vi.mock("../../plugins/provider-runtime.runtime.js", () => ({
4147
refreshProviderOAuthCredentialWithPlugin: refreshProviderOAuthCredentialWithPluginMock,

‎src/agents/btw.test.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,13 @@ const resolveSessionAuthProfileOverrideMock = vi.fn();
1616
const getActiveEmbeddedRunSnapshotMock = vi.fn();
1717
const diagDebugMock = vi.fn();
1818

19-
vi.mock("@mariozechner/pi-ai", () => ({
20-
streamSimple: (...args: unknown[]) => streamSimpleMock(...args),
21-
}));
19+
vi.mock("@mariozechner/pi-ai", async (importOriginal) => {
20+
const original = await importOriginal<typeof import("@mariozechner/pi-ai")>();
21+
return {
22+
...original,
23+
streamSimple: (...args: unknown[]) => streamSimpleMock(...args),
24+
};
25+
});
2226

2327
vi.mock("@mariozechner/pi-coding-agent", () => ({
2428
SessionManager: {

‎src/agents/pi-embedded-runner/compact.hooks.harness.ts‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -192,10 +192,16 @@ export async function loadCompactHooksHarness(): Promise<{
192192
};
193193
});
194194

195-
vi.doMock("@mariozechner/pi-ai/oauth", () => ({
196-
getOAuthApiKey: vi.fn(),
197-
getOAuthProviders: vi.fn(() => []),
198-
}));
195+
vi.doMock("@mariozechner/pi-ai/oauth", async () => {
196+
const actual = await vi.importActual<typeof import("@mariozechner/pi-ai/oauth")>(
197+
"@mariozechner/pi-ai/oauth",
198+
);
199+
return {
200+
...actual,
201+
getOAuthApiKey: vi.fn(),
202+
getOAuthProviders: vi.fn(() => []),
203+
};
204+
});
199205

200206
vi.doMock("@mariozechner/pi-coding-agent", () => ({
201207
AuthStorage: class AuthStorage {},

‎src/agents/pi-embedded-runner/extra-params.google.test.ts‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,16 @@ import type { Model } from "@mariozechner/pi-ai";
22
import { describe, expect, it, vi } from "vitest";
33
import { runExtraParamsCase } from "./extra-params.test-support.js";
44

5-
vi.mock("@mariozechner/pi-ai", () => ({
6-
streamSimple: vi.fn(() => ({
7-
push: vi.fn(),
8-
result: vi.fn(),
9-
})),
10-
}));
5+
vi.mock("@mariozechner/pi-ai", async (importOriginal) => {
6+
const original = await importOriginal<typeof import("@mariozechner/pi-ai")>();
7+
return {
8+
...original,
9+
streamSimple: vi.fn(() => ({
10+
push: vi.fn(),
11+
result: vi.fn(),
12+
})),
13+
};
14+
});
1115

1216
describe("extra-params: Google thinking payload compatibility", () => {
1317
it("strips negative thinking budgets and fills Gemini 3.1 thinkingLevel", () => {

‎src/agents/pi-embedded-runner/extra-params.xai-tool-payload.test.ts‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,16 @@ import type { Model } from "@mariozechner/pi-ai";
22
import { describe, expect, it, vi } from "vitest";
33
import { runExtraParamsCase } from "./extra-params.test-support.js";
44

5-
vi.mock("@mariozechner/pi-ai", () => ({
6-
streamSimple: vi.fn(() => ({
7-
push: vi.fn(),
8-
result: vi.fn(),
9-
})),
10-
}));
5+
vi.mock("@mariozechner/pi-ai", async (importOriginal) => {
6+
const original = await importOriginal<typeof import("@mariozechner/pi-ai")>();
7+
return {
8+
...original,
9+
streamSimple: vi.fn(() => ({
10+
push: vi.fn(),
11+
result: vi.fn(),
12+
})),
13+
};
14+
});
1115

1216
describe("extra-params: xAI tool payload compatibility", () => {
1317
it("strips function.strict for xai providers", () => {

0 commit comments

Comments
 (0)