Files
khb_microservices/packages/khbuild_assistant_prep/src/tts.test.ts
2026-10-16 12:55:18 +03:00

116 lines
6.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { describe, expect, it } from "vitest";
import { publishReply, type ChatDeps, type ManagerInfo } from "./slack/chat.js";
import { createSlackApi } from "./slack/api.js";
import { createGoogleTts, normalizeVoice, speechText, splitForTts } from "./slack/tts.js";
describe("синтез речи Chirp 3 HD", () => {
it("имена голосов нормализуются, неизвестные отвергаются", () => {
expect(normalizeVoice("aoede")).toBe("Aoede");
expect(normalizeVoice("en-US-Chirp3-HD-Puck")).toBe("Puck");
expect(normalizeVoice("Nobody")).toBeNull();
expect(normalizeVoice(null)).toBeNull();
});
it("из ответа убирается разметка Slack/Markdown", () => {
const t = speechText("*Done* ✅\n• item <https://x.io/a|link text> and `code`\n```\nblock\n```\nSee https://x.io now");
expect(t).not.toMatch(/[*`<>✅]|https?:/);
expect(t).toContain("Done");
expect(t).toContain("link text");
});
it("длинный текст делится на части до лимита байт", () => {
const text = Array.from({ length: 400 }, (_, i) => `Sentence number ${i}.`).join(" ");
const parts = splitForTts(text, 1000);
expect(parts.length).toBeGreaterThan(5);
for (const p of parts) expect(Buffer.byteLength(p)).toBeLessThanOrEqual(1000);
expect(parts.join(" ").replace(/\s+/g, " ")).toBe(text);
});
it("запрос к Google TTS: голос, язык, MP3; части склеиваются", async () => {
const reqs: { url: string; body: any }[] = [];
const fake = (async (url: string, init: { body: string }) => {
reqs.push({ url, body: JSON.parse(init.body) });
return { ok: true, status: 200, json: async () => ({ audioContent: Buffer.from(`mp3-${reqs.length}`).toString("base64") }) };
}) as unknown as typeof fetch;
const tts = createGoogleTts({ apiKey: "K", languageCode: "en-US" }, fake);
const out = await tts.synthesize("Hello there. " + "Long sentence here. ".repeat(300), "Kore");
expect(reqs.length).toBeGreaterThan(1);
expect(reqs[0]!.url).toContain("texttospeech.googleapis.com/v1/text:synthesize?key=K");
expect(reqs[0]!.body.voice).toEqual({ languageCode: "en-US", name: "en-US-Chirp3-HD-Kore" });
expect(reqs[0]!.body.audioConfig.audioEncoding).toBe("MP3");
expect(out.toString()).toMatch(/^mp3-1mp3-2/);
await expect(tts.synthesize("x", "Bogus")).rejects.toThrow(/неизвестный голос/);
});
it("ошибка API превращается в исключение с текстом Google", async () => {
const fake = (async () => ({ ok: false, status: 403, json: async () => ({ error: { message: "billing disabled" } }) })) as unknown as typeof fetch;
await expect(createGoogleTts({ apiKey: "K", languageCode: "en-US" }, fake).synthesize("Hi", "Aoede")).rejects.toThrow(/billing disabled/);
});
});
describe("режим ответов чата", () => {
const manager = (mode?: ManagerInfo["replyMode"], voice?: string): ManagerInfo => ({ personId: "m", name: "M", slackUserId: "U", slackChannelId: "C", replyMode: mode, ttsVoice: voice });
function setup(opts: { ttsFails?: boolean; noUpload?: boolean } = {}) {
const events: string[] = [];
const problems: string[] = [];
const deps = {
ctx: { pool: { query: async (_s: string, p: unknown[]) => void problems.push(String(p[1])) }, log: { warn: () => undefined } },
slack: {
postMessage: async (_c: string, t: string) => (events.push(`text:${t}`), true),
uploadFile: opts.noUpload ? undefined : async (_c: string, name: string) => void events.push(`audio:${name}`),
},
tts: { synthesize: async (_t: string, v: string) => (opts.ttsFails ? Promise.reject(new Error("billing disabled")) : (events.push(`voice:${v}`), Buffer.from("x"))) },
defaultVoice: "Aoede",
} as unknown as ChatDeps;
return { deps, events, problems };
}
it("по умолчанию - только текст, синтез не вызывается", async () => {
const s = setup();
expect(await publishReply(s.deps, manager(), "C", "Hi")).toMatchObject({ published: true, audioSent: false });
expect(s.events).toEqual(["text:Hi"]);
});
it("both - и аудио (голос чата), и текст", async () => {
const s = setup();
expect(await publishReply(s.deps, manager("both", "Puck"), "C", "Hi")).toMatchObject({ published: true, audioSent: true });
expect(s.events).toEqual(["voice:Puck", "audio:assistant-reply.mp3", "text:Hi"]);
});
it("audio - только аудио, голос по умолчанию из настроек", async () => {
const s = setup();
expect(await publishReply(s.deps, manager("audio"), "C", "Hi")).toMatchObject({ published: true, audioSent: true });
expect(s.events).toEqual(["voice:Aoede", "audio:assistant-reply.mp3"]);
});
it("сбой синтеза или загрузки: ответ уходит текстом, проблема пишется в лог", async () => {
for (const o of [{ ttsFails: true }, { noUpload: true }]) {
const s = setup(o);
const r = await publishReply(s.deps, manager("audio"), "C", "Hi");
expect(r.audioSent).toBe(false);
expect(s.events).toContain("text:Hi");
}
const s = setup({ ttsFails: true });
await publishReply(s.deps, manager("audio"), "C", "Hi");
expect(s.problems[0]).toMatch(/billing disabled/);
});
});
describe("загрузка аудио в Slack", () => {
it("трёхшаговая внешняя загрузка: адрес -> байты -> завершение с каналом", async () => {
const calls: string[] = [];
const fake = (async (url: string, init: { body?: unknown }) => {
calls.push(url.replace("https://slack.com/api/", ""));
if (url.endsWith("getUploadURLExternal")) return { ok: true, json: async () => ({ ok: true, upload_url: "https://up.slack/x", file_id: "F1" }) };
if (url === "https://up.slack/x") return { ok: true, status: 200 };
return { ok: true, json: async () => ({ ok: true, _body: JSON.parse(String(init.body)) }) };
}) as unknown as typeof fetch;
await createSlackApi("xoxb", fake).uploadFile!("C1", "a.mp3", Buffer.from("abc"), "Voice");
expect(calls).toEqual(["files.getUploadURLExternal", "https://up.slack/x", "files.completeUploadExternal"]);
});
it("отсутствие scope - исключение", async () => {
const fake = (async () => ({ ok: true, json: async () => ({ ok: false, error: "missing_scope" }) })) as unknown as typeof fetch;
await expect(createSlackApi("xoxb", fake).uploadFile!("C1", "a.mp3", Buffer.from("a"))).rejects.toThrow(/missing_scope/);
});
});