peppa/packages/testkit/test/old-git-cleanup.test.ts
peppa-bot bc14e5824c Заход приёмки 27.11: стыковка задач между собой [skip ci]
Двадцать задач слиты одним заходом; три правила одной задачи ломались кодом другой:

- PEP-273 × PEP-250, PEP-279: три новых файла веба брали `next/link` напрямую — переведены на
  `@/components/Link` (сторож no-prefetch.test.ts).
- PEP-281 × PEP-272: адрес аватара в health-anon.test.ts и спеке web-auth — на git.vibe42.kz
  (сторож old-git-cleanup.test.ts не пускает старый адрес в репозиторий).
- PEP-217 × PEP-281: в observe.db миграции стали подряд (web_vitals — версия 4, монитор «Интернет» —
  версия 5); тест PEP-281 возвращал файл «к версии 3» и повторял чужую миграцию. Версия берётся по
  самой миграции (`observeMigrationIndex`).

Стыки, решённые при слиянии: страница /gitea и мок `/repos/search` (PEP-273 × PEP-280; после
«Сделать закрытым» страница берёт свежий список мимо кэша), импорты (PEP-250 × PEP-302,
PEP-279 × PEP-291, PEP-273 × PEP-304), память — файл на задачу по раскладке PEP-306.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-27 10:11:36 +05:00

90 lines
3.9 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-281, spec gitea-integration «Платформа не ссылается на старый Git»: after the move (PEP-230) the
// platform's repositories live in git.vibe42.kz; the old Gitea is archived. No file of the platform (code,
// docs, settings examples, test data) names it or reads its token; the default Gitea address is the new
// one; the built-in «Интернет» monitor created before the move checks the new address after an upgrade.
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { DatabaseSync } from "node:sqlite";
import { after, test } from "node:test";
const root = new URL("../../../", import.meta.url).pathname;
const OLD_HOST = ["git", "telecom", "quest"].join(".");
const OLD_TOKEN = ["GITEA", "OLD", "TOKEN"].join("_");
const NEW_HOST = "git.vibe42.kz";
/** Files allowed to name the old host or token, and why. */
const ALLOWED: Record<string, string> = {
"packages/core/src/observe.ts": "the observe.db migration replaces the old host in existing monitors",
"openspec/specs/gitea-integration/spec.md": "the requirement itself names what must not appear",
};
const tmp = mkdtempSync(join(tmpdir(), "pep281-"));
process.env.PEPPA_OBSERVE_DB = join(tmp, "observe.db");
const core = await import("@peppa/core");
after(() => {
core.closeObserveDb();
rmSync(tmp, { recursive: true, force: true });
});
test("В репозитории нет старого адреса", () => {
const files = execFileSync("git", ["ls-files", "-z"], { cwd: root, encoding: "utf8" })
.split("\0")
.filter((f) => f && !f.startsWith("openspec/changes/archive/"));
const found: string[] = [];
for (const f of files) {
let text: string;
try {
text = readFileSync(join(root, f), "utf8");
} catch {
continue; // a deleted but still tracked file, a symlink to a directory
}
if (!ALLOWED[f] && (text.includes(OLD_TOKEN) || text.includes(OLD_HOST))) found.push(f);
}
assert.deepEqual(found, []);
});
test("GITEA_URL не задан", async () => {
const { loadEnv } = await import("@peppa/shared");
const saved = process.env.GITEA_URL;
delete process.env.GITEA_URL;
try {
assert.equal(loadEnv().GITEA_URL, `https://${NEW_HOST}`);
} finally {
if (saved !== undefined) process.env.GITEA_URL = saved;
}
assert.ok(core.DEFAULT_INTERNET_HOSTS.includes(NEW_HOST));
assert.ok(!core.DEFAULT_INTERNET_HOSTS.includes(OLD_HOST));
});
/** A monitor written straight into the file, then the file put back to the version before PEP-281. */
function oldMonitor(hosts: string[]): number {
core.closeObserveDb();
rmSync(process.env.PEPPA_OBSERVE_DB!, { force: true });
core.observeDb();
core.closeObserveDb();
const raw = new DatabaseSync(process.env.PEPPA_OBSERVE_DB!);
const iso = new Date().toISOString();
const row = raw
.prepare(
`INSERT INTO monitors (name, kind, target, interval_sec, timeout_ms, fail_threshold, recover_threshold, created_by, created_at, updated_at, state_since)
VALUES ('Интернет', 'internet', ?, 60, 5000, 3, 2, 'system', ?, ?, ?) RETURNING id`,
)
.get(JSON.stringify({ hosts }), iso, iso, iso) as { id: number };
// The version right before the PEP-281 migration — other migrations (PEP-217: web_vitals) stay applied.
raw.exec(`PRAGMA user_version = ${core.observeMigrationIndex(OLD_HOST)}`);
raw.close();
return row.id;
}
test("Мониторинг «Интернет», созданный до переезда", () => {
const id = oldMonitor(["registry.npmjs.org", OLD_HOST]);
assert.deepEqual(core.getMonitor(id)!.target, { hosts: ["registry.npmjs.org", NEW_HOST] });
});
test("Новый адрес уже был в списке", () => {
const id = oldMonitor([NEW_HOST, OLD_HOST]);
assert.deepEqual(core.getMonitor(id)!.target, { hosts: [NEW_HOST] });
});