mirror of
https://github.com/openclaw/openclaw.git
synced 2026-05-06 08:20:43 +00:00
perf: speed up slow test imports
This commit is contained in:
@@ -1,7 +1,6 @@
|
||||
import { streamSimpleOpenAICompletions, type Model } from "@mariozechner/pi-ai";
|
||||
import type { Model } from "@mariozechner/pi-ai";
|
||||
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ModelProviderConfig } from "../config/config.js";
|
||||
import { withFetchPreconnect } from "../test-utils/fetch-mock.js";
|
||||
import type { AuthProfileStore } from "./auth-profiles.js";
|
||||
import {
|
||||
CUSTOM_LOCAL_AUTH_MARKER,
|
||||
@@ -9,6 +8,26 @@ import {
|
||||
NON_ENV_SECRETREF_MARKER,
|
||||
} from "./model-auth-markers.js";
|
||||
|
||||
vi.mock("../plugins/plugin-registry.js", () => ({
|
||||
loadPluginManifestRegistryForPluginRegistry: () => ({
|
||||
diagnostics: [],
|
||||
plugins: [
|
||||
{
|
||||
origin: "bundled",
|
||||
nonSecretAuthMarkers: ["gcp-vertex-credentials"],
|
||||
},
|
||||
],
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("../plugins/providers.js", () => ({
|
||||
resolveOwningPluginIdsForProvider: () => [],
|
||||
}));
|
||||
|
||||
vi.mock("../plugins/setup-registry.js", () => ({
|
||||
resolvePluginSetupProvider: () => undefined,
|
||||
}));
|
||||
|
||||
vi.mock("../plugins/provider-runtime.js", async () => {
|
||||
const actual = await vi.importActual<typeof import("../plugins/provider-runtime.js")>(
|
||||
"../plugins/provider-runtime.js",
|
||||
@@ -939,33 +958,11 @@ describe("resolveApiKeyForProvider – synthetic local auth for custom providers
|
||||
});
|
||||
|
||||
describe("applyLocalNoAuthHeaderOverride", () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
|
||||
afterEach(() => {
|
||||
globalThis.fetch = originalFetch;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("clears Authorization for synthetic local OpenAI-compatible auth markers", async () => {
|
||||
let capturedAuthorization: string | null | undefined;
|
||||
let capturedXTest: string | null | undefined;
|
||||
let resolveRequest: (() => void) | undefined;
|
||||
const requestSeen = new Promise<void>((resolve) => {
|
||||
resolveRequest = resolve;
|
||||
});
|
||||
globalThis.fetch = withFetchPreconnect(
|
||||
vi.fn(async (_input, init) => {
|
||||
const headers = new Headers(init?.headers);
|
||||
capturedAuthorization = headers.get("Authorization");
|
||||
capturedXTest = headers.get("X-Test");
|
||||
resolveRequest?.();
|
||||
return new Response(JSON.stringify({ error: { message: "unauthorized" } }), {
|
||||
status: 401,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it("marks synthetic local OpenAI-compatible auth so SDK request headers clear Authorization", () => {
|
||||
const model = applyLocalNoAuthHeaderOverride(
|
||||
{
|
||||
id: "local-llm",
|
||||
@@ -987,26 +984,10 @@ describe("applyLocalNoAuthHeaderOverride", () => {
|
||||
},
|
||||
);
|
||||
|
||||
streamSimpleOpenAICompletions(
|
||||
model,
|
||||
{
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: "hello",
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
apiKey: CUSTOM_LOCAL_AUTH_MARKER,
|
||||
},
|
||||
);
|
||||
|
||||
await requestSeen;
|
||||
|
||||
expect(capturedAuthorization).toBeNull();
|
||||
expect(capturedXTest).toBe("1");
|
||||
expect(model.headers).toMatchObject({
|
||||
Authorization: null,
|
||||
"X-Test": "1",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import type { AgentMessage } from "@mariozechner/pi-agent-core";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { buildMemorySystemPromptAddition } from "../../../plugin-sdk/core.js";
|
||||
import { buildMemorySystemPromptAddition } from "../../../context-engine/delegate.js";
|
||||
import {
|
||||
clearMemoryPluginState,
|
||||
registerMemoryPromptSection,
|
||||
|
||||
@@ -185,10 +185,7 @@ export function getHoisted(): AttemptSpawnWorkspaceHoisted {
|
||||
return hoisted;
|
||||
}
|
||||
|
||||
vi.mock("@mariozechner/pi-coding-agent", async () => {
|
||||
const actual = await vi.importActual<typeof import("@mariozechner/pi-coding-agent")>(
|
||||
"@mariozechner/pi-coding-agent",
|
||||
);
|
||||
vi.mock("@mariozechner/pi-coding-agent", () => {
|
||||
function AuthStorage() {}
|
||||
class DefaultResourceLoader {
|
||||
async reload() {}
|
||||
@@ -198,7 +195,6 @@ vi.mock("@mariozechner/pi-coding-agent", async () => {
|
||||
Math.max(1, Math.ceil(JSON.stringify(value ?? "").length / 4));
|
||||
|
||||
return {
|
||||
...actual,
|
||||
AuthStorage,
|
||||
createAgentSession: (...args: unknown[]) => hoisted.createAgentSessionMock(...args),
|
||||
DefaultResourceLoader,
|
||||
|
||||
@@ -8,12 +8,28 @@ let webMedia: typeof import("../../media/web-media.js");
|
||||
let createImageGenerateTool: typeof import("./image-generate-tool.js").createImageGenerateTool;
|
||||
let resolveImageGenerationModelConfigForTool: typeof import("./image-generate-tool.js").resolveImageGenerationModelConfigForTool;
|
||||
|
||||
function hasStubbedImageProviderAuth(providerId: string): boolean {
|
||||
if (providerId === "openai") {
|
||||
return Boolean(process.env.OPENAI_API_KEY?.trim() || process.env.OPENAI_API_KEYS?.trim());
|
||||
}
|
||||
if (providerId === "google") {
|
||||
return Boolean(
|
||||
process.env.GEMINI_API_KEY?.trim() ||
|
||||
process.env.GEMINI_API_KEYS?.trim() ||
|
||||
process.env.GOOGLE_API_KEY?.trim() ||
|
||||
process.env.GOOGLE_API_KEYS?.trim(),
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function stubImageGenerationProviders() {
|
||||
vi.spyOn(imageGenerationRuntime, "listRuntimeImageGenerationProviders").mockReturnValue([
|
||||
{
|
||||
id: "google",
|
||||
defaultModel: "gemini-3.1-flash-image-preview",
|
||||
models: ["gemini-3.1-flash-image-preview", "gemini-3-pro-image-preview"],
|
||||
isConfigured: () => hasStubbedImageProviderAuth("google"),
|
||||
capabilities: {
|
||||
generate: {
|
||||
maxCount: 4,
|
||||
@@ -39,6 +55,7 @@ function stubImageGenerationProviders() {
|
||||
id: "openai",
|
||||
defaultModel: "gpt-image-1",
|
||||
models: ["gpt-image-1"],
|
||||
isConfigured: () => hasStubbedImageProviderAuth("openai"),
|
||||
capabilities: {
|
||||
generate: {
|
||||
maxCount: 4,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { CURRENT_SESSION_VERSION, SessionManager } from "@mariozechner/pi-coding-agent";
|
||||
import type { SessionManager } from "@mariozechner/pi-coding-agent";
|
||||
import { formatErrorMessage } from "../../infra/errors.js";
|
||||
import { emitSessionTranscriptUpdate } from "../../sessions/transcript-events.js";
|
||||
import { extractAssistantVisibleText } from "../../shared/chat-message-content.js";
|
||||
@@ -16,6 +16,14 @@ import { parseSessionThreadInfo } from "./thread-info.js";
|
||||
import { resolveMirroredTranscriptText } from "./transcript-mirror.js";
|
||||
import type { SessionEntry } from "./types.js";
|
||||
|
||||
let piCodingAgentModulePromise: Promise<typeof import("@mariozechner/pi-coding-agent")> | null =
|
||||
null;
|
||||
|
||||
async function loadPiCodingAgentModule(): Promise<typeof import("@mariozechner/pi-coding-agent")> {
|
||||
piCodingAgentModulePromise ??= import("@mariozechner/pi-coding-agent");
|
||||
return await piCodingAgentModulePromise;
|
||||
}
|
||||
|
||||
async function ensureSessionHeader(params: {
|
||||
sessionFile: string;
|
||||
sessionId: string;
|
||||
@@ -23,6 +31,7 @@ async function ensureSessionHeader(params: {
|
||||
if (fs.existsSync(params.sessionFile)) {
|
||||
return;
|
||||
}
|
||||
const { CURRENT_SESSION_VERSION } = await loadPiCodingAgentModule();
|
||||
await fs.promises.mkdir(path.dirname(params.sessionFile), { recursive: true });
|
||||
const header = {
|
||||
type: "session",
|
||||
@@ -266,6 +275,7 @@ export async function appendExactAssistantMessageToSessionTranscript(params: {
|
||||
...params.message,
|
||||
...(explicitIdempotencyKey ? { idempotencyKey: explicitIdempotencyKey } : {}),
|
||||
} as Parameters<SessionManager["appendMessage"]>[0];
|
||||
const { SessionManager } = await loadPiCodingAgentModule();
|
||||
const sessionManager = SessionManager.open(sessionFile);
|
||||
const messageId = sessionManager.appendMessage(message);
|
||||
|
||||
|
||||
@@ -342,5 +342,3 @@ vi.mock("/src/plugins/runtime/runtime-web-channel-plugin.js", () => ({
|
||||
|
||||
process.env.OPENCLAW_SKIP_CHANNELS = "1";
|
||||
process.env.OPENCLAW_SKIP_CRON = "1";
|
||||
process.env.OPENCLAW_SKIP_CHANNELS = "1";
|
||||
process.env.OPENCLAW_SKIP_CRON = "1";
|
||||
|
||||
Reference in New Issue
Block a user