refactor(test): simplify env scoping in exec and usage tests

This commit is contained in:
Peter Steinberger
2026-02-21 13:17:06 +00:00
parent aff272ec35
commit ae70bf4dca
2 changed files with 40 additions and 43 deletions

View File

@@ -2,7 +2,7 @@ import fs from "node:fs";
import os from "node:os"; import os from "node:os";
import path from "node:path"; import path from "node:path";
import { beforeEach, describe, expect, it, vi } from "vitest"; import { beforeEach, describe, expect, it, vi } from "vitest";
import { captureEnv } from "../../test-utils/env.js"; import { withEnvAsync } from "../../test-utils/env.js";
vi.mock("../../config/config.js", () => { vi.mock("../../config/config.js", () => {
return { return {
@@ -143,48 +143,49 @@ describe("sessions.usage", () => {
it("resolves store entries by sessionId when queried via discovered agent-prefixed key", async () => { it("resolves store entries by sessionId when queried via discovered agent-prefixed key", async () => {
const storeKey = "agent:opus:slack:dm:u123"; const storeKey = "agent:opus:slack:dm:u123";
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-usage-test-")); const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-usage-test-"));
const envSnapshot = captureEnv(["OPENCLAW_STATE_DIR"]);
process.env.OPENCLAW_STATE_DIR = stateDir;
try { try {
const agentSessionsDir = path.join(stateDir, "agents", "opus", "sessions"); await withEnvAsync({ OPENCLAW_STATE_DIR: stateDir }, async () => {
fs.mkdirSync(agentSessionsDir, { recursive: true }); const agentSessionsDir = path.join(stateDir, "agents", "opus", "sessions");
const sessionFile = path.join(agentSessionsDir, "s-opus.jsonl"); fs.mkdirSync(agentSessionsDir, { recursive: true });
fs.writeFileSync(sessionFile, "", "utf-8"); const sessionFile = path.join(agentSessionsDir, "s-opus.jsonl");
fs.writeFileSync(sessionFile, "", "utf-8");
// Swap the store mock for this test: the canonical key differs from the discovered key // Swap the store mock for this test: the canonical key differs from the discovered key
// but points at the same sessionId. // but points at the same sessionId.
vi.mocked(loadCombinedSessionStoreForGateway).mockReturnValue({ vi.mocked(loadCombinedSessionStoreForGateway).mockReturnValue({
storePath: "(multiple)", storePath: "(multiple)",
store: { store: {
[storeKey]: { [storeKey]: {
sessionId: "s-opus", sessionId: "s-opus",
sessionFile: "s-opus.jsonl", sessionFile: "s-opus.jsonl",
label: "Named session", label: "Named session",
updatedAt: 999, updatedAt: 999,
},
}, },
}, });
});
// Query via discovered key: agent:<id>:<sessionId> // Query via discovered key: agent:<id>:<sessionId>
const respond = await runSessionsUsage({ const respond = await runSessionsUsage({
startDate: "2026-02-01", startDate: "2026-02-01",
endDate: "2026-02-02", endDate: "2026-02-02",
key: "agent:opus:s-opus", key: "agent:opus:s-opus",
limit: 10, limit: 10,
}); });
expect(respond).toHaveBeenCalledTimes(1); expect(respond).toHaveBeenCalledTimes(1);
expect(respond.mock.calls[0]?.[0]).toBe(true); expect(respond.mock.calls[0]?.[0]).toBe(true);
const result = respond.mock.calls[0]?.[1] as unknown as { sessions: Array<{ key: string }> }; const result = respond.mock.calls[0]?.[1] as unknown as {
expect(result.sessions).toHaveLength(1); sessions: Array<{ key: string }>;
expect(result.sessions[0]?.key).toBe(storeKey); };
expect(vi.mocked(loadSessionCostSummary)).toHaveBeenCalled(); expect(result.sessions).toHaveLength(1);
expect( expect(result.sessions[0]?.key).toBe(storeKey);
vi.mocked(loadSessionCostSummary).mock.calls.some((call) => call[0]?.agentId === "opus"), expect(vi.mocked(loadSessionCostSummary)).toHaveBeenCalled();
).toBe(true); expect(
vi.mocked(loadSessionCostSummary).mock.calls.some((call) => call[0]?.agentId === "opus"),
).toBe(true);
});
} finally { } finally {
envSnapshot.restore();
fs.rmSync(stateDir, { recursive: true, force: true }); fs.rmSync(stateDir, { recursive: true, force: true });
} }
}); });

View File

@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { captureEnv } from "../test-utils/env.js"; import { withEnvAsync } from "../test-utils/env.js";
import { runCommandWithTimeout, shouldSpawnWithShell } from "./exec.js"; import { runCommandWithTimeout, shouldSpawnWithShell } from "./exec.js";
describe("runCommandWithTimeout", () => { describe("runCommandWithTimeout", () => {
@@ -13,9 +13,7 @@ describe("runCommandWithTimeout", () => {
}); });
it("merges custom env with process.env", async () => { it("merges custom env with process.env", async () => {
const envSnapshot = captureEnv(["OPENCLAW_BASE_ENV"]); await withEnvAsync({ OPENCLAW_BASE_ENV: "base" }, async () => {
process.env.OPENCLAW_BASE_ENV = "base";
try {
const result = await runCommandWithTimeout( const result = await runCommandWithTimeout(
[ [
process.execPath, process.execPath,
@@ -31,9 +29,7 @@ describe("runCommandWithTimeout", () => {
expect(result.code).toBe(0); expect(result.code).toBe(0);
expect(result.stdout).toBe("base|ok"); expect(result.stdout).toBe("base|ok");
expect(result.termination).toBe("exit"); expect(result.termination).toBe("exit");
} finally { });
envSnapshot.restore();
}
}); });
it("kills command when no output timeout elapses", async () => { it("kills command when no output timeout elapses", async () => {