peppa/packages/testkit/test/products-move.test.ts
peppa-bot e83302c398
Some checks failed
peppa/lint lint: success за 1с
peppa/typecheck typecheck: success за 21с
peppa/build build: success за 15с
peppa/test test: failure за 693с
peppa-ci / ci (pull_request) Failing after 12m51s
PEP-231: продукты переезжают вместе с данными и без отчёта о выкладке
products-move.sh (Mac) и product-up.sh (сервер): та же версия, тома со сверкой сумм,
Postgres дампом, предпроверки и откат, превью, раннер проверок. Маршрут Mac: на сервер
идут только адреса продуктов — общее правило спорило со страницами Gitea.

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

88 lines
6.0 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 в Peppa не пишет");
assert.match(up, /rm -f "\$dir\/override\.json" # значения уже в контейнере/, "секреты на диске не остаются");
});
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\(`\^\.\+/, "общее правило на весь домен");
});
});