Сервер на Hono, клиент Google и его мок, переводы ru/kk/en, тесты по сценариям, проверки и деплой (Dockerfile, /healthz). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
192 lines
8.3 KiB
TypeScript
192 lines
8.3 KiB
TypeScript
import { describe, expect, it, vi } from "vitest";
|
||
import { createGoogleClient } from "../src/google/client.js";
|
||
import { CALENDAR_SCOPE, GoogleAuthError, GoogleError } from "../src/google/types.js";
|
||
|
||
const json = (body: unknown, status = 200) =>
|
||
new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
||
|
||
function clientWith(...responses: (Response | Error)[]) {
|
||
const fetchMock = vi.fn(async (_url: string | URL | Request, _init?: RequestInit) => {
|
||
const next = responses.shift();
|
||
if (!next) throw new Error("unexpected request");
|
||
if (next instanceof Error) throw next;
|
||
return next;
|
||
});
|
||
const client = createGoogleClient({
|
||
clientId: "client-id",
|
||
clientSecret: "client-secret",
|
||
fetch: fetchMock as typeof fetch,
|
||
});
|
||
return { client, fetchMock };
|
||
}
|
||
|
||
const range = {
|
||
timeMin: new Date("2026-11-14T05:00:00Z"),
|
||
timeMax: new Date("2026-11-25T05:00:00Z"),
|
||
};
|
||
|
||
describe("клиент Google: страница согласия", () => {
|
||
it("Scenario: Запрашивается только чтение", () => {
|
||
const { client } = clientWith();
|
||
const url = new URL(
|
||
client.authUrl({ state: "s-1", redirectUri: "https://ea.test/auth/google/callback" }),
|
||
);
|
||
expect(url.origin + url.pathname).toBe("https://accounts.google.com/o/oauth2/v2/auth");
|
||
expect(url.searchParams.get("scope")).toBe(CALENDAR_SCOPE);
|
||
expect(CALENDAR_SCOPE).toBe("https://www.googleapis.com/auth/calendar.events.readonly");
|
||
expect(url.searchParams.get("client_id")).toBe("client-id");
|
||
expect(url.searchParams.get("redirect_uri")).toBe("https://ea.test/auth/google/callback");
|
||
expect(url.searchParams.get("state")).toBe("s-1");
|
||
expect(url.searchParams.get("access_type")).toBe("offline");
|
||
expect(url.searchParams.get("response_type")).toBe("code");
|
||
});
|
||
});
|
||
|
||
describe("клиент Google: обмен кода и обновление доступа", () => {
|
||
it("меняет код на ключ подключения", async () => {
|
||
const { client, fetchMock } = clientWith(json({ access_token: "a", refresh_token: "r-1" }));
|
||
await expect(
|
||
client.exchangeCode({ code: "c-1", redirectUri: "https://ea.test/cb" }),
|
||
).resolves.toEqual({ refreshToken: "r-1" });
|
||
const [url, init] = fetchMock.mock.calls[0] ?? [];
|
||
expect(String(url)).toBe("https://oauth2.googleapis.com/token");
|
||
const body = new URLSearchParams(String(init?.body));
|
||
expect(Object.fromEntries(body)).toEqual({
|
||
client_id: "client-id",
|
||
client_secret: "client-secret",
|
||
grant_type: "authorization_code",
|
||
code: "c-1",
|
||
redirect_uri: "https://ea.test/cb",
|
||
});
|
||
});
|
||
|
||
it("Scenario: Google не подтвердил подключение — ошибка обмена кода", async () => {
|
||
const { client } = clientWith(json({ error: "invalid_grant" }, 400));
|
||
const failure = client.exchangeCode({ code: "old", redirectUri: "https://ea.test/cb" });
|
||
await expect(failure).rejects.toBeInstanceOf(GoogleError);
|
||
await expect(failure).rejects.not.toBeInstanceOf(GoogleAuthError);
|
||
});
|
||
|
||
it("ответ без ключа подключения — ошибка", async () => {
|
||
const { client } = clientWith(json({ access_token: "a" }));
|
||
await expect(
|
||
client.exchangeCode({ code: "c", redirectUri: "https://ea.test/cb" }),
|
||
).rejects.toBeInstanceOf(GoogleError);
|
||
});
|
||
|
||
it("обновляет доступ по ключу подключения", async () => {
|
||
const { client, fetchMock } = clientWith(json({ access_token: "a-2" }));
|
||
await expect(client.refreshAccessToken("r-1")).resolves.toBe("a-2");
|
||
const body = new URLSearchParams(String(fetchMock.mock.calls[0]?.[1]?.body));
|
||
expect(body.get("grant_type")).toBe("refresh_token");
|
||
expect(body.get("refresh_token")).toBe("r-1");
|
||
});
|
||
|
||
it("Scenario: Доступ отозван в настройках Google — invalid_grant", async () => {
|
||
const { client } = clientWith(json({ error: "invalid_grant" }, 400));
|
||
await expect(client.refreshAccessToken("r-1")).rejects.toBeInstanceOf(GoogleAuthError);
|
||
});
|
||
|
||
it("Scenario: Google не отвечает — сбой сети и 500 не считаются отзывом", async () => {
|
||
const offline = clientWith(new TypeError("fetch failed"));
|
||
const failure = offline.client.refreshAccessToken("r-1");
|
||
await expect(failure).rejects.toBeInstanceOf(GoogleError);
|
||
await expect(failure).rejects.not.toBeInstanceOf(GoogleAuthError);
|
||
const broken = clientWith(new Response("oops", { status: 500 }));
|
||
await expect(broken.client.refreshAccessToken("r-1")).rejects.toBeInstanceOf(GoogleError);
|
||
});
|
||
});
|
||
|
||
describe("клиент Google: чтение событий", () => {
|
||
it("читает события основного календаря: со временем, на весь день, без названия", async () => {
|
||
const { client, fetchMock } = clientWith(
|
||
json({
|
||
timeZone: "Asia/Almaty",
|
||
items: [
|
||
{
|
||
id: "1",
|
||
status: "confirmed",
|
||
summary: "Планёрка",
|
||
start: { dateTime: "2026-11-16T10:00:00+05:00" },
|
||
end: { dateTime: "2026-11-16T10:30:00+05:00" },
|
||
},
|
||
{
|
||
id: "2",
|
||
summary: "Выставка",
|
||
start: { date: "2026-11-17" },
|
||
end: { date: "2026-11-19" },
|
||
},
|
||
{
|
||
id: "3",
|
||
summary: " ",
|
||
start: { dateTime: "2026-11-17T12:00:00+05:00" },
|
||
end: { dateTime: "2026-11-17T13:00:00+05:00" },
|
||
},
|
||
{ id: "4", status: "cancelled", summary: "Отменено", start: { date: "2026-11-17" } },
|
||
],
|
||
}),
|
||
);
|
||
const result = await client.listEvents("a-1", range);
|
||
expect(result.timeZone).toBe("Asia/Almaty");
|
||
expect(result.events).toEqual([
|
||
{
|
||
id: "1",
|
||
title: "Планёрка",
|
||
allDay: false,
|
||
start: new Date("2026-11-16T05:00:00Z"),
|
||
end: new Date("2026-11-16T05:30:00Z"),
|
||
},
|
||
{ id: "2", title: "Выставка", allDay: true, startDate: "2026-11-17", endDate: "2026-11-19" },
|
||
{
|
||
id: "3",
|
||
title: null,
|
||
allDay: false,
|
||
start: new Date("2026-11-17T07:00:00Z"),
|
||
end: new Date("2026-11-17T08:00:00Z"),
|
||
},
|
||
]);
|
||
|
||
const [rawUrl, init] = fetchMock.mock.calls[0] ?? [];
|
||
const url = new URL(String(rawUrl));
|
||
expect(url.origin + url.pathname).toBe(
|
||
"https://www.googleapis.com/calendar/v3/calendars/primary/events",
|
||
);
|
||
expect(url.searchParams.get("singleEvents")).toBe("true");
|
||
expect(url.searchParams.get("orderBy")).toBe("startTime");
|
||
expect(url.searchParams.get("timeMin")).toBe("2026-11-14T05:00:00.000Z");
|
||
expect(url.searchParams.get("timeMax")).toBe("2026-11-25T05:00:00.000Z");
|
||
expect(init?.method ?? "GET").toBe("GET");
|
||
expect(new Headers(init?.headers).get("authorization")).toBe("Bearer a-1");
|
||
});
|
||
|
||
it("листает страницы", async () => {
|
||
const event = (id: string) => ({ id, summary: id, start: { date: "2026-11-17" } });
|
||
const { client, fetchMock } = clientWith(
|
||
json({ timeZone: "Asia/Almaty", items: [event("a")], nextPageToken: "p2" }),
|
||
json({ timeZone: "Asia/Almaty", items: [event("b")] }),
|
||
);
|
||
const result = await client.listEvents("a-1", range);
|
||
expect(result.events.map((e) => e.id)).toEqual(["a", "b"]);
|
||
expect(new URL(String(fetchMock.mock.calls[1]?.[0])).searchParams.get("pageToken")).toBe("p2");
|
||
});
|
||
|
||
it.each([
|
||
[401, { error: { errors: [{ reason: "authError" }] } }],
|
||
[403, { error: { errors: [{ reason: "insufficientPermissions" }] } }],
|
||
])("Scenario: Доступ отозван — ответ %i", async (status, body) => {
|
||
const { client } = clientWith(json(body, status));
|
||
await expect(client.listEvents("a-1", range)).rejects.toBeInstanceOf(GoogleAuthError);
|
||
});
|
||
|
||
it.each([
|
||
[403, { error: { errors: [{ reason: "rateLimitExceeded" }] } }],
|
||
[500, {}],
|
||
[503, {}],
|
||
])("Scenario: Google не отвечает — ответ %i не считается отзывом", async (status, body) => {
|
||
const { client } = clientWith(json(body, status));
|
||
const failure = client.listEvents("a-1", range);
|
||
await expect(failure).rejects.toBeInstanceOf(GoogleError);
|
||
await expect(failure).rejects.not.toBeInstanceOf(GoogleAuthError);
|
||
});
|
||
});
|