test(tui): cover gateway auth fallbacks and dedupe env setup

This commit is contained in:
Peter Steinberger
2026-02-21 18:35:47 +00:00
parent ec8288e9b8
commit 2a0ea7cb97

View File

@@ -1,13 +1,11 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { captureEnv, withEnv } from "../test-utils/env.js";
const loadConfig = vi.fn();
const resolveGatewayPort = vi.fn();
const pickPrimaryTailnetIPv4 = vi.fn();
const pickPrimaryLanIPv4 = vi.fn();
const originalEnvToken = process.env.OPENCLAW_GATEWAY_TOKEN;
const originalEnvPassword = process.env.OPENCLAW_GATEWAY_PASSWORD;
vi.mock("../config/config.js", async (importOriginal) => {
const actual = await importOriginal<typeof import("../config/config.js")>();
return {
@@ -34,7 +32,10 @@ vi.mock("../gateway/net.js", async (importOriginal) => {
const { resolveGatewayConnection } = await import("./gateway-chat.js");
describe("resolveGatewayConnection", () => {
let envSnapshot: ReturnType<typeof captureEnv>;
beforeEach(() => {
envSnapshot = captureEnv(["OPENCLAW_GATEWAY_TOKEN", "OPENCLAW_GATEWAY_PASSWORD"]);
loadConfig.mockReset();
resolveGatewayPort.mockReset();
pickPrimaryTailnetIPv4.mockReset();
@@ -47,17 +48,7 @@ describe("resolveGatewayConnection", () => {
});
afterEach(() => {
if (originalEnvToken === undefined) {
delete process.env.OPENCLAW_GATEWAY_TOKEN;
} else {
process.env.OPENCLAW_GATEWAY_TOKEN = originalEnvToken;
}
if (originalEnvPassword === undefined) {
delete process.env.OPENCLAW_GATEWAY_PASSWORD;
} else {
process.env.OPENCLAW_GATEWAY_PASSWORD = originalEnvPassword;
}
envSnapshot.restore();
});
it("throws when url override is missing explicit credentials", () => {
@@ -112,4 +103,34 @@ describe("resolveGatewayConnection", () => {
expect(result.url).toBe("ws://127.0.0.1:18800");
});
it("uses OPENCLAW_GATEWAY_TOKEN for local mode", () => {
loadConfig.mockReturnValue({ gateway: { mode: "local" } });
withEnv({ OPENCLAW_GATEWAY_TOKEN: "env-token" }, () => {
const result = resolveGatewayConnection({});
expect(result.token).toBe("env-token");
});
});
it("falls back to config auth token when env token is missing", () => {
loadConfig.mockReturnValue({ gateway: { mode: "local", auth: { token: "config-token" } } });
const result = resolveGatewayConnection({});
expect(result.token).toBe("config-token");
});
it("prefers OPENCLAW_GATEWAY_PASSWORD over remote password fallback", () => {
loadConfig.mockReturnValue({
gateway: {
mode: "remote",
remote: { url: "wss://remote.example/ws", token: "remote-token", password: "remote-pass" },
},
});
withEnv({ OPENCLAW_GATEWAY_PASSWORD: "env-pass" }, () => {
const result = resolveGatewayConnection({});
expect(result.password).toBe("env-pass");
});
});
});