executive-ai/test/helpers.ts
Peppa 56cba4cad0 EA-1: приложение — подключение календаря Google и список дел на 7 дней
Сервер на Hono, клиент Google и его мок, переводы ru/kk/en, тесты по сценариям,
проверки и деплой (Dockerfile, /healthz).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 12:29:10 +05:00

86 lines
3.7 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 { vi } from "vitest";
import type { CalendarEvent } from "../src/agenda.js";
import { createApp } from "../src/app.js";
import type { GoogleClient } from "../src/google/types.js";
export const ALMATY = "Asia/Almaty";
/** Понедельник 16 ноября 2026, 10:00 по Алматы. */
export const MONDAY_10 = new Date("2026-11-16T10:00:00+05:00");
export function timed(title: string | null, start: string, end?: string): CalendarEvent {
const startDate = new Date(`${start}:00+05:00`);
const endDate = end ? new Date(`${end}:00+05:00`) : new Date(startDate.getTime() + 3_600_000);
return { id: `${title}-${start}`, title, allDay: false, start: startDate, end: endDate };
}
export function allDay(title: string | null, startDate: string, endDate: string): CalendarEvent {
return { id: `${title}-${startDate}`, title, allDay: true, startDate, endDate };
}
/** Подставной календарь Google с заданными событиями; вызовы можно проверять. */
export function stubGoogle(initial: CalendarEvent[] = [], timeZone = ALMATY) {
const state = { events: initial };
const client = {
isMock: false,
authUrl: vi.fn(
({ state: s, redirectUri }: { state: string; redirectUri: string }) =>
`https://accounts.google.test/consent?state=${s}&redirect_uri=${encodeURIComponent(redirectUri)}`,
),
exchangeCode: vi.fn(async () => ({ refreshToken: "stub-refresh-token" })),
refreshAccessToken: vi.fn(async () => "stub-access-token"),
listEvents: vi.fn(async () => ({ timeZone, events: state.events })),
} satisfies GoogleClient;
return { client, state };
}
/** Браузер для тестов: хранит cookie между запросами. */
export function browser(app: ReturnType<typeof createApp>, headers: Record<string, string> = {}) {
const jar = new Map<string, string>();
return {
jar,
async get(path: string, method = "GET") {
const cookie = [...jar].map(([k, v]) => `${k}=${v}`).join("; ");
const res = await app.request(`http://ea.test${path}`, {
method,
headers: { "accept-language": "ru-RU", ...headers, ...(cookie ? { cookie } : {}) },
});
for (const line of res.headers.getSetCookie()) {
const [pair = "", ...attrs] = line.split(";");
const eq = pair.indexOf("=");
const name = pair.slice(0, eq);
const value = pair.slice(eq + 1);
const expired = attrs.some((a) => /^\s*max-age=0$/i.test(a));
if (expired || value === "") jar.delete(name);
else jar.set(name, value);
}
return res;
},
/** Проходит подключение: кнопка → страница согласия → возврат в EA. */
async connect(answer: "allow" | "deny" = "allow") {
const start = await this.get("/connect");
const consent = new URL(start.headers.get("location") ?? "");
const state = consent.searchParams.get("state") ?? "";
const query =
answer === "allow" ? `code=stub-code&state=${state}` : `error=access_denied&state=${state}`;
const back = await this.get(`/auth/google/callback?${query}`);
return this.get(back.headers.get("location") ?? "/");
},
};
}
export function appWith(google: GoogleClient, now: Date = MONDAY_10) {
return createApp({ google, sessionSecret: "test-secret", now: () => now });
}
/** Видимый текст страницы без разметки и стилей. */
export function visibleText(html: string): string {
return html
.replace(/<style[\s\S]*?<\/style>/g, " ")
.replace(/<title[\s\S]*?<\/title>/g, " ")
.replace(/<[^>]+>/g, " ")
.replace(/&quot;/g, '"')
.replace(/&amp;/g, "&")
.replace(/\s+/g, " ")
.trim();
}