dika/test/fresh.test.js
Peppa e0d34f20ea
All checks were successful
peppa/lint lint: success за 0с
peppa/test test: success за 0с
peppa/build build: success за 0с
ci / checks (pull_request) Successful in 4s
deploy / deploy (pull_request) Successful in 14s
DIK-12: «Цена не подтверждена» и срок акции в понятном формате
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 14:01:01 +05:00

129 lines
7.3 KiB
JavaScript
Raw Permalink 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 test from "node:test";
import assert from "node:assert/strict";
import http from "node:http";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { buildList, offerStatus, astanaTime } from "../src/lib.js";
import { readRows, toCsv } from "../src/venues.js";
import { createStore, checkPassword } from "../src/admin.js";
import { createHandler } from "../src/index.js";
const wed = new Date("2026-11-18T08:00:00Z"); // среда 13:00 Астана
const venue = (over) => ({ id: "a", name: "A", address: "ул. А, 1", lat: 51.1283, lng: 71.4305,
lunch: { price: 3500, days: [1, 2, 3, 4, 5], from: "12:00", to: "15:00" }, promo: { text: "Кофе", until: "2026-12-31" }, checked: "2026-11-18", ...over });
const one = (v) => buildList([v], 51.1283, 71.4305, { now: wed })[0];
test("Сценарий: акция закончилась — заведение остаётся", () => {
const v = one(venue({ promo: { text: "Кофе", until: "2026-11-15" } }));
assert.equal(v.id, "a"); assert.equal(v.promo, null); assert.ok(v.lunch);
});
test("Сценарий: данные давно не проверяли — заведение без цены и акции", () => {
const v = one(venue({ checked: "2026-11-01" }));
assert.equal(v.id, "a"); assert.equal(v.lunch, null); assert.equal(v.promo, null);
});
test("Сценарий: граница в 14 дней", () => {
assert.ok(one(venue({ checked: "2026-11-04" })).lunch);
assert.equal(one(venue({ checked: "2026-11-03" })).lunch, null);
});
test("Сценарий: владелец обновил дату — запись снова на сайте", () => {
assert.equal(one(venue({ checked: "2026-11-01" })).lunch, null);
assert.ok(one(venue({ checked: "2026-11-18" })).lunch);
});
test("Сценарий: статусы для владельца", () => {
const t = astanaTime(wed);
assert.deepEqual(offerStatus(venue(), t), { lunch: "active", promo: "active" });
assert.deepEqual(offerStatus(venue({ checked: "2026-11-01" }), t), { lunch: "stale", promo: "stale" });
assert.deepEqual(offerStatus(venue({ lunch: null, promo: { text: "x", until: "2026-11-01" } }), t), { lunch: "none", promo: "expired" });
assert.deepEqual(offerStatus(venue({ promo: null }), t), { lunch: "active", promo: "none" });
});
const tmpBase = () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "dika-"));
fs.cpSync("data", dir, { recursive: true });
return dir;
};
const TODAY = astanaTime().date;
test("Запись таблицы не меняет остальное содержимое базы", () => {
const src = fs.readFileSync("data/venues.csv", "utf8");
assert.equal(toCsv(readRows("data").venues), src);
});
test("Сценарий: владелец меняет цену, акцию и дату", () => {
const dir = tmpBase();
const store = createStore(dir);
const id = readRows(dir).venues[0].id;
const r = store.update(id, { price: "3900", promo: "Кофе в подарок", promoUntil: TODAY, checked: TODAY });
assert.deepEqual(r, { ok: true });
const row = store.list().find((x) => x.id === id);
assert.equal(row.lunch.price, 3900); assert.equal(row.promo.text, "Кофе в подарок"); assert.equal(row.checked, TODAY);
assert.equal(store.db.venues.find((v) => v.id === id).lunch.price, 3900);
assert.equal(readRows(dir).venues.length, store.list().length); // записи не удаляются
assert.equal(store.update(id, { promo: "нет", checked: TODAY }).ok, true);
assert.equal(store.list().find((x) => x.id === id).promo, null);
});
test("Сценарий: неверное значение отклоняется, данные не меняются", () => {
const dir = tmpBase();
const store = createStore(dir);
const before = fs.readFileSync(`${dir}/venues.csv`, "utf8");
const id = readRows(dir).venues[0].id;
assert.equal(store.update(id, { price: "abc", checked: TODAY }).error, "bad_price");
assert.equal(store.update(id, { checked: "2099-01-01" }).error, "future_date");
assert.equal(store.update(id, { checked: "" }).error, "bad_date");
assert.equal(store.update("нет-такого", { checked: TODAY }).error, "not_found");
assert.equal(fs.readFileSync(`${dir}/venues.csv`, "utf8"), before);
});
test("Каталог данных без базы получает стартовую", () => {
const dir = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "dika-")), "live");
const store = createStore(dir, "data");
assert.ok(store.db.venues.length >= 20 && fs.existsSync(`${dir}/venues.csv`));
});
test("Проверка пароля", () => {
const h = (p) => "Basic " + Buffer.from("owner:" + p).toString("base64");
assert.equal(checkPassword(h("s3cret"), "s3cret"), true);
assert.equal(checkPassword(h("wrong"), "s3cret"), false);
assert.equal(checkPassword(undefined, "s3cret"), false);
assert.equal(checkPassword(h(""), ""), false);
});
async function withServer(opts, fn) {
const s = http.createServer(createHandler(opts)).listen(0);
try { await fn(`http://127.0.0.1:${s.address().port}`); } finally { s.close(); }
}
test("Сценарий: пароль не задан / неверный / верный; изменение видно на сайте", async () => {
await withServer({ dataDir: tmpBase(), password: "" }, async (b) => {
const r = await fetch(b + "/admin"); assert.equal(r.status, 503);
});
await withServer({ dataDir: tmpBase(), password: "s3cret" }, async (b) => {
assert.equal((await fetch(b + "/admin")).status, 401);
assert.equal((await fetch(b + "/admin/api/venues")).status, 401);
const auth = { authorization: "Basic " + Buffer.from("o:s3cret").toString("base64") };
assert.equal((await fetch(b + "/admin", { headers: auth })).status, 200);
const rows = await (await fetch(b + "/admin/api/venues", { headers: auth })).json();
const v = rows[0];
const post = (body) => fetch(`${b}/admin/api/venues/${v.id}`, { method: "POST", headers: auth, body: JSON.stringify(body) });
assert.equal((await post({ price: "abc", checked: TODAY })).status, 400);
assert.equal((await post({ price: "4321", checked: TODAY })).status, 200);
const site = await (await fetch(`${b}/api/venues?lat=51.1283&lng=71.4305`)).json();
assert.equal(site.length > 0, true);
assert.equal((await fetch(b + "/healthz")).status, 200);
});
});
test("Сценарий: страница правки показывает дату проверки и подсказку; тексты есть на всех языках", async () => {
const html = fs.readFileSync(new URL("../admin/index.html", import.meta.url), "utf8");
for (const l of ["ru", "kk", "en"]) {
const t = JSON.parse(fs.readFileSync(new URL(`../public/i18n/${l}.json`, import.meta.url), "utf8"));
for (const k of ["admCheckedOn", "admNeverChecked", "admHiddenHint", "admAutoDate"]) {
assert.ok(t[k], `${l}:${k}`); assert.ok(html.includes(k), k);
}
}
});
test("Сценарий: цена не подтверждена — давние данные и нет данных", () => {
assert.equal(one(venue({ checked: "2026-11-01" })).unconfirmed, true);
assert.equal(one(venue({ lunch: null, promo: null })).unconfirmed, true);
assert.equal(one(venue()).unconfirmed, false);
assert.equal(one(venue({ checked: "2026-11-18", lunch: { price: 3500, days: [6], from: "12:00", to: "15:00" } })).unconfirmed, false);
});