mirror of
https://github.com/openclaw/openclaw.git
synced 2026-05-08 06:31:24 +00:00
perf(test): speed up browser test suites
This commit is contained in:
@@ -1,53 +1,19 @@
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { createServer } from "node:http";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { deleteBridgeAuthForPort, setBridgeAuthForPort } from "./bridge-auth-registry.js";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { __test } from "./client-fetch.js";
|
||||
|
||||
describe("fetchBrowserJson loopback auth (bridge auth registry)", () => {
|
||||
afterEach(() => {
|
||||
vi.resetModules();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("falls back to per-port bridge auth when config auth is not available", async () => {
|
||||
vi.doMock("../config/config.js", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("../config/config.js")>();
|
||||
return {
|
||||
...original,
|
||||
loadConfig: () => ({}),
|
||||
};
|
||||
const port = 18765;
|
||||
const getBridgeAuthForPort = vi.fn((candidate: number) =>
|
||||
candidate === port ? { token: "registry-token" } : undefined,
|
||||
);
|
||||
const init = __test.withLoopbackBrowserAuth(`http://127.0.0.1:${port}/`, undefined, {
|
||||
loadConfig: () => ({}),
|
||||
resolveBrowserControlAuth: () => ({}),
|
||||
getBridgeAuthForPort,
|
||||
});
|
||||
|
||||
const server = createServer((req, res) => {
|
||||
const auth = String(req.headers.authorization ?? "").trim();
|
||||
if (auth !== "Bearer registry-token") {
|
||||
res.statusCode = 401;
|
||||
res.setHeader("Content-Type", "text/plain; charset=utf-8");
|
||||
res.end("Unauthorized");
|
||||
return;
|
||||
}
|
||||
res.statusCode = 200;
|
||||
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
||||
res.end(JSON.stringify({ ok: true }));
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(0, "127.0.0.1", () => resolve());
|
||||
});
|
||||
|
||||
const port = (server.address() as AddressInfo).port;
|
||||
setBridgeAuthForPort(port, { token: "registry-token" });
|
||||
|
||||
try {
|
||||
const { fetchBrowserJson } = await import("./client-fetch.js");
|
||||
const result = await fetchBrowserJson<{ ok: boolean }>(`http://127.0.0.1:${port}/`, {
|
||||
timeoutMs: 2000,
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
} finally {
|
||||
deleteBridgeAuthForPort(port);
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
const headers = new Headers(init.headers ?? {});
|
||||
expect(headers.get("authorization")).toBe("Bearer registry-token");
|
||||
expect(getBridgeAuthForPort).toHaveBeenCalledWith(port);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,6 +8,12 @@ import {
|
||||
} from "./control-service.js";
|
||||
import { createBrowserRouteDispatcher } from "./routes/dispatcher.js";
|
||||
|
||||
type LoopbackBrowserAuthDeps = {
|
||||
loadConfig: typeof loadConfig;
|
||||
resolveBrowserControlAuth: typeof resolveBrowserControlAuth;
|
||||
getBridgeAuthForPort: typeof getBridgeAuthForPort;
|
||||
};
|
||||
|
||||
function isAbsoluteHttp(url: string): boolean {
|
||||
return /^https?:\/\//i.test(url.trim());
|
||||
}
|
||||
@@ -21,9 +27,10 @@ function isLoopbackHttpUrl(url: string): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
function withLoopbackBrowserAuth(
|
||||
function withLoopbackBrowserAuthImpl(
|
||||
url: string,
|
||||
init: (RequestInit & { timeoutMs?: number }) | undefined,
|
||||
deps: LoopbackBrowserAuthDeps,
|
||||
): RequestInit & { timeoutMs?: number } {
|
||||
const headers = new Headers(init?.headers ?? {});
|
||||
if (headers.has("authorization") || headers.has("x-openclaw-password")) {
|
||||
@@ -34,8 +41,8 @@ function withLoopbackBrowserAuth(
|
||||
}
|
||||
|
||||
try {
|
||||
const cfg = loadConfig();
|
||||
const auth = resolveBrowserControlAuth(cfg);
|
||||
const cfg = deps.loadConfig();
|
||||
const auth = deps.resolveBrowserControlAuth(cfg);
|
||||
if (auth.token) {
|
||||
headers.set("Authorization", `Bearer ${auth.token}`);
|
||||
return { ...init, headers };
|
||||
@@ -58,7 +65,7 @@ function withLoopbackBrowserAuth(
|
||||
: parsed.protocol === "https:"
|
||||
? 443
|
||||
: 80;
|
||||
const bridgeAuth = getBridgeAuthForPort(port);
|
||||
const bridgeAuth = deps.getBridgeAuthForPort(port);
|
||||
if (bridgeAuth?.token) {
|
||||
headers.set("Authorization", `Bearer ${bridgeAuth.token}`);
|
||||
} else if (bridgeAuth?.password) {
|
||||
@@ -71,6 +78,17 @@ function withLoopbackBrowserAuth(
|
||||
return { ...init, headers };
|
||||
}
|
||||
|
||||
function withLoopbackBrowserAuth(
|
||||
url: string,
|
||||
init: (RequestInit & { timeoutMs?: number }) | undefined,
|
||||
): RequestInit & { timeoutMs?: number } {
|
||||
return withLoopbackBrowserAuthImpl(url, init, {
|
||||
loadConfig,
|
||||
resolveBrowserControlAuth,
|
||||
getBridgeAuthForPort,
|
||||
});
|
||||
}
|
||||
|
||||
function enhanceBrowserFetchError(url: string, err: unknown, timeoutMs: number): Error {
|
||||
const hint = isAbsoluteHttp(url)
|
||||
? "If this is a sandboxed session, ensure the sandbox browser is running and try again."
|
||||
@@ -215,3 +233,7 @@ export async function fetchBrowserJson<T>(
|
||||
throw enhanceBrowserFetchError(url, err, timeoutMs);
|
||||
}
|
||||
}
|
||||
|
||||
export const __test = {
|
||||
withLoopbackBrowserAuth: withLoopbackBrowserAuthImpl,
|
||||
};
|
||||
|
||||
@@ -17,30 +17,26 @@ function buildConfig() {
|
||||
};
|
||||
}
|
||||
|
||||
vi.mock("../config/config.js", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("../config/config.js")>();
|
||||
return {
|
||||
...actual,
|
||||
createConfigIO: () => ({
|
||||
loadConfig: () => {
|
||||
// Always return fresh config for createConfigIO to simulate fresh disk read
|
||||
return buildConfig();
|
||||
},
|
||||
}),
|
||||
vi.mock("../config/config.js", () => ({
|
||||
createConfigIO: () => ({
|
||||
loadConfig: () => {
|
||||
// simulate stale loadConfig that doesn't see updates unless cache cleared
|
||||
if (!cachedConfig) {
|
||||
cachedConfig = buildConfig();
|
||||
}
|
||||
return cachedConfig;
|
||||
// Always return fresh config for createConfigIO to simulate fresh disk read
|
||||
return buildConfig();
|
||||
},
|
||||
clearConfigCache: vi.fn(() => {
|
||||
// Clear the simulated cache
|
||||
cachedConfig = null;
|
||||
}),
|
||||
writeConfigFile: vi.fn(async () => {}),
|
||||
};
|
||||
});
|
||||
}),
|
||||
loadConfig: () => {
|
||||
// simulate stale loadConfig that doesn't see updates unless cache cleared
|
||||
if (!cachedConfig) {
|
||||
cachedConfig = buildConfig();
|
||||
}
|
||||
return cachedConfig;
|
||||
},
|
||||
clearConfigCache: vi.fn(() => {
|
||||
// Clear the simulated cache
|
||||
cachedConfig = null;
|
||||
}),
|
||||
writeConfigFile: vi.fn(async () => {}),
|
||||
}));
|
||||
|
||||
vi.mock("./chrome.js", () => ({
|
||||
isChromeCdpReady: vi.fn(async () => false),
|
||||
@@ -72,8 +68,34 @@ vi.mock("../media/store.js", () => ({
|
||||
}));
|
||||
|
||||
describe("server-context hot-reload profiles", () => {
|
||||
let modulesPromise: Promise<{
|
||||
createBrowserRouteContext: typeof import("./server-context.js").createBrowserRouteContext;
|
||||
resolveBrowserConfig: typeof import("./config.js").resolveBrowserConfig;
|
||||
loadConfig: typeof import("../config/config.js").loadConfig;
|
||||
clearConfigCache: typeof import("../config/config.js").clearConfigCache;
|
||||
}> | null = null;
|
||||
|
||||
const getModules = async () => {
|
||||
if (!modulesPromise) {
|
||||
modulesPromise = (async () => {
|
||||
// Avoid parallel imports here; Vitest mock factories use async importOriginal
|
||||
// and parallel loading can observe partially-initialized modules.
|
||||
const configMod = await import("../config/config.js");
|
||||
const config = await import("./config.js");
|
||||
const serverContext = await import("./server-context.js");
|
||||
return {
|
||||
createBrowserRouteContext: serverContext.createBrowserRouteContext,
|
||||
resolveBrowserConfig: config.resolveBrowserConfig,
|
||||
loadConfig: configMod.loadConfig,
|
||||
clearConfigCache: configMod.clearConfigCache,
|
||||
};
|
||||
})();
|
||||
}
|
||||
return await modulesPromise;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
vi.clearAllMocks();
|
||||
cfgProfiles = {
|
||||
openclaw: { cdpPort: 18800, color: "#FF4500" },
|
||||
};
|
||||
@@ -81,11 +103,10 @@ describe("server-context hot-reload profiles", () => {
|
||||
});
|
||||
|
||||
it("forProfile hot-reloads newly added profiles from config", async () => {
|
||||
// Start with only openclaw profile
|
||||
const { createBrowserRouteContext } = await import("./server-context.js");
|
||||
const { resolveBrowserConfig } = await import("./config.js");
|
||||
const { loadConfig } = await import("../config/config.js");
|
||||
const { createBrowserRouteContext, resolveBrowserConfig, loadConfig, clearConfigCache } =
|
||||
await getModules();
|
||||
|
||||
// Start with only openclaw profile
|
||||
// 1. Prime the cache by calling loadConfig() first
|
||||
const cfg = loadConfig();
|
||||
const resolved = resolveBrowserConfig(cfg.browser, cfg);
|
||||
@@ -129,14 +150,11 @@ describe("server-context hot-reload profiles", () => {
|
||||
expect(stillStaleCfg.browser.profiles.desktop).toBeUndefined();
|
||||
|
||||
// Verify clearConfigCache was not called
|
||||
const { clearConfigCache } = await import("../config/config.js");
|
||||
expect(clearConfigCache).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("forProfile still throws for profiles that don't exist in fresh config", async () => {
|
||||
const { createBrowserRouteContext } = await import("./server-context.js");
|
||||
const { resolveBrowserConfig } = await import("./config.js");
|
||||
const { loadConfig } = await import("../config/config.js");
|
||||
const { createBrowserRouteContext, resolveBrowserConfig, loadConfig } = await getModules();
|
||||
|
||||
const cfg = loadConfig();
|
||||
const resolved = resolveBrowserConfig(cfg.browser, cfg);
|
||||
@@ -157,9 +175,7 @@ describe("server-context hot-reload profiles", () => {
|
||||
});
|
||||
|
||||
it("forProfile refreshes existing profile config after loadConfig cache updates", async () => {
|
||||
const { createBrowserRouteContext } = await import("./server-context.js");
|
||||
const { resolveBrowserConfig } = await import("./config.js");
|
||||
const { loadConfig } = await import("../config/config.js");
|
||||
const { createBrowserRouteContext, resolveBrowserConfig, loadConfig } = await getModules();
|
||||
|
||||
const cfg = loadConfig();
|
||||
const resolved = resolveBrowserConfig(cfg.browser, cfg);
|
||||
@@ -187,9 +203,7 @@ describe("server-context hot-reload profiles", () => {
|
||||
});
|
||||
|
||||
it("listProfiles refreshes config before enumerating profiles", async () => {
|
||||
const { createBrowserRouteContext } = await import("./server-context.js");
|
||||
const { resolveBrowserConfig } = await import("./config.js");
|
||||
const { loadConfig } = await import("../config/config.js");
|
||||
const { createBrowserRouteContext, resolveBrowserConfig, loadConfig } = await getModules();
|
||||
|
||||
const cfg = loadConfig();
|
||||
const resolved = resolveBrowserConfig(cfg.browser, cfg);
|
||||
|
||||
@@ -1,91 +1,46 @@
|
||||
import { createServer, type AddressInfo } from "node:net";
|
||||
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
|
||||
import { fetch as realFetch } from "undici";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { isAuthorizedBrowserRequest } from "./http-auth.js";
|
||||
|
||||
let testPort = 0;
|
||||
let prevGatewayPort: string | undefined;
|
||||
|
||||
vi.mock("../config/config.js", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("../config/config.js")>();
|
||||
return {
|
||||
...actual,
|
||||
loadConfig: () => ({
|
||||
gateway: {
|
||||
auth: {
|
||||
token: "browser-control-secret",
|
||||
},
|
||||
},
|
||||
browser: {
|
||||
enabled: true,
|
||||
defaultProfile: "openclaw",
|
||||
profiles: {
|
||||
openclaw: { cdpPort: testPort + 1, color: "#FF4500" },
|
||||
},
|
||||
},
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("./routes/index.js", () => ({
|
||||
registerBrowserRoutes(app: {
|
||||
get: (
|
||||
path: string,
|
||||
handler: (req: unknown, res: { json: (body: unknown) => void }) => void,
|
||||
) => void;
|
||||
}) {
|
||||
app.get("/", (_req, res) => {
|
||||
res.json({ ok: true });
|
||||
});
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("./server-context.js", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("./server-context.js")>();
|
||||
return {
|
||||
...actual,
|
||||
createBrowserRouteContext: vi.fn(() => ({
|
||||
forProfile: vi.fn(() => ({
|
||||
stopRunningBrowser: vi.fn(async () => {}),
|
||||
})),
|
||||
})),
|
||||
};
|
||||
});
|
||||
let server: ReturnType<typeof createServer> | null = null;
|
||||
let port = 0;
|
||||
|
||||
describe("browser control HTTP auth", () => {
|
||||
beforeEach(async () => {
|
||||
prevGatewayPort = process.env.OPENCLAW_GATEWAY_PORT;
|
||||
|
||||
const probe = createServer();
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
probe.once("error", reject);
|
||||
probe.listen(0, "127.0.0.1", () => resolve());
|
||||
server = createServer((req: IncomingMessage, res: ServerResponse) => {
|
||||
if (!isAuthorizedBrowserRequest(req, { token: "browser-control-secret" })) {
|
||||
res.statusCode = 401;
|
||||
res.setHeader("Content-Type", "text/plain; charset=utf-8");
|
||||
res.end("Unauthorized");
|
||||
return;
|
||||
}
|
||||
res.statusCode = 200;
|
||||
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
||||
res.end(JSON.stringify({ ok: true }));
|
||||
});
|
||||
const addr = probe.address() as AddressInfo;
|
||||
testPort = addr.port;
|
||||
await new Promise<void>((resolve) => probe.close(() => resolve()));
|
||||
|
||||
process.env.OPENCLAW_GATEWAY_PORT = String(testPort - 2);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server?.once("error", reject);
|
||||
server?.listen(0, "127.0.0.1", () => resolve());
|
||||
});
|
||||
const addr = server.address();
|
||||
if (!addr || typeof addr === "string") {
|
||||
throw new Error("server address missing");
|
||||
}
|
||||
port = addr.port;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
if (prevGatewayPort === undefined) {
|
||||
delete process.env.OPENCLAW_GATEWAY_PORT;
|
||||
} else {
|
||||
process.env.OPENCLAW_GATEWAY_PORT = prevGatewayPort;
|
||||
const current = server;
|
||||
server = null;
|
||||
if (!current) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { stopBrowserControlServer } = await import("./server.js");
|
||||
await stopBrowserControlServer();
|
||||
await new Promise<void>((resolve) => current.close(() => resolve()));
|
||||
});
|
||||
|
||||
it("requires bearer auth for standalone browser HTTP routes", async () => {
|
||||
const { startBrowserControlServerFromConfig } = await import("./server.js");
|
||||
const started = await startBrowserControlServerFromConfig();
|
||||
expect(started?.port).toBe(testPort);
|
||||
|
||||
const base = `http://127.0.0.1:${testPort}`;
|
||||
const base = `http://127.0.0.1:${port}`;
|
||||
|
||||
const missingAuth = await realFetch(`${base}/`);
|
||||
expect(missingAuth.status).toBe(401);
|
||||
|
||||
Reference in New Issue
Block a user