Files
openclaw/extensions/telegram/src/bot.media.test-utils.ts
Peter Steinberger fa03d9b913 refactor: consolidate coercion helpers (#121366)
* refactor: consolidate coercion helpers

* fix: remove duplicate coercion imports

* fix: preserve serialized coercion guard

* chore: ratchet coercion helper carve-outs

* fix(test): keep gauntlet subprocess startup lean

* fix: preserve imported session timestamp semantics

* fix: preserve catalog timestamp string semantics

* chore: align plugin SDK surface ratchet

* fix: preserve trajectory and SDK string contracts

* fix(test): preserve QA record assertion semantics

* fix: complete standalone record guard rename

* refactor(cron): use canonical string coercion

* fix(acpx): preserve Pi timestamp parsing

* test(channels): adapt custody test harnesses

* test(telegram): classify media harness as test support

* test(acpx): split timestamp contract coverage

* test(channels): support generated custody contracts

* chore: ban the full coercion helper name set

Extends the declaration guard to all eleven consolidated helper names and
renames the cron schedule-identity readNumber wrapper to readScheduleInteger
so the banned generic name cannot regrow.

* fix(scripts): repair release-validation guard drift and lint cause

Restores the renamed isJsonRecord guard in assertTrustedWorkflowHarness after
main added isRecord call sites in parallel, and attaches the caught YAML error
as the thrown error cause (preserve-caught-error was red on main).

* fix: preserve Claude timestamp string semantics

* fix: preserve persisted timestamp string semantics

* fix: preserve date-first timestamp contracts

* fix(openai): harden delegation failure formatting

* chore: close coercion helper guard gaps

* test(openai): model non-error delegation rejection

* chore: refresh plugin SDK API contract

* fix(tasks): use canonical string field reader

* fix(ai): use canonical provider error field coercion

* fix(browser): migrate native bootstrap coercion

* docs(plugin-sdk): clarify text record export compatibility

* fix(gateway): normalize approval execution identity

* test(outbound): isolate message action poll harness
2026-08-11 00:02:18 -07:00

169 lines
5.7 KiB
TypeScript

// Telegram helper module supports bot.media utils behavior.
import * as ssrf from "openclaw/plugin-sdk/ssrf-runtime";
import { afterEach, beforeAll, beforeEach, expect, vi, type Mock } from "vitest";
import { telegramBotInfoForTest } from "./bot.create-telegram-bot.test-support.js";
import * as harness from "./bot.media.e2e.test-harness.js";
type StickerSpy = Mock<(...args: unknown[]) => unknown>;
export const cacheStickerSpy: StickerSpy = vi.fn();
export const getCachedStickerSpy: StickerSpy = vi.fn();
export const describeStickerImageSpy: StickerSpy = vi.fn();
const resolvePinnedHostname = ssrf.resolvePinnedHostname;
const lookupMock = vi.fn();
let resolvePinnedHostnameSpy: ReturnType<typeof vi.spyOn> = null;
export const TELEGRAM_TEST_TIMINGS = {
mediaGroupFlushMs: 20,
textFragmentGapMs: 30,
} as const;
let createTelegramBotRef: typeof import("./bot.js").createTelegramBot;
let replySpyRef: ReturnType<typeof vi.fn>;
let onSpyRef: Mock;
let sendChatActionSpyRef: Mock;
let readRemoteMediaBufferSpyRef: Mock;
let undiciFetchSpyRef: Mock;
let resetReadRemoteMediaBufferMockRef: () => void;
type FetchMockHandle = Mock & { mockRestore: () => void };
function createFetchMockHandle(): FetchMockHandle {
return Object.assign(readRemoteMediaBufferSpyRef, {
mockRestore: () => {
resetReadRemoteMediaBufferMockRef();
},
}) as FetchMockHandle;
}
export async function createBotHandler(): Promise<{
handler: (ctx: Record<string, unknown>) => Promise<void>;
replySpy: ReturnType<typeof vi.fn>;
runtimeError: ReturnType<typeof vi.fn>;
}> {
return createBotHandlerWithOptions({});
}
export async function createBotHandlerWithOptions(options: {
proxyFetch?: typeof fetch;
runtimeLog?: ReturnType<typeof vi.fn>;
runtimeError?: ReturnType<typeof vi.fn>;
}): Promise<{
handler: (ctx: Record<string, unknown>) => Promise<void>;
replySpy: ReturnType<typeof vi.fn>;
runtimeError: ReturnType<typeof vi.fn>;
}> {
onSpyRef.mockClear();
replySpyRef.mockClear();
sendChatActionSpyRef.mockClear();
const runtimeError = options.runtimeError ?? vi.fn();
const runtimeLog = options.runtimeLog ?? vi.fn();
const effectiveProxyFetch = options.proxyFetch ?? (undiciFetchSpyRef as unknown as typeof fetch);
createTelegramBotRef({
token: "tok",
// Production always constructs the bot from getMe(), so inbound handlers may
// resolve the bot user id from botInfo when a test ctx carries only a username.
botInfo: telegramBotInfoForTest,
config: harness.telegramBotDepsForTest.getRuntimeConfig(),
testTimings: TELEGRAM_TEST_TIMINGS,
...(effectiveProxyFetch ? { proxyFetch: effectiveProxyFetch } : {}),
runtime: {
log: runtimeLog as (...data: unknown[]) => void,
error: runtimeError as (...data: unknown[]) => void,
getRuntimeConfig: () => harness.telegramBotDepsForTest.getRuntimeConfig(),
exit: () => {
throw new Error("exit");
},
} as Parameters<typeof createTelegramBotRef>[0]["runtime"],
});
const handler = onSpyRef.mock.calls.find((call) => call[0] === "message")?.[1] as (
ctx: Record<string, unknown>,
) => Promise<void>;
expect(handler).toBeDefined();
return { handler, replySpy: replySpyRef, runtimeError };
}
export function mockTelegramFileDownload(params: {
contentType: string;
bytes: Uint8Array;
}): FetchMockHandle {
undiciFetchSpyRef.mockResolvedValueOnce(
new Response(Buffer.from(params.bytes), {
status: 200,
headers: { "content-type": params.contentType },
}),
);
readRemoteMediaBufferSpyRef.mockResolvedValueOnce({
buffer: Buffer.from(params.bytes),
contentType: params.contentType,
fileName: "mock-file",
});
return createFetchMockHandle();
}
export function mockTelegramPngDownload(): FetchMockHandle {
undiciFetchSpyRef.mockResolvedValue(
new Response(Buffer.from(new Uint8Array([0x89, 0x50, 0x4e, 0x47])), {
status: 200,
headers: { "content-type": "image/png" },
}),
);
readRemoteMediaBufferSpyRef.mockResolvedValue({
buffer: Buffer.from(new Uint8Array([0x89, 0x50, 0x4e, 0x47])),
contentType: "image/png",
fileName: "mock-file.png",
});
return createFetchMockHandle();
}
export function watchTelegramFetch(): FetchMockHandle {
return createFetchMockHandle();
}
async function loadTelegramBotHarness() {
onSpyRef = harness.onSpy;
sendChatActionSpyRef = harness.sendChatActionSpy;
readRemoteMediaBufferSpyRef = harness.readRemoteMediaBufferSpy;
undiciFetchSpyRef = harness.undiciFetchSpy;
resetReadRemoteMediaBufferMockRef = harness.resetReadRemoteMediaBufferMock;
const botModule = await import("./bot.js");
createTelegramBotRef = (opts) =>
botModule.createTelegramBot({
...opts,
telegramDeps: harness.telegramBotDepsForTest,
});
replySpyRef = harness.mediaHarnessReplySpy;
}
beforeAll(async () => {
await loadTelegramBotHarness();
});
beforeEach(() => {
onSpyRef.mockClear();
replySpyRef.mockClear();
sendChatActionSpyRef.mockClear();
vi.useRealTimers();
lookupMock.mockResolvedValue([{ address: "93.184.216.34", family: 4 }]);
resolvePinnedHostnameSpy = vi
.spyOn(ssrf, "resolvePinnedHostname")
.mockImplementation((hostname) => resolvePinnedHostname(hostname, lookupMock));
});
afterEach(() => {
lookupMock.mockClear();
resolvePinnedHostnameSpy?.mockRestore();
resolvePinnedHostnameSpy = null;
});
vi.mock("./sticker-cache.js", () => ({
cacheSticker: (...args: unknown[]) => cacheStickerSpy(...args),
getCachedSticker: (...args: unknown[]) => getCachedStickerSpy(...args),
describeStickerImage: (...args: unknown[]) => describeStickerImageSpy(...args),
getAllCachedStickers: vi.fn(() => []),
getCacheStats: vi.fn(() => ({ count: 0 })),
searchStickers: vi.fn(() => []),
}));