Skip to content

Commit 45a1e3c

Browse files
authored
fix(test): release acquired state when wrapper setup fails (#132301)
1 parent b41a06f commit 45a1e3c

4 files changed

Lines changed: 216 additions & 16 deletions

File tree

‎test/helpers/auth-wizard.test.ts‎

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
import fs from "node:fs/promises";
2+
import path from "node:path";
3+
import { describe, expect, it, vi } from "vitest";
4+
import {
5+
closeOpenClawAgentDatabaseByPath,
6+
openOpenClawAgentDatabase,
7+
} from "../../src/state/openclaw-agent-db.js";
8+
import {
9+
closeOpenClawStateDatabaseByPath,
10+
openOpenClawStateDatabase,
11+
} from "../../src/state/openclaw-state-db.js";
12+
import { captureFullEnv, withEnvAsync } from "../../src/test-utils/env.js";
13+
import { setupAuthTestEnv } from "./auth-wizard.js";
14+
15+
describe("setupAuthTestEnv", () => {
16+
it.each([
17+
{ name: "default", agentSubdir: undefined },
18+
{ name: "custom", agentSubdir: "custom-agent" },
19+
])("owns the $name agent directory until cleanup", async ({ agentSubdir }) => {
20+
const previousEnv = { ...process.env };
21+
const snapshot = captureFullEnv();
22+
const fixture = await setupAuthTestEnv("auth-wrapper-success-", { agentSubdir });
23+
try {
24+
expect(fixture.agentDir).toBe(path.join(fixture.stateDir, agentSubdir ?? "agent"));
25+
expect((await fs.stat(fixture.agentDir)).isDirectory()).toBe(true);
26+
expect(process.env.OPENCLAW_AGENT_DIR).toBe(fixture.agentDir);
27+
expect(process.env.OPENCLAW_STATE_DIR).toBe(fixture.stateDir);
28+
expect(process.env.OPENCLAW_CONFIG_PATH).toBe(path.join(fixture.stateDir, "openclaw.json"));
29+
expect(process.env.HOME).toBe(previousEnv.HOME);
30+
await fixture.cleanup();
31+
expect(process.env).toEqual(previousEnv);
32+
await expect(fs.stat(path.dirname(fixture.stateDir))).rejects.toMatchObject({
33+
code: "ENOENT",
34+
});
35+
} finally {
36+
try {
37+
await fixture.cleanup();
38+
} finally {
39+
snapshot.restore();
40+
}
41+
}
42+
});
43+
44+
it.each(["absent", "set"])(
45+
"releases state after agent mkdir fails with agent override %s",
46+
async (prior) => {
47+
await withEnvAsync(
48+
{
49+
OPENCLAW_AGENT_DIR:
50+
prior === "set" ? path.join(process.env.HOME!, "prior-agent") : undefined,
51+
},
52+
async () => {
53+
const previousEnv = { ...process.env };
54+
const snapshot = captureFullEnv();
55+
const failure = new Error("agent mkdir failed");
56+
let root: string | undefined;
57+
let shared: ReturnType<typeof openOpenClawStateDatabase> | undefined;
58+
let agent: ReturnType<typeof openOpenClawAgentDatabase> | undefined;
59+
const mkdir = fs.mkdir;
60+
const mkdirSpy = vi.spyOn(fs, "mkdir").mockImplementation(async (...args) => {
61+
if (
62+
typeof args[0] === "string" &&
63+
args[0] === process.env.OPENCLAW_AGENT_DIR &&
64+
path.basename(args[0]) === "faulting-agent"
65+
) {
66+
const stateDir = path.dirname(args[0]);
67+
root = path.dirname(stateDir);
68+
expect((await fs.stat(stateDir)).isDirectory()).toBe(true);
69+
const env = { ...process.env, OPENCLAW_STATE_DIR: stateDir };
70+
shared = openOpenClawStateDatabase({ env });
71+
agent = openOpenClawAgentDatabase({ agentId: "main", env });
72+
throw failure;
73+
}
74+
return mkdir(...args);
75+
});
76+
try {
77+
await expect(
78+
setupAuthTestEnv("auth-wrapper-failure-", { agentSubdir: "faulting-agent" }),
79+
).rejects.toBe(failure);
80+
expect.soft(process.env).toEqual(previousEnv);
81+
expect.soft(shared?.db.isOpen).toBe(false);
82+
expect.soft(agent?.db.isOpen).toBe(false);
83+
expect(root).toBeDefined();
84+
await expect(fs.stat(root!)).rejects.toMatchObject({ code: "ENOENT" });
85+
} finally {
86+
mkdirSpy.mockRestore();
87+
try {
88+
if (agent) {
89+
closeOpenClawAgentDatabaseByPath(agent.path);
90+
}
91+
if (shared) {
92+
closeOpenClawStateDatabaseByPath(shared.path);
93+
}
94+
} finally {
95+
snapshot.restore();
96+
if (root) {
97+
await fs.rm(root, { recursive: true, force: true });
98+
}
99+
}
100+
}
101+
},
102+
);
103+
},
104+
);
105+
});

‎test/helpers/auth-wizard.ts‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,10 +44,16 @@ export async function setupAuthTestEnv(
4444
): Promise<AuthTestEnv> {
4545
clearRuntimeAuthProfileStoreSnapshots();
4646
const state = await createOpenClawTestState({ prefix, layout: "state-only" });
47-
const agentDir = path.join(state.stateDir, options?.agentSubdir ?? "agent");
48-
process.env.OPENCLAW_AGENT_DIR = agentDir;
49-
await fs.mkdir(agentDir, { recursive: true });
50-
return { stateDir: state.stateDir, agentDir, cleanup: state.cleanup };
47+
try {
48+
const agentDir = path.join(state.stateDir, options?.agentSubdir ?? "agent");
49+
process.env.OPENCLAW_AGENT_DIR = agentDir;
50+
await fs.mkdir(agentDir, { recursive: true });
51+
return { stateDir: state.stateDir, agentDir, cleanup: state.cleanup };
52+
} catch (error) {
53+
// Ownership has not reached the caller, so release the acquired state here.
54+
await state.cleanup();
55+
throw error;
56+
}
5157
}
5258

5359
type AuthTestLifecycle = {
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
import fs from "node:fs/promises";
2+
import path from "node:path";
3+
import { describe, expect, it, vi } from "vitest";
4+
import { captureFullEnv } from "../../src/test-utils/env.js";
5+
import { createOpenClawTestInstance } from "./openclaw-test-instance.js";
6+
7+
describe("createOpenClawTestInstance acquisition", () => {
8+
it.each(["merge", "serialization", "write"] as const)(
9+
"releases acquired state when initial config %s fails",
10+
async (stage) => {
11+
const previousEnv = { ...process.env };
12+
const snapshot = captureFullEnv();
13+
const failure = new Error(`config ${stage} failed`);
14+
let root: string | undefined;
15+
let writeFailure: unknown;
16+
const mkdtemp = fs.mkdtemp;
17+
const allocationSpy = vi.spyOn(fs, "mkdtemp").mockImplementation(async (...args) => {
18+
const allocated = await mkdtemp(...args);
19+
if (args[0].endsWith("instance-wrapper-failure-")) {
20+
root = await fs.realpath(allocated);
21+
}
22+
return allocated;
23+
});
24+
const writeFile = fs.writeFile;
25+
const writeSpy = vi.spyOn(fs, "writeFile").mockImplementation(async (...args) => {
26+
if (
27+
stage === "write" &&
28+
root &&
29+
args[0] === path.join(root, "home", ".openclaw", "openclaw.json")
30+
) {
31+
// A directory at the config path makes the real filesystem write reject.
32+
await fs.mkdir(args[0]);
33+
try {
34+
await writeFile(...args);
35+
} catch (error) {
36+
writeFailure = error;
37+
throw error;
38+
}
39+
return;
40+
}
41+
return writeFile(...args);
42+
});
43+
const failConfig = () => {
44+
expect(root).toBeDefined();
45+
throw failure;
46+
};
47+
const config =
48+
stage === "merge"
49+
? {
50+
get gateway() {
51+
return failConfig();
52+
},
53+
}
54+
: stage === "serialization"
55+
? { toJSON: failConfig }
56+
: {};
57+
try {
58+
const rejected = await createOpenClawTestInstance({
59+
name: "acquisition-failure",
60+
port: 12345,
61+
state: { prefix: "instance-wrapper-failure-" },
62+
config,
63+
}).catch((error: unknown) => error);
64+
if (stage === "write") {
65+
expect(writeFailure).toMatchObject({ code: "EISDIR" });
66+
expect(rejected).toBe(writeFailure);
67+
} else {
68+
expect(rejected).toBe(failure);
69+
}
70+
expect(process.env).toEqual(previousEnv);
71+
expect(root).toBeDefined();
72+
await expect(fs.stat(root!)).rejects.toMatchObject({ code: "ENOENT" });
73+
} finally {
74+
allocationSpy.mockRestore();
75+
writeSpy.mockRestore();
76+
snapshot.restore();
77+
if (root) {
78+
await fs.rm(root, { recursive: true, force: true });
79+
}
80+
}
81+
},
82+
);
83+
});

‎test/helpers/openclaw-test-instance.ts‎

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -456,19 +456,25 @@ export async function createOpenClawTestInstance(
456456
applyEnv: false,
457457
env: options.env,
458458
});
459-
await state.writeConfig(
460-
mergeConfig(
461-
{
462-
gateway: {
463-
port,
464-
auth: { mode: "token", token: gatewayToken },
465-
controlUi: { enabled: false },
459+
try {
460+
await state.writeConfig(
461+
mergeConfig(
462+
{
463+
gateway: {
464+
port,
465+
auth: { mode: "token", token: gatewayToken },
466+
controlUi: { enabled: false },
467+
},
468+
hooks: { enabled: true, token: hookToken, path: "/hooks" },
466469
},
467-
hooks: { enabled: true, token: hookToken, path: "/hooks" },
468-
},
469-
options.config,
470-
),
471-
);
470+
options.config,
471+
),
472+
);
473+
} catch (error) {
474+
// Config staging can fail before the instance exposes its cleanup handle.
475+
await state.cleanup();
476+
throw error;
477+
}
472478

473479
const stdout = createBoundedStringLog();
474480
const stderr = createBoundedStringLog();

0 commit comments

Comments
 (0)