|
| 1 | +import nodeFs from "node:fs"; |
1 | 2 | import fs from "node:fs/promises"; |
2 | 3 | import path from "node:path"; |
3 | 4 | import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; |
| 5 | +import type { OpenClawConfig } from "../config/types.openclaw.js"; |
4 | 6 | import type { RuntimeEnv } from "../runtime.js"; |
5 | 7 | import { makeTempWorkspace } from "../test-helpers/workspace.js"; |
6 | 8 | import { captureEnv } from "../test-utils/env.js"; |
@@ -46,6 +48,70 @@ let waitForGatewayReachableMock:
|
46 | 48 | }>) |
47 | 49 | | undefined; |
48 | 50 | |
| 51 | +function resolveTestConfigPath() { |
| 52 | +const override = process.env.OPENCLAW_CONFIG_PATH?.trim(); |
| 53 | +if (override) { |
| 54 | +return override; |
| 55 | +} |
| 56 | +const stateDir = process.env.OPENCLAW_STATE_DIR?.trim(); |
| 57 | +if (!stateDir) { |
| 58 | +throw new Error("OPENCLAW_STATE_DIR must be set before config IO in this test"); |
| 59 | +} |
| 60 | +return path.join(stateDir, "openclaw.json"); |
| 61 | +} |
| 62 | + |
| 63 | +vi.mock("../config/io.js", () => ({ |
| 64 | +createConfigIO: () => ({ |
| 65 | +configPath: resolveTestConfigPath(), |
| 66 | +}), |
| 67 | +loadConfig: () => { |
| 68 | +try { |
| 69 | +return JSON.parse(nodeFs.readFileSync(resolveTestConfigPath(), "utf-8")); |
| 70 | +} catch (err) { |
| 71 | +if ((err as NodeJS.ErrnoException).code === "ENOENT") { |
| 72 | +return {}; |
| 73 | +} |
| 74 | +throw err; |
| 75 | +} |
| 76 | +}, |
| 77 | +readConfigFileSnapshot: async () => { |
| 78 | +const configPath = resolveTestConfigPath(); |
| 79 | +try { |
| 80 | +const raw = await fs.readFile(configPath, "utf-8"); |
| 81 | +const config = JSON.parse(raw); |
| 82 | +return { |
| 83 | +exists: true, |
| 84 | +valid: true, |
| 85 | + config, |
| 86 | +sourceConfig: config, |
| 87 | + raw, |
| 88 | +hash: "test-config-hash", |
| 89 | +}; |
| 90 | +} catch (err) { |
| 91 | +if ((err as NodeJS.ErrnoException).code !== "ENOENT") { |
| 92 | +throw err; |
| 93 | +} |
| 94 | +return { |
| 95 | +exists: false, |
| 96 | +valid: true, |
| 97 | +config: {}, |
| 98 | +sourceConfig: {}, |
| 99 | +raw: null, |
| 100 | +hash: undefined, |
| 101 | +}; |
| 102 | +} |
| 103 | +}, |
| 104 | +})); |
| 105 | + |
| 106 | +vi.mock("../config/config.js", () => ({ |
| 107 | +replaceConfigFile: async ({ nextConfig }: { nextConfig: OpenClawConfig }) => { |
| 108 | +const configPath = resolveTestConfigPath(); |
| 109 | +await fs.mkdir(path.dirname(configPath), { recursive: true }); |
| 110 | +await fs.writeFile(configPath, `${JSON.stringify(nextConfig, null, 2)}\n`, "utf-8"); |
| 111 | +}, |
| 112 | +resolveGatewayPort: (cfg: OpenClawConfig) => cfg.gateway?.port ?? 18789, |
| 113 | +})); |
| 114 | + |
49 | 115 | vi.mock("../gateway/client.js", () => ({ |
50 | 116 | GatewayClient: class { |
51 | 117 | params: { |
|