peppa/packages/testkit/test/products-move.test.ts
peppa-bot f3d10a4c25 PEP-243: платформа называется FORGE — название во всех текстах для людей и подсказках агентам, адрес forge.telecom.quest
«Peppa FACTORY» → «FORGE» в экранах, сообщениях, словарях en/kk, шаблоне и тестах; «Пеппа» → «FORGE» в подсказках
агентам и правилах; логотип, значок, версия кэша service worker; в словаре старые названия — в «Нельзя».
Внутренние имена (CLI peppa, PEPPA_*, MCP-сервер peppa, ключи PEP-N) не меняются. Второй адрес — в mac-route.sh.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 11:18:49 +05:00

100 lines
7.5 KiB
TypeScript
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.

// PEP-231: the projects' products move from the Mac to the server WITH their data and without a
// deploy report. The scripts are run by an administrator on real hosts; here — the rules that
// keep users' data safe, checked on the scripts themselves, and the Mac route rule on real names.
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { describe, test } from "node:test";
const path = (p: string) => fileURLToPath(new URL(`../../../scripts/server-move/${p}`, import.meta.url));
const read = (p: string) => readFileSync(path(p), "utf8");
const fn = (src: string, name: string) => {
const from = src.indexOf(`\n${name}() {`);
assert.ok(from >= 0, `нет функции ${name}`);
return src.slice(from, src.indexOf("\n}\n", from));
};
describe("PEP-231: продукт переезжает на сервер со своими данными", () => {
const move = read("products-move.sh");
const up = read("product-up.sh");
test("Сценарий: скрипты разбираются оболочкой", () => {
for (const f of ["products-move.sh", "product-up.sh", "mac-route.sh"]) {
const r = spawnSync("bash", ["-n", path(f)], { encoding: "utf8" });
assert.equal(r.status, 0, `${f}: ${r.stderr}`);
}
});
test("Сценарий: на сервере уже есть данные этого продукта — перенос не начинается и ничего не убирает", () => {
const pre = fn(move, "precheck");
assert.match(pre, /docker ps -aq --filter label=com\.docker\.compose\.project=\$p/, "контейнеры проекта на сервере");
assert.match(pre, /docker volume ls -q \| grep -E '\^\$\{p\}_'/, "тома проекта на сервере");
const cmd = fn(move, "cmd_move");
const guard = cmd.indexOf("run_guarded precheck");
assert.ok(guard > 0 && guard < cmd.indexOf("server_clean"), "предпроверка — до любой уборки");
assert.match(cmd.slice(guard, cmd.indexOf("\n", guard)), /return 1/, "провал предпроверки — выход без уборки сервера");
assert.doesNotMatch(fn(move, "transfer"), /server_clean|down/, "сам перенос на сервере ничего не удаляет");
});
test("Сценарий: продукт на сервере не прошёл проверку — созданное убрано, на Mac снова работает", () => {
const cmd = fn(move, "cmd_move");
const fail = cmd.slice(cmd.indexOf("else"));
assert.ok(fail.indexOf("server_clean") < fail.indexOf("mac_start") && fail.indexOf("server_clean") > 0);
// set -e не действует в условии if — шаги идут через run_guarded, иначе сбой копирования прошёл бы молча.
assert.match(fn(move, "run_guarded"), /set \+e; \( set -e; "\$@" \); rc=\$\?; set -e/);
assert.match(cmd, /if run_guarded move_steps/);
});
test("Сценарий: данные сверяются на обеих сторонах, Postgres едет дампом", () => {
const copy = fn(move, "copy_volume");
assert.match(copy, /\[ "\$a" = "\$b" \] \|\| die/, "суммы файлов тома на Mac и сервере");
assert.match(fn(move, "pg_restore_all"), /pg-sum[\s\S]*различается/, "сумма содержимого базы");
const tr = fn(move, "transfer");
assert.ok(tr.indexOf("pg_restore_all") < tr.lastIndexOf('UP up "$p" "$sha"'), "база восстановлена до запуска приложения");
assert.match(up, /\/proc\/1\/comm\)" = postgres/, "ждём настоящий postgres, а не временный сервер initdb");
assert.match(up, /уже не пустая[\s\S]*не перезаписываю/, "непустая база не перезаписывается");
});
test("Сценарий: владельцу не приходит сообщение о новой версии — отчёт о выкладке не уходит", () => {
assert.doesNotMatch(up, /api\/hooks\/gitea|X-Peppa-Event/, "product-up.sh в FORGE не пишет");
assert.match(up, /rm -f "\$dir\/override\.json" # значения уже в контейнере/, "секреты на диске не остаются");
});
test("Сценарий: продукт получает настройки контейнера Mac, а не то, что сейчас записано в FORGE", () => {
// Перенос 22.11: у пяти продуктов секреты в FORGE были новее последней выкладки (или заведены с ошибкой) —
// переезд не должен менять поведение продукта; новые секреты придут со следующей выкладкой.
const tr = fn(move, "transfer");
assert.ok(tr.indexOf('mac_env "$p"') > 0 && tr.indexOf('mac_env "$p"') < tr.indexOf("UP up"), "окружение Mac — до первого запуска на сервере");
assert.match(fn(move, "mac_env"), /if e not in img/, "только то, что задано сверх образа");
assert.match(fn(move, "mac_env"), /umask 077/, "файл с окружением — только владельцу");
assert.match(up, /if \[ -s "\$dir\/override-mac\.json" \]; then[^\n]*else secrets; fi/, "секреты FORGE — только когда окружения Mac нет");
assert.match(tr, /rm -f \$RP\/products-move\/\$p\/override-mac\.json/, "после запуска файл с сервера убран");
assert.match(fn(move, "env_diff"), /env_sums/, "сверка окружения — по суммам, без значений");
});
test("Сценарий: репетиция — Mac не останавливается", () => {
const tr = fn(move, "transfer");
const stops = [...tr.matchAll(/docker stop/g)].length;
assert.equal([...tr.matchAll(/"\$mode" = move/g)].length, 2, "обе остановки — только в режиме move");
assert.equal(stops, 2);
});
});
describe("PEP-231: адрес продукта без контейнера на Mac идёт на сервер", () => {
const route = read("mac-route.sh");
const m = /rule: "HostRegexp\(`([^`]+)`\)"\n\s+service: peppa-server\n\s+entryPoints: \[web\]\n\s+priority: (\d+)/.exec(route);
test("Сценарий: правило ловит адреса продуктов и не трогает остальные", () => {
assert.ok(m, "правило продуктов в mac-route.sh");
const re = new RegExp(m![1].replaceAll("\\\\", "\\"));
for (const h of ["mrv-staging.telecom.quest", "qazaq-legacy-foundation-web-prod.telecom.quest", "dika-pr19.telecom.quest"]) assert.ok(re.test(h), h);
for (const h of ["git.telecom.quest", "someone.telecom.quest", "bugsink.telecom.quest", "mrv-staging.example.com", "a.mrv-prod.telecom.quest"]) assert.ok(!re.test(h), h);
});
test("Сценарий: страницы Gitea на Mac не задеты — нет правила «всё неизвестное → сервер»", () => {
assert.equal(m![2], "2", "выше общего правила страниц (1), ниже маршрута контейнера");
assert.doesNotMatch(route, /HostRegexp\(`\^\.\+/, "общее правило на весь домен");
});
});