dika/test/owner-photo.test.js
peppa-bot cb9196521a
All checks were successful
peppa/lint lint: success за 0с
peppa/test test: success за 1с
peppa/build build: success за 0с
ci / checks (pull_request) Successful in 10s
deploy / deploy (pull_request) Successful in 20s
DIK-69: владелец загружает фото файлом, инструкция и понятные ошибки на странице правки
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 11:58:05 +00:00

102 lines
6.0 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.

// DIK-69: владелец загружает фото файлом и меняет описание; посетители не видят страницу правки.
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 { createHandler } from "../src/index.js";
import { photoType } from "../src/admin.js";
import { readRows, validateVenues } from "../src/venues.js";
const JPG = Buffer.concat([Buffer.from([0xff, 0xd8, 0xff, 0xe0]), Buffer.alloc(2000, 1)]);
const auth = { authorization: "Basic " + Buffer.from("o:s3cret").toString("base64") };
async function server() {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "dika-photo-"));
const srv = http.createServer(createHandler({ dataDir: dir, password: "s3cret" }));
await new Promise((r) => srv.listen(0, "127.0.0.1", r));
return { b: `http://127.0.0.1:${srv.address().port}`, dir, close: () => srv.close() };
}
const firstId = (dir) => readRows(dir).venues[0].id;
test("Сценарий: Фото загружено — видно на главной и на «Все заведения» с пометкой владельца", async () => {
const s = await server();
try {
const id = firstId(s.dir);
const r = await fetch(`${s.b}/admin/api/venues/${id}/photo`, { method: "POST", headers: auth, body: JPG });
assert.equal(r.status, 200);
const { photo } = await r.json();
assert.match(photo, /^\/photos\/[\w-]+\.jpg$/);
const img = await fetch(s.b + photo);
assert.equal(img.status, 200); assert.equal(img.headers.get("content-type"), "image/jpeg");
assert.deepEqual(Buffer.from(await img.arrayBuffer()), JPG);
const home = (await (await fetch(`${s.b}/api/venues`)).json()).find((v) => v.id === id);
assert.equal(home.photo, photo); assert.equal(home.photoSource, "владелец");
const base = (await (await fetch(`${s.b}/api/base`)).json()).find((v) => v.id === id);
assert.equal(base.photo, photo); assert.equal(base.photoSource, "владелец");
assert.deepEqual(validateVenues(readRows(s.dir).venues), []);
const d = await fetch(`${s.b}/admin/api/venues/${id}`, { method: "POST", headers: auth, body: JSON.stringify({ description: "Кафе у дома. Ланч каждый день", photo }) });
assert.equal(d.status, 200);
const home2 = (await (await fetch(`${s.b}/api/venues`)).json()).find((v) => v.id === id);
assert.equal(home2.description, "Кафе у дома. Ланч каждый день"); assert.equal(home2.descriptionSource, "владелец");
assert.equal(home2.photo, photo);
} finally { s.close(); }
});
test("Сценарий: Файл слишком большой — прежнее фото не меняется", async () => {
const s = await server();
try {
const id = firstId(s.dir);
const before = readRows(s.dir).venues[0]["фото"];
const big = Buffer.concat([JPG, Buffer.alloc(5 * 1024 * 1024)]);
const r = await fetch(`${s.b}/admin/api/venues/${id}/photo`, { method: "POST", headers: auth, body: big });
assert.equal(r.status, 413); assert.equal((await r.json()).error, "photo_too_big");
assert.equal(readRows(s.dir).venues[0]["фото"], before);
} finally { s.close(); }
});
test("Сценарий: Файл не картинка", async () => {
const s = await server();
try {
const r = await fetch(`${s.b}/admin/api/venues/${firstId(s.dir)}/photo`, { method: "POST", headers: auth, body: Buffer.from("%PDF-1.4 меню") });
assert.equal(r.status, 400); assert.equal((await r.json()).error, "photo_type");
assert.equal(photoType(Buffer.from("RIFF0000WEBPVP8 ")), "webp");
assert.equal(photoType(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0])), "png");
} finally { s.close(); }
});
test("Сценарий: Посетитель без пароля — понятная страница, данных нет", async () => {
const s = await server();
try {
const r = await fetch(`${s.b}/admin`);
assert.equal(r.status, 401);
const html = await r.text();
assert.match(html, /Эта страница — для владельца сервиса/);
assert.match(html, /пароль/);
assert.equal(r.headers.get("x-robots-tag"), "noindex");
assert.equal((await fetch(`${s.b}/admin/api/venues/${firstId(s.dir)}/photo`, { method: "POST", body: JPG })).status, 401);
assert.equal((await fetch(`${s.b}/photos/..%2Fvenues.csv`)).status, 404);
} finally { s.close(); }
});
test("Сценарий: Ссылки на страницу правки нет у посетителей", async () => {
const s = await server();
try {
for (const p of ["/", "/base", "/app.js", "/base.js"]) assert.doesNotMatch(await (await fetch(s.b + p)).text(), /\/admin/, p);
} finally { s.close(); }
});
test("Страница правки: инструкция, подписи «Описание» и «Фото», сообщения об ошибках на ru/kk/en", () => {
const html = fs.readFileSync(new URL("../admin/index.html", import.meta.url), "utf8");
for (const k of ["admHowTitle", "admHowText"]) assert.match(html, new RegExp(`data-i="${k}"`));
for (const k of ["admPhotoPick", "admPhotoFile", "admErrPhotoBig", "admErrPhotoType", "admErrPhotoNet", "admErrPhotoBroken", "admDescription", "admPhoto"]) assert.match(html, new RegExp(`t\\.${k}\\b`));
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 ["admHowText", "admErrPhotoBig", "admErrPhotoType", "admLoginTitle", "admPhotoPick"]) assert.ok(t[k], `${l}.${k}`);
}
const ru = JSON.parse(fs.readFileSync(new URL("../public/i18n/ru.json", import.meta.url), "utf8"));
assert.match(ru.admDescription, /^Описание/); assert.match(ru.admPhoto, /^Фото/);
assert.equal(ru.admErrPhotoBig, "Фото слишком большое. Выберите файл до 3 МБ или уменьшите фото.");
});