INA-2: тесты по сценариям, Dockerfile, словарь и README
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
b75d8e5e67
commit
7386229c1a
4
.dockerignore
Normal file
4
.dockerignore
Normal file
@ -0,0 +1,4 @@
|
||||
node_modules
|
||||
dist
|
||||
.pnpm-store
|
||||
.git
|
||||
21
Dockerfile
Normal file
21
Dockerfile
Normal file
@ -0,0 +1,21 @@
|
||||
# Сайт-визитка INA (INA-2). Основа — deploy/Dockerfile.node.
|
||||
# Приложение слушает $PORT и отвечает 200 на GET /healthz (deploy.health).
|
||||
FROM node:22-bookworm-slim AS build
|
||||
WORKDIR /app
|
||||
RUN corepack enable
|
||||
COPY package.json pnpm-lock.yaml ./
|
||||
RUN pnpm install --frozen-lockfile
|
||||
COPY tsconfig.json tsconfig.build.json ./
|
||||
COPY src ./src
|
||||
RUN pnpm build
|
||||
|
||||
# У сервера нет зависимостей во время работы — в образ идут только сборка и переводы.
|
||||
FROM node:22-bookworm-slim
|
||||
WORKDIR /app
|
||||
ENV NODE_ENV=production PORT=3000
|
||||
COPY package.json ./
|
||||
COPY --from=build /app/dist ./dist
|
||||
COPY locales ./locales
|
||||
USER node
|
||||
EXPOSE 3000
|
||||
CMD ["node", "dist/index.js"]
|
||||
13
README.md
13
README.md
@ -1,3 +1,16 @@
|
||||
# inat
|
||||
|
||||
Проект Peppa FACTORY. Ключ стори: `INA`. Правила — в [AGENTS.md](AGENTS.md).
|
||||
|
||||
Одностраничный сайт-визитка (Node.js 22 + TypeScript, без фреймворка).
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm dev # http://localhost:3000, порт — $PORT
|
||||
pnpm lint && pnpm typecheck && pnpm test && pnpm build
|
||||
pnpm start # запуск собранной версии из dist/
|
||||
```
|
||||
|
||||
- Тексты страницы — `locales/ru.json`, `kk.json`, `en.json` (одинаковые ключи, список — `src/i18n.ts`).
|
||||
Страница показывает русский (`DEFAULT_LOCALE`).
|
||||
- `GET /healthz` → `200 ok` — проверка работоспособности при деплое.
|
||||
|
||||
@ -32,3 +32,15 @@
|
||||
| Вернуть работу | поправить | реджект, вернуть в бэклог, change request | Кнопка «Поправить» |
|
||||
| Список задач | доска, бэклог | канбан-борд, backlog | «Бэклог» допустим как название колонки |
|
||||
| Ошибки продукта | баги | инциденты, Bugsink, Sentry | Вкладка «Баги» |
|
||||
|
||||
## Сайт-визитка INA
|
||||
|
||||
Слова, которые видит посетитель сайта. Тексты — в `locales/{ru,kk,en}.json`.
|
||||
|
||||
| Понятие | Пишем | Нельзя | Пояснение |
|
||||
|---|---|---|---|
|
||||
| Временный текст | [ЗАГЛУШКА] (kk: [ҮЛГІ], en: [PLACEHOLDER]) | lorem ipsum, TODO, тест, placeholder (в ru) | Метка в начале текста, пока нет настоящего; убирается задачей замены текстов |
|
||||
| Блок о компании | Кто мы | О нас, About | Заголовок первого блока |
|
||||
| Блок об услугах | Чем занимаемся | Услуги, Services | Заголовок второго блока |
|
||||
| Блок контактов | Контакты | Связь, Contact us | Заголовок третьего блока |
|
||||
| Нет страницы | Страница не найдена | 404, Not Found | Ошибка из двух фраз: что случилось и куда перейти |
|
||||
|
||||
@ -1,20 +1,20 @@
|
||||
## 1. Каркас проекта и проверки
|
||||
|
||||
- [ ] 1.1 `package.json` (pnpm), TypeScript, Biome, `tsconfig.json`/`tsconfig.build.json`, `.gitignore`
|
||||
- [ ] 1.2 `.peppa/project.json` → `checks` (install, lint, typecheck, test, build) и `deploy`
|
||||
- [x] 1.1 `package.json` (pnpm), TypeScript, Biome, `tsconfig.json`/`tsconfig.build.json`, `.gitignore`
|
||||
- [x] 1.2 `.peppa/project.json` → `checks` (install, lint, typecheck, test, build) и `deploy`
|
||||
|
||||
## 2. Переводы и страница
|
||||
|
||||
- [ ] 2.1 `locales/ru.json`, `kk.json`, `en.json` с заглушками и одинаковыми ключами; загрузка и проверка ключей
|
||||
- [ ] 2.2 Рендер HTML главной: три блока, title, description, адаптивный CSS, экранирование
|
||||
- [ ] 2.3 HTTP-сервер: `/`, `/healthz`, 404, 405, порт из `$PORT`
|
||||
- [x] 2.1 `locales/ru.json`, `kk.json`, `en.json` с заглушками и одинаковыми ключами; загрузка и проверка ключей
|
||||
- [x] 2.2 Рендер HTML главной: три блока, title, description, адаптивный CSS, экранирование
|
||||
- [x] 2.3 HTTP-сервер: `/`, `/healthz`, 404, 405, порт из `$PORT`
|
||||
|
||||
## 3. Деплой и документация
|
||||
|
||||
- [ ] 3.1 `Dockerfile`, проверка `docker build` и `curl /healthz` (если docker доступен)
|
||||
- [ ] 3.2 `docs/glossary.md` — понятия сайта; README — как запустить
|
||||
- [x] 3.1 `Dockerfile`; docker в среде агента нет — раскладка образа (dist + locales) проверена запуском `node dist/index.js` и `curl /healthz`
|
||||
- [x] 3.2 `docs/glossary.md` — понятия сайта; README — как запустить
|
||||
|
||||
## 4. Тесты и проверка
|
||||
|
||||
- [ ] 4.1 Тесты по сценариям спеки (страница, заглушки, переводы, healthz, 404/405, вёрстка)
|
||||
- [ ] 4.2 Все проверки `bash .gitea/peppa-check.sh <check>` зелёные, `openspec validate ina-2-business-card-site`
|
||||
- [x] 4.1 Тесты по сценариям спеки (страница, заглушки, переводы, healthz, 404/405, вёрстка)
|
||||
- [x] 4.2 Все проверки `bash .gitea/peppa-check.sh <check>` зелёные, `openspec validate ina-2-business-card-site`
|
||||
|
||||
17
test/helpers.ts
Normal file
17
test/helpers.ts
Normal file
@ -0,0 +1,17 @@
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { createApp } from "../src/server.ts";
|
||||
|
||||
export interface Running {
|
||||
url: string;
|
||||
close: () => Promise<void>;
|
||||
}
|
||||
|
||||
export async function startApp(): Promise<Running> {
|
||||
const server = createApp();
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const { port } = server.address() as AddressInfo;
|
||||
return {
|
||||
url: `http://127.0.0.1:${port}`,
|
||||
close: () => new Promise((resolve) => server.close(() => resolve())),
|
||||
};
|
||||
}
|
||||
61
test/i18n.test.ts
Normal file
61
test/i18n.test.ts
Normal file
@ -0,0 +1,61 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { describe, it } from "node:test";
|
||||
import {
|
||||
LOCALES,
|
||||
LOCALES_DIR,
|
||||
loadMessages,
|
||||
REQUIRED_KEYS,
|
||||
validateMessages,
|
||||
} from "../src/i18n.ts";
|
||||
|
||||
describe("Требование: файлы переводов на трёх языках", () => {
|
||||
const ruKeys = Object.keys(JSON.parse(readFileSync(`${LOCALES_DIR}/ru.json`, "utf8"))).sort();
|
||||
|
||||
for (const locale of LOCALES) {
|
||||
it(`Scenario Outline: полный файл перевода — ${locale}`, () => {
|
||||
const data: unknown = JSON.parse(readFileSync(`${LOCALES_DIR}/${locale}.json`, "utf8"));
|
||||
assert.deepEqual(validateMessages(data), []);
|
||||
assert.deepEqual(Object.keys(data as object).sort(), ruKeys);
|
||||
const m = loadMessages(locale);
|
||||
for (const key of [
|
||||
"about.text",
|
||||
"services.text",
|
||||
"contacts.text",
|
||||
"meta.title",
|
||||
"meta.description",
|
||||
] as const) {
|
||||
assert.ok(m[key].trim().length > 0, `${locale}: ${key} is empty`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
it("Scenario: пропущенный ключ", () => {
|
||||
const ru = loadMessages("ru") as Record<string, string>;
|
||||
const { "contacts.heading": _removed, ...broken } = ru;
|
||||
assert.deepEqual(validateMessages(broken), ["missing key contacts.heading"]);
|
||||
});
|
||||
|
||||
it("пустое значение и лишний ключ тоже считаются ошибкой", () => {
|
||||
const ru = loadMessages("ru") as Record<string, string>;
|
||||
const problems = validateMessages({ ...ru, "about.text": " ", "extra.key": "x" });
|
||||
assert.deepEqual(problems, ["empty key about.text", "unknown key extra.key"]);
|
||||
assert.deepEqual(validateMessages([]), ["file must contain a JSON object"]);
|
||||
});
|
||||
|
||||
it("заглушки помечены во всех языках", () => {
|
||||
const markers = { ru: "[ЗАГЛУШКА]", kk: "[ҮЛГІ]", en: "[PLACEHOLDER]" } as const;
|
||||
const placeholderKeys = REQUIRED_KEYS.filter(
|
||||
(k) => !k.endsWith("heading") && !k.endsWith("Label") && !k.startsWith("notFound."),
|
||||
);
|
||||
for (const locale of LOCALES) {
|
||||
const m = loadMessages(locale);
|
||||
for (const key of placeholderKeys) {
|
||||
assert.ok(
|
||||
m[key].startsWith(markers[locale]),
|
||||
`${locale}: ${key} has no placeholder marker`,
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
120
test/site.test.ts
Normal file
120
test/site.test.ts
Normal file
@ -0,0 +1,120 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { after, before, describe, it } from "node:test";
|
||||
import { loadMessages } from "../src/i18n.ts";
|
||||
import { escapeHtml, renderHomePage } from "../src/render.ts";
|
||||
import { type Running, startApp } from "./helpers.ts";
|
||||
|
||||
let app: Running;
|
||||
before(async () => {
|
||||
app = await startApp();
|
||||
});
|
||||
after(async () => {
|
||||
await app.close();
|
||||
});
|
||||
|
||||
const text = (html: string) =>
|
||||
html
|
||||
.replace(/<style>[\s\S]*?<\/style>/, "")
|
||||
.replace(/<[^>]+>/g, " ")
|
||||
.replace(/\s+/g, " ");
|
||||
|
||||
describe("Требование: главная страница с тремя блоками", () => {
|
||||
it("Scenario: открытие главной страницы", async () => {
|
||||
const res = await fetch(`${app.url}/`);
|
||||
assert.equal(res.status, 200);
|
||||
assert.match(res.headers.get("content-type") ?? "", /^text\/html; charset=utf-8/);
|
||||
const html = await res.text();
|
||||
assert.match(html, /<html lang="ru">/);
|
||||
const headings = [...html.matchAll(/<h2[^>]*>([^<]*)<\/h2>/g)].map((m) => m[1]);
|
||||
assert.deepEqual(headings, ["Кто мы", "Чем занимаемся", "Контакты"]);
|
||||
assert.doesNotMatch(html, /<select|hreflang|lang=["'](kk|en)["']|\?lang=/);
|
||||
assert.doesNotMatch(html, /\[ҮЛГІ\]|\[PLACEHOLDER\]/);
|
||||
});
|
||||
|
||||
it("Scenario: несуществующий адрес", async () => {
|
||||
const res = await fetch(`${app.url}/no-such-page`);
|
||||
assert.equal(res.status, 404);
|
||||
const html = await res.text();
|
||||
assert.match(html, /<html lang="ru">/);
|
||||
assert.match(html, /Страница не найдена/);
|
||||
assert.match(html, /<a href="\/">На главную<\/a>/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Требование: заметные заглушки", () => {
|
||||
it("Scenario: заглушки в блоках и вкладке", async () => {
|
||||
const html = await (await fetch(`${app.url}/`)).text();
|
||||
const title = html.match(/<title>([^<]*)<\/title>/)?.[1] ?? "";
|
||||
assert.ok(title.startsWith("[ЗАГЛУШКА]"), title);
|
||||
const description = html.match(/<meta name="description" content="([^"]*)">/)?.[1] ?? "";
|
||||
assert.ok(description.trim().length > 0);
|
||||
assert.match(description, /\[ЗАГЛУШКА\]/);
|
||||
const name = html.match(/<h1>([^<]*)<\/h1>/)?.[1] ?? "";
|
||||
assert.equal(name, "[ЗАГЛУШКА] Название компании");
|
||||
for (const tag of ["p", "li", "dd"]) {
|
||||
const items = [...html.matchAll(new RegExp(`<${tag}[^>]*>([^<]*)</${tag}>`, "g"))];
|
||||
assert.ok(items.length > 0);
|
||||
for (const [, value] of items) assert.match(value ?? "", /^\[ЗАГЛУШКА\]/, `<${tag}>${value}`);
|
||||
}
|
||||
});
|
||||
|
||||
it("Scenario: нет настоящих контактов", async () => {
|
||||
const html = await (await fetch(`${app.url}/`)).text();
|
||||
assert.doesNotMatch(html, /mailto:|tel:/);
|
||||
assert.doesNotMatch(text(html), /[\w.+-]+@[\w-]+\.[\w.]+/);
|
||||
assert.doesNotMatch(text(html), /\+?\d[\d\s()-]{6,}\d/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Требование: адаптивная вёрстка", () => {
|
||||
it("Scenario: телефон 360 px — viewport и отсутствие фиксированных ширин", async () => {
|
||||
const html = await (await fetch(`${app.url}/`)).text();
|
||||
assert.match(html, /<meta name="viewport" content="width=device-width, initial-scale=1">/);
|
||||
const css = html.match(/<style>([\s\S]*?)<\/style>/)?.[1] ?? "";
|
||||
// No fixed widths in px that could exceed a 360 px screen.
|
||||
for (const [, value] of css.matchAll(/(?:^|[;{])\s*(?:min-)?width:\s*(\d+)px/g)) {
|
||||
assert.ok(Number(value) <= 320, `width ${value}px`);
|
||||
}
|
||||
assert.doesNotMatch(css, /white-space:\s*nowrap/);
|
||||
assert.match(css, /box-sizing:border-box/);
|
||||
});
|
||||
|
||||
it("Scenario: очень длинное слово переносится", () => {
|
||||
const m = { ...loadMessages("ru"), "about.text": `[ЗАГЛУШКА] ${"а".repeat(80)}` };
|
||||
const html = renderHomePage("ru", m);
|
||||
assert.ok(html.includes("а".repeat(80)));
|
||||
assert.match(html, /overflow-wrap:anywhere/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Требование: проверка работоспособности", () => {
|
||||
it("Scenario: сайт работает", async () => {
|
||||
const res = await fetch(`${app.url}/healthz`);
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(await res.text(), "ok");
|
||||
});
|
||||
|
||||
it("Scenario: неподдерживаемый метод", async () => {
|
||||
const res = await fetch(`${app.url}/`, { method: "POST" });
|
||||
assert.equal(res.status, 405);
|
||||
assert.equal(res.headers.get("allow"), "GET, HEAD");
|
||||
});
|
||||
|
||||
it("HEAD отвечает без тела", async () => {
|
||||
const res = await fetch(`${app.url}/healthz`, { method: "HEAD" });
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(await res.text(), "");
|
||||
});
|
||||
});
|
||||
|
||||
describe("экранирование текстов", () => {
|
||||
it("спецсимволы из переводов не ломают разметку", () => {
|
||||
assert.equal(
|
||||
escapeHtml(`<a href="x">'&'</a>`),
|
||||
"<a href="x">'&'</a>",
|
||||
);
|
||||
const m = { ...loadMessages("ru"), "meta.description": `[ЗАГЛУШКА] "кавычки" <b>` };
|
||||
const html = renderHomePage("ru", m);
|
||||
assert.match(html, /content="\[ЗАГЛУШКА\] "кавычки" <b>"/);
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user