Skip to content

Commit 914bece

Browse files
committed
fix: isolate live test home from real config
1 parent 8ea4c4a commit 914bece

3 files changed

Lines changed: 296 additions & 17 deletions

File tree

‎docs/help/testing.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,9 @@ Think of the suites as “increasing realism” (and increasing flakiness/cost):
151151
- Not CI-stable by design (real networks, real provider policies, quotas, outages)
152152
- Costs money / uses rate limits
153153
- Prefer running narrowed subsets instead of “everything”
154-
- Live runs will source `~/.profile` to pick up missing API keys
154+
- Live runs source `~/.profile` to pick up missing API keys.
155+
- By default, live runs still isolate `HOME` and copy config/auth material into a temp test home so unit fixtures cannot mutate your real `~/.openclaw`.
156+
- Set `OPENCLAW_LIVE_USE_REAL_HOME=1` only when you intentionally need live tests to use your real home directory.
155157
- `pnpm test:live` now defaults to a quieter mode: it keeps `[live] ...` progress output, but suppresses the extra `~/.profile` notice and mutes gateway bootstrap logs/Bonjour chatter. Set `OPENCLAW_LIVE_TEST_QUIET=0` if you want the full startup logs back.
156158
- API key rotation (provider-specific): set `*_API_KEYS` with comma/semicolon format or `*_API_KEY_1`, `*_API_KEY_2` (for example `OPENAI_API_KEYS`, `ANTHROPIC_API_KEYS`, `GEMINI_API_KEYS`) or per-live override via `OPENCLAW_LIVE_*_KEY`; tests retry on rate limit responses.
157159
- Progress/heartbeat output:
@@ -452,6 +454,7 @@ Live tests discover credentials the same way the CLI does. Practical implication
452454

453455
- Profile store: `~/.openclaw/credentials/` (preferred; what “profile keys” means in the tests)
454456
- Config: `~/.openclaw/openclaw.json` (or `OPENCLAW_CONFIG_PATH`)
457+
- Live local runs copy the active config plus auth stores into a temp test home by default; `agents.*.workspace` / `agentDir` path overrides are stripped in that staged copy so probes stay off your real host workspace.
455458

456459
If you want to rely on env keys (e.g. exported in your `~/.profile`), run local tests after `source ~/.profile`, or use the Docker runners below (they can mount `~/.profile` into the container).
457460

‎test/test-env.test.ts‎

Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
import fs from "node:fs";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import { afterEach, describe, expect, it } from "vitest";
5+
import { installTestEnv } from "./test-env.js";
6+
7+
const ORIGINAL_ENV = { ...process.env };
8+
9+
const tempDirs = new Set<string>();
10+
const cleanupFns: Array<() => void> = [];
11+
12+
function restoreProcessEnv(): void {
13+
for (const key of Object.keys(process.env)) {
14+
if (!(key in ORIGINAL_ENV)) {
15+
delete process.env[key];
16+
}
17+
}
18+
for (const [key, value] of Object.entries(ORIGINAL_ENV)) {
19+
if (value === undefined) {
20+
delete process.env[key];
21+
} else {
22+
process.env[key] = value;
23+
}
24+
}
25+
}
26+
27+
function writeFile(targetPath: string, content: string): void {
28+
fs.mkdirSync(path.dirname(targetPath), { recursive: true });
29+
fs.writeFileSync(targetPath, content, "utf8");
30+
}
31+
32+
function createTempHome(): string {
33+
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-test-env-real-home-"));
34+
tempDirs.add(tempDir);
35+
return tempDir;
36+
}
37+
38+
afterEach(() => {
39+
while (cleanupFns.length > 0) {
40+
cleanupFns.pop()?.();
41+
}
42+
restoreProcessEnv();
43+
for (const tempDir of tempDirs) {
44+
fs.rmSync(tempDir, { recursive: true, force: true });
45+
}
46+
tempDirs.clear();
47+
});
48+
49+
describe("installTestEnv", () => {
50+
it("keeps live tests on a temp HOME while copying config and auth state", () => {
51+
const realHome = createTempHome();
52+
writeFile(path.join(realHome, ".profile"), "export TEST_PROFILE_ONLY=from-profile\n");
53+
writeFile(
54+
path.join(realHome, "custom-openclaw.json5"),
55+
`{
56+
// Preserve provider config, strip host-bound paths.
57+
agents: {
58+
defaults: {
59+
workspace: "/Users/peter/Projects",
60+
agentDir: "/Users/peter/.openclaw/agents/main/agent",
61+
},
62+
list: [
63+
{
64+
id: "dev",
65+
workspace: "/Users/peter/dev-workspace",
66+
agentDir: "/Users/peter/.openclaw/agents/dev/agent",
67+
},
68+
],
69+
},
70+
models: {
71+
providers: {
72+
custom: { baseUrl: "https://example.test/v1" },
73+
},
74+
},
75+
}`,
76+
);
77+
writeFile(path.join(realHome, ".openclaw", "credentials", "token.txt"), "secret\n");
78+
writeFile(
79+
path.join(realHome, ".openclaw", "agents", "main", "agent", "auth-profiles.json"),
80+
JSON.stringify({ version: 1, profiles: { default: { provider: "openai" } } }, null, 2),
81+
);
82+
writeFile(path.join(realHome, ".claude", ".credentials.json"), '{"accessToken":"token"}\n');
83+
84+
process.env.HOME = realHome;
85+
process.env.USERPROFILE = realHome;
86+
process.env.OPENCLAW_LIVE_TEST = "1";
87+
process.env.OPENCLAW_LIVE_TEST_QUIET = "1";
88+
process.env.OPENCLAW_CONFIG_PATH = "~/custom-openclaw.json5";
89+
90+
const testEnv = installTestEnv();
91+
cleanupFns.push(testEnv.cleanup);
92+
93+
expect(testEnv.tempHome).not.toBe(realHome);
94+
expect(process.env.HOME).toBe(testEnv.tempHome);
95+
expect(process.env.OPENCLAW_TEST_HOME).toBe(testEnv.tempHome);
96+
expect(process.env.TEST_PROFILE_ONLY).toBe("from-profile");
97+
98+
const copiedConfigPath = path.join(testEnv.tempHome, ".openclaw", "openclaw.json");
99+
const copiedConfig = JSON.parse(fs.readFileSync(copiedConfigPath, "utf8")) as {
100+
agents?: {
101+
defaults?: Record<string, unknown>;
102+
list?: Array<Record<string, unknown>>;
103+
};
104+
models?: { providers?: Record<string, unknown> };
105+
};
106+
expect(copiedConfig.models?.providers?.custom).toEqual({ baseUrl: "https://example.test/v1" });
107+
expect(copiedConfig.agents?.defaults?.workspace).toBeUndefined();
108+
expect(copiedConfig.agents?.defaults?.agentDir).toBeUndefined();
109+
expect(copiedConfig.agents?.list?.[0]?.workspace).toBeUndefined();
110+
expect(copiedConfig.agents?.list?.[0]?.agentDir).toBeUndefined();
111+
112+
expect(
113+
fs.existsSync(path.join(testEnv.tempHome, ".openclaw", "credentials", "token.txt")),
114+
).toBe(true);
115+
expect(
116+
fs.existsSync(
117+
path.join(testEnv.tempHome, ".openclaw", "agents", "main", "agent", "auth-profiles.json"),
118+
),
119+
).toBe(true);
120+
expect(fs.existsSync(path.join(testEnv.tempHome, ".claude", ".credentials.json"))).toBe(true);
121+
});
122+
123+
it("allows explicit live runs against the real HOME", () => {
124+
const realHome = createTempHome();
125+
writeFile(path.join(realHome, ".profile"), "export TEST_PROFILE_ONLY=from-profile\n");
126+
127+
process.env.HOME = realHome;
128+
process.env.USERPROFILE = realHome;
129+
process.env.OPENCLAW_LIVE_TEST = "1";
130+
process.env.OPENCLAW_LIVE_USE_REAL_HOME = "1";
131+
process.env.OPENCLAW_LIVE_TEST_QUIET = "1";
132+
133+
const testEnv = installTestEnv();
134+
135+
expect(testEnv.tempHome).toBe(realHome);
136+
expect(process.env.HOME).toBe(realHome);
137+
expect(process.env.TEST_PROFILE_ONLY).toBe("from-profile");
138+
});
139+
});

‎test/test-env.ts‎

Lines changed: 153 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,12 @@ import { execFileSync } from "node:child_process";
22
import fs from "node:fs";
33
import os from "node:os";
44
import path from "node:path";
5+
import JSON5 from "json5";
56

67
type RestoreEntry = { key: string; value: string | undefined };
78

9+
const LIVE_EXTERNAL_AUTH_DIRS = [".claude", ".codex", ".minimax"] as const;
10+
811
function isTruthyEnvValue(value: string | undefined): boolean {
912
if (!value) {
1013
return false;
@@ -31,8 +34,19 @@ function restoreEnv(entries: RestoreEntry[]): void {
3134
}
3235
}
3336

34-
function loadProfileEnv(): void {
35-
const profilePath = path.join(os.homedir(), ".profile");
37+
function resolveHomeRelativePath(input: string, homeDir: string): string {
38+
const trimmed = input.trim();
39+
if (trimmed === "~") {
40+
return homeDir;
41+
}
42+
if (trimmed.startsWith("~/") || trimmed.startsWith("~\\")) {
43+
return path.join(homeDir, trimmed.slice(2));
44+
}
45+
return path.resolve(trimmed);
46+
}
47+
48+
function loadProfileEnv(homeDir = os.homedir()): void {
49+
const profilePath = path.join(homeDir, ".profile");
3650
if (!fs.existsSync(profilePath)) {
3751
return;
3852
}
@@ -67,20 +81,8 @@ function loadProfileEnv(): void {
6781
}
6882
}
6983

70-
export function installTestEnv(): { cleanup: () => void; tempHome: string } {
71-
const live =
72-
process.env.LIVE === "1" ||
73-
process.env.OPENCLAW_LIVE_TEST === "1" ||
74-
process.env.OPENCLAW_LIVE_GATEWAY === "1";
75-
76-
// Live tests must use the real user environment (keys, profiles, config).
77-
// The default test env isolates HOME to avoid touching real state.
78-
if (live) {
79-
loadProfileEnv();
80-
return { cleanup: () => {}, tempHome: process.env.HOME ?? "" };
81-
}
82-
83-
const restore: RestoreEntry[] = [
84+
function resolveRestoreEntries(): RestoreEntry[] {
85+
return [
8486
{ key: "OPENCLAW_TEST_FAST", value: process.env.OPENCLAW_TEST_FAST },
8587
{ key: "HOME", value: process.env.HOME },
8688
{ key: "USERPROFILE", value: process.env.USERPROFILE },
@@ -96,6 +98,8 @@ export function installTestEnv(): { cleanup: () => void; tempHome: string } {
9698
{ key: "OPENCLAW_BRIDGE_PORT", value: process.env.OPENCLAW_BRIDGE_PORT },
9799
{ key: "OPENCLAW_CANVAS_HOST_PORT", value: process.env.OPENCLAW_CANVAS_HOST_PORT },
98100
{ key: "OPENCLAW_TEST_HOME", value: process.env.OPENCLAW_TEST_HOME },
101+
{ key: "OPENCLAW_AGENT_DIR", value: process.env.OPENCLAW_AGENT_DIR },
102+
{ key: "PI_CODING_AGENT_DIR", value: process.env.PI_CODING_AGENT_DIR },
99103
{ key: "TELEGRAM_BOT_TOKEN", value: process.env.TELEGRAM_BOT_TOKEN },
100104
{ key: "DISCORD_BOT_TOKEN", value: process.env.DISCORD_BOT_TOKEN },
101105
{ key: "SLACK_BOT_TOKEN", value: process.env.SLACK_BOT_TOKEN },
@@ -106,7 +110,12 @@ export function installTestEnv(): { cleanup: () => void; tempHome: string } {
106110
{ key: "GITHUB_TOKEN", value: process.env.GITHUB_TOKEN },
107111
{ key: "NODE_OPTIONS", value: process.env.NODE_OPTIONS },
108112
];
113+
}
109114

115+
function createIsolatedTestHome(restore: RestoreEntry[]): {
116+
cleanup: () => void;
117+
tempHome: string;
118+
} {
110119
const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-test-home-"));
111120

112121
process.env.HOME = tempHome;
@@ -118,6 +127,8 @@ export function installTestEnv(): { cleanup: () => void; tempHome: string } {
118127
delete process.env.OPENCLAW_CONFIG_PATH;
119128
// Prefer deriving state dir from HOME so nested tests that change HOME also isolate correctly.
120129
delete process.env.OPENCLAW_STATE_DIR;
130+
delete process.env.OPENCLAW_AGENT_DIR;
131+
delete process.env.PI_CODING_AGENT_DIR;
121132
// Prefer test-controlled ports over developer overrides (avoid port collisions across tests/workers).
122133
delete process.env.OPENCLAW_GATEWAY_PORT;
123134
delete process.env.OPENCLAW_BRIDGE_ENABLED;
@@ -158,6 +169,132 @@ export function installTestEnv(): { cleanup: () => void; tempHome: string } {
158169
return { cleanup, tempHome };
159170
}
160171

172+
function ensureParentDir(targetPath: string): void {
173+
fs.mkdirSync(path.dirname(targetPath), { recursive: true });
174+
}
175+
176+
function copyDirIfExists(sourcePath: string, targetPath: string): void {
177+
if (!fs.existsSync(sourcePath)) {
178+
return;
179+
}
180+
fs.mkdirSync(targetPath, { recursive: true });
181+
fs.cpSync(sourcePath, targetPath, {
182+
recursive: true,
183+
force: true,
184+
});
185+
}
186+
187+
function copyFileIfExists(sourcePath: string, targetPath: string): void {
188+
if (!fs.existsSync(sourcePath)) {
189+
return;
190+
}
191+
ensureParentDir(targetPath);
192+
fs.copyFileSync(sourcePath, targetPath);
193+
}
194+
195+
function sanitizeLiveConfig(raw: string): string {
196+
try {
197+
const parsed = JSON5.parse(raw) as {
198+
agents?: {
199+
defaults?: Record<string, unknown>;
200+
list?: Array<Record<string, unknown>>;
201+
};
202+
};
203+
if (!parsed || typeof parsed !== "object") {
204+
return raw;
205+
}
206+
if (parsed.agents?.defaults && typeof parsed.agents.defaults === "object") {
207+
delete parsed.agents.defaults.workspace;
208+
delete parsed.agents.defaults.agentDir;
209+
}
210+
if (Array.isArray(parsed.agents?.list)) {
211+
parsed.agents.list = parsed.agents.list.map((entry) => {
212+
if (!entry || typeof entry !== "object") {
213+
return entry;
214+
}
215+
const nextEntry = { ...entry };
216+
delete nextEntry.workspace;
217+
delete nextEntry.agentDir;
218+
return nextEntry;
219+
});
220+
}
221+
return `${JSON.stringify(parsed, null, 2)}\n`;
222+
} catch {
223+
return raw;
224+
}
225+
}
226+
227+
function copyLiveAuthProfiles(realStateDir: string, tempStateDir: string): void {
228+
const agentsDir = path.join(realStateDir, "agents");
229+
if (!fs.existsSync(agentsDir)) {
230+
return;
231+
}
232+
for (const entry of fs.readdirSync(agentsDir, { withFileTypes: true })) {
233+
if (!entry.isDirectory()) {
234+
continue;
235+
}
236+
const sourcePath = path.join(agentsDir, entry.name, "agent", "auth-profiles.json");
237+
const targetPath = path.join(tempStateDir, "agents", entry.name, "agent", "auth-profiles.json");
238+
copyFileIfExists(sourcePath, targetPath);
239+
}
240+
}
241+
242+
function stageLiveTestState(params: {
243+
env: NodeJS.ProcessEnv;
244+
realHome: string;
245+
tempHome: string;
246+
}): void {
247+
const realStateDir = params.env.OPENCLAW_STATE_DIR?.trim()
248+
? resolveHomeRelativePath(params.env.OPENCLAW_STATE_DIR, params.realHome)
249+
: path.join(params.realHome, ".openclaw");
250+
const tempStateDir = path.join(params.tempHome, ".openclaw");
251+
fs.mkdirSync(tempStateDir, { recursive: true });
252+
253+
const realConfigPath = params.env.OPENCLAW_CONFIG_PATH?.trim()
254+
? resolveHomeRelativePath(params.env.OPENCLAW_CONFIG_PATH, params.realHome)
255+
: path.join(realStateDir, "openclaw.json");
256+
if (fs.existsSync(realConfigPath)) {
257+
const rawConfig = fs.readFileSync(realConfigPath, "utf8");
258+
fs.writeFileSync(
259+
path.join(tempStateDir, "openclaw.json"),
260+
sanitizeLiveConfig(rawConfig),
261+
"utf8",
262+
);
263+
}
264+
265+
copyDirIfExists(path.join(realStateDir, "credentials"), path.join(tempStateDir, "credentials"));
266+
copyLiveAuthProfiles(realStateDir, tempStateDir);
267+
268+
for (const authDir of LIVE_EXTERNAL_AUTH_DIRS) {
269+
copyDirIfExists(path.join(params.realHome, authDir), path.join(params.tempHome, authDir));
270+
}
271+
}
272+
273+
export function installTestEnv(): { cleanup: () => void; tempHome: string } {
274+
const live =
275+
process.env.LIVE === "1" ||
276+
process.env.OPENCLAW_LIVE_TEST === "1" ||
277+
process.env.OPENCLAW_LIVE_GATEWAY === "1";
278+
const allowRealHome = isTruthyEnvValue(process.env.OPENCLAW_LIVE_USE_REAL_HOME);
279+
const realHome = process.env.HOME ?? os.homedir();
280+
const liveEnvSnapshot = { ...process.env };
281+
282+
loadProfileEnv(realHome);
283+
284+
if (live && allowRealHome) {
285+
return { cleanup: () => {}, tempHome: realHome };
286+
}
287+
288+
const restore = resolveRestoreEntries();
289+
const testEnv = createIsolatedTestHome(restore);
290+
291+
if (live) {
292+
stageLiveTestState({ env: liveEnvSnapshot, realHome, tempHome: testEnv.tempHome });
293+
}
294+
295+
return testEnv;
296+
}
297+
161298
export function withIsolatedTestHome(): { cleanup: () => void; tempHome: string } {
162299
return installTestEnv();
163300
}

0 commit comments

Comments
 (0)