peppa/bench/tasks/05-external-api/checks/check.mjs
Асель d108197f0f PEP-184: задачи 5–8, тест набора, archive change, память
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 02:09:17 +05:00

95 lines
4.8 KiB
JavaScript
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.

// BENCH-HIDDEN — скрытые проверки задачи 5 (внешний сервис курсов; здесь — наш мок сервиса).
import { createServer } from "node:http";
import { assertText, files, freePort, page } from "../../../lib/check-kit.mjs";
const RATES = { USD: 0.00198, EUR: 0.00171, RUB: 0.157 };
const mock = { mode: "ok", hits: 0 };
export async function setup() {
const port = await freePort();
const server = createServer((req, res) => {
const url = new URL(req.url, "http://x");
if (url.pathname !== "/v1/latest" || url.searchParams.get("base") !== "KZT") return res.writeHead(404).end("{}");
mock.hits++;
if (mock.mode === "down") return res.writeHead(503, { "content-type": "application/json" }).end('{"error":"maintenance"}');
if (mock.mode === "slow") return; // не отвечаем вовсе
res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ base: "KZT", date: "2026-11-16", rates: RATES }));
});
await new Promise((r) => server.listen(port, "127.0.0.1", r));
return {
env: { RATES_API_URL: `http://127.0.0.1:${port}` },
teardown: () => new Promise((r) => { server.closeAllConnections?.(); server.close(r); }),
};
}
async function convert(t, amount, to) {
const r = await t.app.get(`/api/convert?amount=${encodeURIComponent(amount)}&to=${to}`);
return { r, b: r.json() };
}
export default [
{
name: "пересчёт по курсу сервиса",
async run(t) {
for (const [to, rate] of Object.entries(RATES)) {
const { r, b } = await convert(t, 10000, to);
t.assert.equal(r.status, 200, `${to}: ${r.status} ${r.text.slice(0, 200)}`);
t.assert.ok(Math.abs(Number(b.result) - 10000 * rate) < 0.011, `${to}: ${b.result} вместо ${10000 * rate}`);
t.assert.equal(Number(b.rate), rate);
}
},
},
{
name: "курс не запрашивается на каждый расчёт",
async run(t) {
const before = mock.hits;
for (let i = 0; i < 5; i++) await convert(t, 1000 + i, "USD");
t.assert.ok(mock.hits - before <= 1, `5 расчётов — ${mock.hits - before} запросов к сервису`);
},
},
{ name: "неизвестная валюта — подсказка", async run(t) { const { r } = await convert(t, 1000, "XYZ"); t.assert.equal(r.status, 400); t.assert.ok(r.json()?.errors, "нет errors"); } },
{ name: "отрицательная сумма — подсказка", async run(t) { const { r, b } = await convert(t, -5, "USD"); t.assert.equal(r.status, 400); t.assert.ok(b?.errors?.amount, "нет errors.amount"); } },
{ name: "сумма больше 10 млн — подсказка", async run(t) { const { r, b } = await convert(t, 10000001, "USD"); t.assert.equal(r.status, 400); t.assert.ok(b?.errors?.amount, "нет errors.amount"); } },
{
name: "страница калькулятора",
async run(t) {
const html = await page(t, "/convert");
t.assert.ok(!html.includes("Скоро здесь будет калькулятор"), "на /convert всё ещё заглушка");
t.assert.match(html, /<(form|input)\b/i, "на /convert нет поля ввода");
assertText(html, "курс");
},
},
{
name: "сервис лежит — понятное сообщение, сайт жив",
async run(t) {
mock.mode = "down";
await t.app.restart(); // без сохранённого курса
const { r } = await convert(t, 1000, "USD");
t.assert.ok(r.status >= 500 && r.status < 600, `ожидали 5xx, получили ${r.status}`);
t.assert.ok(r.text.includes("Курсы временно недоступны"), `ответ: ${r.text.slice(0, 200)}`);
t.assert.equal((await t.app.get("/healthz")).status, 200);
},
},
{
name: "сервис не отвечает — ответ быстрее 8 секунд",
async run(t) {
mock.mode = "slow";
await t.app.restart();
const started = Date.now();
const { r } = await convert(t, 1000, "USD");
const sec = (Date.now() - started) / 1000;
t.assert.ok(sec < 8, `ждали ответа ${sec.toFixed(1)} с`);
t.assert.ok(r.text.includes("Курсы временно недоступны"), `ответ: ${r.text.slice(0, 200)}`);
mock.mode = "ok";
},
},
{
name: "у проекта есть свой мок сервиса и зелёные тесты",
async run(t) {
t.assert.ok(files(t.workdir).some((f) => f.startsWith("product/") && /mock/i.test(f)), "в product/ нет файла с mock в имени");
const r = await t.run("node", ["--test", "product/test/"]);
t.assert.equal(r.code, 0, `тесты упали:\n${r.out.slice(-1500)}`);
},
},
];