chore: Fix types in tests 36/N.

This commit is contained in:
cpojer
2026-02-17 15:46:48 +09:00
parent 2a4ca7671e
commit 7b31e8fc59
14 changed files with 86 additions and 42 deletions

View File

@@ -26,8 +26,8 @@ describe("voyage embedding provider", () => {
}); });
it("configures client with correct defaults and headers", async () => { it("configures client with correct defaults and headers", async () => {
const fetchMock = createFetchMock(); const fetchMock = createFetchMock() as ReturnType<typeof vi.fn>;
vi.stubGlobal("fetch", fetchMock); vi.stubGlobal("fetch", fetchMock as unknown as typeof fetch);
vi.mocked(authModule.resolveApiKeyForProvider).mockResolvedValue({ vi.mocked(authModule.resolveApiKeyForProvider).mockResolvedValue({
apiKey: "voyage-key-123", apiKey: "voyage-key-123",
@@ -64,8 +64,8 @@ describe("voyage embedding provider", () => {
}); });
it("respects remote overrides for baseUrl and apiKey", async () => { it("respects remote overrides for baseUrl and apiKey", async () => {
const fetchMock = createFetchMock(); const fetchMock = createFetchMock() as ReturnType<typeof vi.fn>;
vi.stubGlobal("fetch", fetchMock); vi.stubGlobal("fetch", fetchMock as unknown as typeof fetch);
const result = await createVoyageEmbeddingProvider({ const result = await createVoyageEmbeddingProvider({
config: {} as never, config: {} as never,
@@ -96,8 +96,8 @@ describe("voyage embedding provider", () => {
json: async () => ({ json: async () => ({
data: [{ embedding: [0.1, 0.2] }, { embedding: [0.3, 0.4] }], data: [{ embedding: [0.1, 0.2] }, { embedding: [0.3, 0.4] }],
}), }),
})) as unknown as typeof fetch; })) as ReturnType<typeof vi.fn>;
vi.stubGlobal("fetch", fetchMock); vi.stubGlobal("fetch", fetchMock as unknown as typeof fetch);
vi.mocked(authModule.resolveApiKeyForProvider).mockResolvedValue({ vi.mocked(authModule.resolveApiKeyForProvider).mockResolvedValue({
apiKey: "voyage-key-123", apiKey: "voyage-key-123",

View File

@@ -2,6 +2,7 @@ import fs from "node:fs/promises";
import os from "node:os"; import os from "node:os";
import path from "node:path"; import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { OpenClawConfig } from "../config/config.js";
import { getMemorySearchManager, type MemoryIndexManager } from "./index.js"; import { getMemorySearchManager, type MemoryIndexManager } from "./index.js";
import { createOpenAIEmbeddingProviderMock } from "./test-embeddings-mock.js"; import { createOpenAIEmbeddingProviderMock } from "./test-embeddings-mock.js";
@@ -53,21 +54,25 @@ describe("memory search async sync", () => {
}, },
list: [{ id: "main", default: true }], list: [{ id: "main", default: true }],
}, },
}; } as OpenClawConfig;
const result = await getMemorySearchManager({ cfg, agentId: "main" }); const result = await getMemorySearchManager({ cfg, agentId: "main" });
expect(result.manager).not.toBeNull(); expect(result.manager).not.toBeNull();
if (!result.manager) { if (!result.manager) {
throw new Error("manager missing"); throw new Error("manager missing");
} }
manager = result.manager; manager = result.manager as unknown as MemoryIndexManager;
const pending = new Promise<void>(() => {}); const pending = new Promise<void>(() => {});
(manager as unknown as { sync: () => Promise<void> }).sync = vi.fn(async () => pending); (manager as unknown as { sync: () => Promise<void> }).sync = vi.fn(async () => pending);
const resolved = await new Promise<boolean>((resolve, reject) => { const resolved = await new Promise<boolean>((resolve, reject) => {
const timeout = setTimeout(() => resolve(false), 1000); const timeout = setTimeout(() => resolve(false), 1000);
void manager const activeManager = manager;
if (!activeManager) {
throw new Error("manager missing");
}
void activeManager
.search("hello") .search("hello")
.then(() => { .then(() => {
clearTimeout(timeout); clearTimeout(timeout);

View File

@@ -2,6 +2,7 @@ import fs from "node:fs/promises";
import os from "node:os"; import os from "node:os";
import path from "node:path"; import path from "node:path";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import type { OpenClawConfig } from "../config/config.js";
import { getEmbedBatchMock, resetEmbeddingMocks } from "./embedding.test-mocks.js"; import { getEmbedBatchMock, resetEmbeddingMocks } from "./embedding.test-mocks.js";
import type { MemoryIndexManager } from "./index.js"; import type { MemoryIndexManager } from "./index.js";
import { getRequiredMemoryIndexManager } from "./test-manager-helpers.js"; import { getRequiredMemoryIndexManager } from "./test-manager-helpers.js";
@@ -68,7 +69,7 @@ describe("memory manager atomic reindex", () => {
}, },
list: [{ id: "main", default: true }], list: [{ id: "main", default: true }],
}, },
}; } as OpenClawConfig;
manager = await getRequiredMemoryIndexManager({ cfg, agentId: "main" }); manager = await getRequiredMemoryIndexManager({ cfg, agentId: "main" });

View File

@@ -2,11 +2,12 @@ import fs from "node:fs/promises";
import os from "node:os"; import os from "node:os";
import path from "node:path"; import path from "node:path";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import type { OpenClawConfig } from "../config/config.js";
import { getMemorySearchManager, type MemoryIndexManager } from "./index.js"; import { getMemorySearchManager, type MemoryIndexManager } from "./index.js";
import { createOpenAIEmbeddingProviderMock } from "./test-embeddings-mock.js"; import { createOpenAIEmbeddingProviderMock } from "./test-embeddings-mock.js";
import "./test-runtime-mocks.js"; import "./test-runtime-mocks.js";
const embedBatch = vi.fn(async () => []); const embedBatch = vi.fn(async (_texts: string[]) => [] as number[][]);
const embedQuery = vi.fn(async () => [0.5, 0.5, 0.5]); const embedQuery = vi.fn(async () => [0.5, 0.5, 0.5]);
vi.mock("./embeddings.js", () => ({ vi.mock("./embeddings.js", () => ({
@@ -110,7 +111,7 @@ describe("memory indexing with OpenAI batches", () => {
return { fetchMock, state }; return { fetchMock, state };
} }
function createBatchCfg() { function createBatchCfg(): OpenClawConfig {
return { return {
agents: { agents: {
defaults: { defaults: {
@@ -126,7 +127,7 @@ describe("memory indexing with OpenAI batches", () => {
}, },
list: [{ id: "main", default: true }], list: [{ id: "main", default: true }],
}, },
}; } as OpenClawConfig;
} }
beforeAll(async () => { beforeAll(async () => {
@@ -141,7 +142,7 @@ describe("memory indexing with OpenAI batches", () => {
if (!result.manager) { if (!result.manager) {
throw new Error("manager missing"); throw new Error("manager missing");
} }
manager = result.manager; manager = result.manager as unknown as MemoryIndexManager;
}); });
afterAll(async () => { afterAll(async () => {

View File

@@ -43,7 +43,10 @@ describe("memory embedding batches", () => {
}); });
const status = managerLarge.status(); const status = managerLarge.status();
const totalTexts = embedBatch.mock.calls.reduce((sum, call) => sum + (call[0]?.length ?? 0), 0); const totalTexts = embedBatch.mock.calls.reduce(
(sum: number, call: unknown[]) => sum + ((call[0] as string[] | undefined)?.length ?? 0),
0,
);
expect(totalTexts).toBe(status.chunks); expect(totalTexts).toBe(status.chunks);
expect(embedBatch.mock.calls.length).toBeGreaterThan(1); expect(embedBatch.mock.calls.length).toBeGreaterThan(1);
expect(updates.length).toBeGreaterThan(0); expect(updates.length).toBeGreaterThan(0);
@@ -112,7 +115,7 @@ describe("memory embedding batches", () => {
await fs.writeFile(path.join(memoryDir, "2026-01-07.md"), "\n\n\n"); await fs.writeFile(path.join(memoryDir, "2026-01-07.md"), "\n\n\n");
await managerSmall.sync({ reason: "test" }); await managerSmall.sync({ reason: "test" });
const inputs = embedBatch.mock.calls.flatMap((call) => call[0] ?? []); const inputs = embedBatch.mock.calls.flatMap((call: unknown[]) => (call[0] as string[]) ?? []);
expect(inputs).not.toContain(""); expect(inputs).not.toContain("");
}); });
}); });

View File

@@ -2,6 +2,7 @@ import fs from "node:fs/promises";
import os from "node:os"; import os from "node:os";
import path from "node:path"; import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { OpenClawConfig } from "../config/config.js";
import { getEmbedBatchMock, resetEmbeddingMocks } from "./embedding.test-mocks.js"; import { getEmbedBatchMock, resetEmbeddingMocks } from "./embedding.test-mocks.js";
import type { MemoryIndexManager } from "./index.js"; import type { MemoryIndexManager } from "./index.js";
import { getRequiredMemoryIndexManager } from "./test-manager-helpers.js"; import { getRequiredMemoryIndexManager } from "./test-manager-helpers.js";
@@ -53,7 +54,7 @@ describe("memory manager sync failures", () => {
}, },
list: [{ id: "main", default: true }], list: [{ id: "main", default: true }],
}, },
}; } as OpenClawConfig;
manager = await getRequiredMemoryIndexManager({ cfg, agentId: "main" }); manager = await getRequiredMemoryIndexManager({ cfg, agentId: "main" });
const syncSpy = vi.spyOn(manager, "sync"); const syncSpy = vi.spyOn(manager, "sync");

View File

@@ -2,6 +2,7 @@ import fs from "node:fs/promises";
import os from "node:os"; import os from "node:os";
import path from "node:path"; import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { OpenClawConfig } from "../config/config.js";
import { getMemorySearchManager, type MemoryIndexManager } from "./index.js"; import { getMemorySearchManager, type MemoryIndexManager } from "./index.js";
import { buildFileEntry } from "./internal.js"; import { buildFileEntry } from "./internal.js";
@@ -54,14 +55,14 @@ describe("memory vector dedupe", () => {
}, },
list: [{ id: "main", default: true }], list: [{ id: "main", default: true }],
}, },
}; } as OpenClawConfig;
const result = await getMemorySearchManager({ cfg, agentId: "main" }); const result = await getMemorySearchManager({ cfg, agentId: "main" });
expect(result.manager).not.toBeNull(); expect(result.manager).not.toBeNull();
if (!result.manager) { if (!result.manager) {
throw new Error("manager missing"); throw new Error("manager missing");
} }
manager = result.manager; manager = result.manager as unknown as MemoryIndexManager;
const db = ( const db = (
manager as unknown as { manager as unknown as {

View File

@@ -2,6 +2,7 @@ import fs from "node:fs/promises";
import os from "node:os"; import os from "node:os";
import path from "node:path"; import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest"; import { afterEach, describe, expect, it, vi } from "vitest";
import type { OpenClawConfig } from "../config/config.js";
import { getMemorySearchManager, type MemoryIndexManager } from "./index.js"; import { getMemorySearchManager, type MemoryIndexManager } from "./index.js";
const { watchMock } = vi.hoisted(() => ({ const { watchMock } = vi.hoisted(() => ({
@@ -72,14 +73,14 @@ describe("memory watcher config", () => {
}, },
list: [{ id: "main", default: true }], list: [{ id: "main", default: true }],
}, },
}; } as OpenClawConfig;
const result = await getMemorySearchManager({ cfg, agentId: "main" }); const result = await getMemorySearchManager({ cfg, agentId: "main" });
expect(result.manager).not.toBeNull(); expect(result.manager).not.toBeNull();
if (!result.manager) { if (!result.manager) {
throw new Error("manager missing"); throw new Error("manager missing");
} }
manager = result.manager; manager = result.manager as unknown as MemoryIndexManager;
expect(watchMock).toHaveBeenCalledTimes(1); expect(watchMock).toHaveBeenCalledTimes(1);
const [watchedPaths, options] = watchMock.mock.calls[0] as unknown as [ const [watchedPaths, options] = watchMock.mock.calls[0] as unknown as [

View File

@@ -98,7 +98,11 @@ describe("pairing store", () => {
it("regenerates when a generated code collides", async () => { it("regenerates when a generated code collides", async () => {
await withTempStateDir(async () => { await withTempStateDir(async () => {
const spy = vi.spyOn(crypto, "randomInt"); const spy = vi.spyOn(crypto, "randomInt") as unknown as {
mockReturnValue: (value: number) => void;
mockImplementation: (fn: () => number) => void;
mockRestore: () => void;
};
try { try {
spy.mockReturnValue(0); spy.mockReturnValue(0);
const first = await upsertChannelPairingRequest({ const first = await upsertChannelPairingRequest({

View File

@@ -8,7 +8,7 @@
import { beforeEach, describe, expect, it } from "vitest"; import { beforeEach, describe, expect, it } from "vitest";
import { createHookRunner } from "./hooks.js"; import { createHookRunner } from "./hooks.js";
import { createEmptyPluginRegistry, type PluginRegistry } from "./registry.js"; import { createEmptyPluginRegistry, type PluginRegistry } from "./registry.js";
import type { PluginHookBeforeAgentStartResult, TypedPluginHookRegistration } from "./types.js"; import type { PluginHookBeforeAgentStartResult, PluginHookRegistration } from "./types.js";
function addBeforeAgentStartHook( function addBeforeAgentStartHook(
registry: PluginRegistry, registry: PluginRegistry,
@@ -22,7 +22,7 @@ function addBeforeAgentStartHook(
handler, handler,
priority, priority,
source: "test", source: "test",
} as TypedPluginHookRegistration); } as PluginHookRegistration);
} }
const stubCtx = { const stubCtx = {

View File

@@ -16,7 +16,7 @@ import type {
PluginHookBeforeModelResolveResult, PluginHookBeforeModelResolveResult,
PluginHookBeforePromptBuildEvent, PluginHookBeforePromptBuildEvent,
PluginHookBeforePromptBuildResult, PluginHookBeforePromptBuildResult,
TypedPluginHookRegistration, PluginHookRegistration,
} from "./types.js"; } from "./types.js";
function addBeforeModelResolveHook( function addBeforeModelResolveHook(
@@ -34,7 +34,7 @@ function addBeforeModelResolveHook(
handler, handler,
priority, priority,
source: "test", source: "test",
} as TypedPluginHookRegistration); } as PluginHookRegistration);
} }
function addBeforePromptBuildHook( function addBeforePromptBuildHook(
@@ -52,7 +52,7 @@ function addBeforePromptBuildHook(
handler, handler,
priority, priority,
source: "test", source: "test",
} as TypedPluginHookRegistration); } as PluginHookRegistration);
} }
function addLegacyBeforeAgentStartHook( function addLegacyBeforeAgentStartHook(
@@ -67,7 +67,7 @@ function addLegacyBeforeAgentStartHook(
handler, handler,
priority, priority,
source: "test", source: "test",
} as TypedPluginHookRegistration); } as PluginHookRegistration);
} }
const stubCtx: PluginHookAgentContext = { const stubCtx: PluginHookAgentContext = {

View File

@@ -4,7 +4,7 @@ import { createEmptyPluginRegistry, type PluginRegistry } from "./registry.js";
import type { import type {
PluginHookBeforeModelResolveResult, PluginHookBeforeModelResolveResult,
PluginHookBeforePromptBuildResult, PluginHookBeforePromptBuildResult,
TypedPluginHookRegistration, PluginHookRegistration,
} from "./types.js"; } from "./types.js";
function addTypedHook( function addTypedHook(
@@ -23,7 +23,7 @@ function addTypedHook(
handler, handler,
priority, priority,
source: "test", source: "test",
} as TypedPluginHookRegistration); } as PluginHookRegistration);
} }
describe("phase hooks merger", () => { describe("phase hooks merger", () => {

View File

@@ -423,7 +423,14 @@ describe("installPluginFromDir", () => {
const { runCommandWithTimeout } = await import("../process/exec.js"); const { runCommandWithTimeout } = await import("../process/exec.js");
const run = vi.mocked(runCommandWithTimeout); const run = vi.mocked(runCommandWithTimeout);
run.mockResolvedValue({ code: 0, stdout: "", stderr: "" }); run.mockResolvedValue({
code: 0,
stdout: "",
stderr: "",
signal: null,
killed: false,
termination: "exit",
});
const { installPluginFromDir } = await import("./install.js"); const { installPluginFromDir } = await import("./install.js");
const res = await installPluginFromDir({ const res = await installPluginFromDir({
@@ -468,9 +475,16 @@ describe("installPluginFromNpmSpec", () => {
const packedName = "voice-call-0.0.1.tgz"; const packedName = "voice-call-0.0.1.tgz";
run.mockImplementation(async (argv, opts) => { run.mockImplementation(async (argv, opts) => {
if (argv[0] === "npm" && argv[1] === "pack") { if (argv[0] === "npm" && argv[1] === "pack") {
packTmpDir = String(opts?.cwd ?? ""); packTmpDir = String(typeof opts === "number" ? "" : (opts.cwd ?? ""));
await packToArchive({ pkgDir, outDir: packTmpDir, outName: packedName }); await packToArchive({ pkgDir, outDir: packTmpDir, outName: packedName });
return { code: 0, stdout: `${packedName}\n`, stderr: "", signal: null, killed: false }; return {
code: 0,
stdout: `${packedName}\n`,
stderr: "",
signal: null,
killed: false,
termination: "exit",
};
} }
throw new Error(`unexpected command: ${argv.join(" ")}`); throw new Error(`unexpected command: ${argv.join(" ")}`);
}); });
@@ -493,7 +507,8 @@ describe("installPluginFromNpmSpec", () => {
} }
const [argv, options] = packCall; const [argv, options] = packCall;
expect(argv).toEqual(["npm", "pack", "@openclaw/voice-call@0.0.1", "--ignore-scripts"]); expect(argv).toEqual(["npm", "pack", "@openclaw/voice-call@0.0.1", "--ignore-scripts"]);
expect(options?.env).toMatchObject({ NPM_CONFIG_IGNORE_SCRIPTS: "true" }); const commandOptions = typeof options === "number" ? undefined : options;
expect(commandOptions?.env).toMatchObject({ NPM_CONFIG_IGNORE_SCRIPTS: "true" });
expect(packTmpDir).not.toBe(""); expect(packTmpDir).not.toBe("");
expect(fs.existsSync(packTmpDir)).toBe(false); expect(fs.existsSync(packTmpDir)).toBe(false);

View File

@@ -28,12 +28,12 @@ const noopLogger = {
}; };
type Registered = { type Registered = {
methods: Map<string, (ctx: Record<string, unknown>) => unknown>; methods: Map<string, unknown>;
tools: unknown[]; tools: unknown[];
}; };
function setup(config: Record<string, unknown>): Registered { function setup(config: Record<string, unknown>): Registered {
const methods = new Map<string, (ctx: Record<string, unknown>) => unknown>(); const methods = new Map<string, unknown>();
const tools: unknown[] = []; const tools: unknown[] = [];
plugin.register({ plugin.register({
id: "voice-call", id: "voice-call",
@@ -43,14 +43,16 @@ function setup(config: Record<string, unknown>): Registered {
source: "test", source: "test",
config: {}, config: {},
pluginConfig: config, pluginConfig: config,
runtime: { tts: { textToSpeechTelephony: vi.fn() } }, runtime: { tts: { textToSpeechTelephony: vi.fn() } } as unknown as Parameters<
typeof plugin.register
>[0]["runtime"],
logger: noopLogger, logger: noopLogger,
registerGatewayMethod: (method, handler) => methods.set(method, handler), registerGatewayMethod: (method: string, handler: unknown) => methods.set(method, handler),
registerTool: (tool) => tools.push(tool), registerTool: (tool: unknown) => tools.push(tool),
registerCli: () => {}, registerCli: () => {},
registerService: () => {}, registerService: () => {},
resolvePath: (p: string) => p, resolvePath: (p: string) => p,
}); } as unknown as Parameters<typeof plugin.register>[0]);
return { methods, tools }; return { methods, tools };
} }
@@ -87,7 +89,12 @@ describe("voice-call plugin", () => {
it("initiates a call via voicecall.initiate", async () => { it("initiates a call via voicecall.initiate", async () => {
const { methods } = setup({ provider: "mock" }); const { methods } = setup({ provider: "mock" });
const handler = methods.get("voicecall.initiate"); const handler = methods.get("voicecall.initiate") as
| ((ctx: {
params: Record<string, unknown>;
respond: ReturnType<typeof vi.fn>;
}) => Promise<void>)
| undefined;
const respond = vi.fn(); const respond = vi.fn();
await handler?.({ params: { message: "Hi" }, respond }); await handler?.({ params: { message: "Hi" }, respond });
expect(runtimeStub.manager.initiateCall).toHaveBeenCalled(); expect(runtimeStub.manager.initiateCall).toHaveBeenCalled();
@@ -98,7 +105,12 @@ describe("voice-call plugin", () => {
it("returns call status", async () => { it("returns call status", async () => {
const { methods } = setup({ provider: "mock" }); const { methods } = setup({ provider: "mock" });
const handler = methods.get("voicecall.status"); const handler = methods.get("voicecall.status") as
| ((ctx: {
params: Record<string, unknown>;
respond: ReturnType<typeof vi.fn>;
}) => Promise<void>)
| undefined;
const respond = vi.fn(); const respond = vi.fn();
await handler?.({ params: { callId: "call-1" }, respond }); await handler?.({ params: { callId: "call-1" }, respond });
const [ok, payload] = respond.mock.calls[0]; const [ok, payload] = respond.mock.calls[0];