Files
openclaw/src/cli/daemon-cli/test-helpers/lifecycle-core-harness.ts
2026-03-22 17:32:20 -07:00

74 lines
2.3 KiB
TypeScript

import { vi } from "vitest";
import type { GatewayService } from "../../../daemon/service.js";
import type { OutputRuntimeEnv } from "../../../runtime.js";
import type { MockFn } from "../../../test-utils/vitest-mock-fn.js";
export const runtimeLogs: string[] = [];
type LifecycleRuntimeHarness = OutputRuntimeEnv & {
error: MockFn<OutputRuntimeEnv["error"]>;
exit: MockFn<OutputRuntimeEnv["exit"]>;
writeStdout: MockFn<(value: string) => void>;
writeJson: MockFn<(value: unknown, space?: number) => void>;
};
type LifecycleServiceHarness = GatewayService & {
install: MockFn<GatewayService["install"]>;
uninstall: MockFn<GatewayService["uninstall"]>;
stop: MockFn<GatewayService["stop"]>;
isLoaded: MockFn<GatewayService["isLoaded"]>;
readCommand: MockFn<GatewayService["readCommand"]>;
readRuntime: MockFn<GatewayService["readRuntime"]>;
restart: MockFn<GatewayService["restart"]>;
};
export const defaultRuntime: LifecycleRuntimeHarness = {
log: (...args: unknown[]) => {
runtimeLogs.push(args.map((arg) => String(arg)).join(" "));
},
error: vi.fn(),
exit: vi.fn((code: number) => {
throw new Error(`__exit__:${code}`);
}),
writeStdout: vi.fn((value: string) => {
runtimeLogs.push(value.endsWith("\n") ? value.slice(0, -1) : value);
}),
writeJson: vi.fn((value: unknown, space = 2) => {
runtimeLogs.push(JSON.stringify(value, null, space > 0 ? space : undefined));
}),
};
export const service: LifecycleServiceHarness = {
label: "TestService",
loadedText: "loaded",
notLoadedText: "not loaded",
install: vi.fn(),
uninstall: vi.fn(),
stop: vi.fn(),
isLoaded: vi.fn(),
readCommand: vi.fn(),
readRuntime: vi.fn(),
restart: vi.fn(),
};
export function resetLifecycleRuntimeLogs() {
runtimeLogs.length = 0;
}
export function resetLifecycleServiceMocks() {
service.isLoaded.mockClear();
service.readCommand.mockClear();
service.restart.mockClear();
service.isLoaded.mockResolvedValue(true);
service.readCommand.mockResolvedValue({ programArguments: [], environment: {} });
service.restart.mockResolvedValue({ outcome: "completed" });
}
export function stubEmptyGatewayEnv() {
vi.unstubAllEnvs();
vi.stubEnv("OPENCLAW_GATEWAY_TOKEN", "");
vi.stubEnv("CLAWDBOT_GATEWAY_TOKEN", "");
vi.stubEnv("OPENCLAW_GATEWAY_URL", "");
vi.stubEnv("CLAWDBOT_GATEWAY_URL", "");
}