156 lines
8.7 KiB
TypeScript
156 lines
8.7 KiB
TypeScript
// PEP-66: project page tabs «Код», «Спеки», «PR» (mock-gitea + real git) and epics in core.
|
||
import assert from "node:assert/strict";
|
||
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
|
||
import { tmpdir } from "node:os";
|
||
import { join } from "node:path";
|
||
import { after, before, describe, test } from "node:test";
|
||
import { core, db, runner, teardown } from "./helpers.ts";
|
||
import { MockGitea } from "../src/mock-gitea.ts";
|
||
|
||
const TMP = mkdtempSync(join(tmpdir(), "peppa-tabs-"));
|
||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||
|
||
const gitea = new MockGitea(join(TMP, "gitea"));
|
||
const ALICE = { id: 71, login: "mock-tabs-alice", token: "mock-token-tabs-alice" };
|
||
const BOT = { id: 72, login: "peppa-bot", token: "mock-token-tabs-bot" };
|
||
let alice: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
|
||
before(async () => {
|
||
await gitea.start();
|
||
process.env.GITEA_URL = gitea.url;
|
||
process.env.GITEA_TOKEN = BOT.token;
|
||
gitea.addUser(ALICE);
|
||
gitea.addUser(BOT);
|
||
alice = await core.upsertUserFromGitea(db, ALICE, { access_token: ALICE.token });
|
||
});
|
||
after(async () => {
|
||
await gitea.stop();
|
||
await teardown();
|
||
});
|
||
|
||
/** A project on a mock repo; the working copy holds .peppa/project.json (checks) and specs. */
|
||
async function tabsProject(key: string, files: Record<string, string> | null, workspace: Record<string, string> = {}) {
|
||
const slug = `mock-tabs-${key.toLowerCase()}`;
|
||
if (files) gitea.addRepo(ALICE.login, slug, { files, admins: [ALICE.login] });
|
||
const ws = join(TMP, "ws", slug);
|
||
for (const [f, text] of Object.entries(workspace)) {
|
||
mkdirSync(join(ws, f, ".."), { recursive: true });
|
||
writeFileSync(join(ws, f), text);
|
||
}
|
||
mkdirSync(ws, { recursive: true });
|
||
return core.createProject(db, { slug, key, name: `Mock ${key}`, giteaOwner: ALICE.login, workspacePath: ws, ownerId: alice.id });
|
||
}
|
||
|
||
describe("Вкладка «Код»", () => {
|
||
test("Scenario: Репозиторий с кодом — README, ветки main и task/…, последний коммит main", async () => {
|
||
const p = await tabsProject("MTCODE", { "README.md": "# Pay\n\nПлатежи.", "src/index.ts": "export {};\n" });
|
||
gitea.commit(ALICE.login, p.giteaRepo, "main", { "src/pay.ts": "export const pay = 1;\n" }, "Оплата картой");
|
||
gitea.commit(ALICE.login, p.giteaRepo, "task/MTCODE-3", { "src/form.ts": "export {};\n" }, "MTCODE-3: форма");
|
||
const code = await runner.repoOverview(db, p, { fresh: true });
|
||
assert.equal(code.error, null);
|
||
assert.equal(code.defaultBranch, "main");
|
||
assert.match(code.readme!.text, /^# Pay/);
|
||
assert.equal(code.readme!.path, "README.md");
|
||
assert.deepEqual(code.branches.map((b) => b.name), ["main", "task/MTCODE-3"], "default branch first");
|
||
assert.equal(code.commits[0]!.message, "Оплата картой");
|
||
assert.equal(code.commits[0]!.sha, gitea.sha(ALICE.login, p.giteaRepo, "main"));
|
||
assert.equal(code.commits.length, 2);
|
||
assert.equal(code.url, `${gitea.url}/${ALICE.login}/${p.giteaRepo}`);
|
||
});
|
||
|
||
test("Scenario: Gitea недоступна — ссылка на репозиторий и «Gitea сейчас не отвечает», без исключения", async () => {
|
||
const p = await tabsProject("MTDOWN", { "README.md": "# Down" });
|
||
const url = process.env.GITEA_URL;
|
||
process.env.GITEA_URL = "http://127.0.0.1:9";
|
||
try {
|
||
const code = await runner.repoOverview(db, p, { fresh: true });
|
||
assert.equal(code.error, "Gitea сейчас не отвечает");
|
||
assert.equal(code.url, `http://127.0.0.1:9/${ALICE.login}/${p.giteaRepo}`);
|
||
assert.equal(code.readme, null);
|
||
assert.equal((await runner.openPulls(db, p, { fresh: true })).error, "Gitea сейчас не отвечает");
|
||
} finally {
|
||
process.env.GITEA_URL = url;
|
||
}
|
||
// A failure is not cached: the next call asks Gitea again.
|
||
assert.equal((await runner.repoOverview(db, p)).error, null);
|
||
});
|
||
|
||
test("репозиторий без README и пустой репозиторий", async () => {
|
||
const p = await tabsProject("MTNORD", { "src/a.ts": "1" });
|
||
const code = await runner.repoOverview(db, p, { fresh: true });
|
||
assert.equal(code.readme, null);
|
||
assert.equal(code.error, null);
|
||
const missing = await tabsProject("MTMISS", null);
|
||
assert.equal((await runner.repoOverview(db, missing, { fresh: true })).error, "Репозиторий не найден в Gitea");
|
||
});
|
||
});
|
||
|
||
describe("Вкладка «PR»", () => {
|
||
test("Scenario: PR стори — ключ стори и «Проверки: 2 из 2 пройдены»; PR без стори — без проверок", async () => {
|
||
const p = await tabsProject("MTPR", { "README.md": "# PR" }, { ".peppa/project.json": JSON.stringify({ key: "MTPR", checks: { test: "pnpm test", build: "pnpm build" } }) });
|
||
const ref = await core.createTask(db, { projectId: p.id, title: "Форма оплаты" });
|
||
const sha = gitea.commit(ALICE.login, p.giteaRepo, `task/${ref.key}`, { "f.ts": "1" });
|
||
gitea.openPull(ALICE.login, p.giteaRepo, `task/${ref.key}`, `${ref.key}: форма оплаты`);
|
||
gitea.commit(ALICE.login, p.giteaRepo, "chore/deps", { "g.ts": "1" });
|
||
gitea.openPull(ALICE.login, p.giteaRepo, "chore/deps", "Обновить зависимости");
|
||
for (const check of ["test", "build"]) await core.upsertCheckRun(db, p, ref.task.id, { sha, check, state: "success", branch: `task/${ref.key}` });
|
||
|
||
const { pulls, error } = await runner.openPulls(db, p, { fresh: true });
|
||
assert.equal(error, null);
|
||
assert.equal(pulls.length, 2);
|
||
const story = pulls.find((x) => x.branch === `task/${ref.key}`)!;
|
||
assert.equal(story.task?.key, ref.key);
|
||
assert.equal(story.task?.ci.label, "Проверки: 2 из 2 пройдены");
|
||
assert.match(story.url, /\/pulls\/1$/);
|
||
assert.equal(pulls.find((x) => x.branch === "chore/deps")!.task, null);
|
||
});
|
||
|
||
test("Scenario: Открытых PR нет", async () => {
|
||
const p = await tabsProject("MTNOPR", { "README.md": "# none" });
|
||
assert.deepEqual(await runner.openPulls(db, p, { fresh: true }), { pulls: [], error: null });
|
||
});
|
||
});
|
||
|
||
describe("Вкладка «Спеки»", () => {
|
||
const SPEC = "# web-auth Specification\n\n## Purpose\nВход в веб через Gitea.\n\n## Requirements\n\n### Requirement: Вход\nтекст\n\n#### Scenario: a\n- **WHEN** x\n\n### Requirement: Выход\nтекст\n";
|
||
|
||
test("Scenario: Есть спеки — имя, назначение и число требований", async () => {
|
||
const p = await tabsProject("MTSPEC", null, { "openspec/specs/web-auth/spec.md": SPEC, "openspec/specs/billing/spec.md": "# billing\n\n## Purpose\nTBD - created by archiving change x.\n\n## Requirements\n\n### Requirement: Счёт\n" });
|
||
const specs = core.listSpecs(p);
|
||
assert.deepEqual(specs.map((s) => [s.name, s.purpose, s.requirements]), [
|
||
["billing", "", 1],
|
||
["web-auth", "Вход в веб через Gitea.", 2],
|
||
]);
|
||
assert.match(specs[1]!.text, /### Requirement: Выход/);
|
||
});
|
||
|
||
test("Scenario: Спек нет — пустой список", async () => {
|
||
const p = await tabsProject("MTNOSP", null);
|
||
assert.deepEqual(core.listSpecs(p), []);
|
||
});
|
||
});
|
||
|
||
describe("Эпики (цели как метки стори)", () => {
|
||
test("Scenario: Новая стори в эпике; Стори без эпика; Эпик в архив — стори не меняется", async () => {
|
||
const p = await tabsProject("MTEPIC", null);
|
||
const epic = await core.createEpic(db, p.id, "Оплата картой", "Приём оплат");
|
||
const withEpic = await core.createTask(db, { projectId: p.id, title: "Форма оплаты", goalId: epic.id });
|
||
const without = await core.createTask(db, { projectId: p.id, title: "Без эпика" });
|
||
assert.equal(withEpic.task.goalId, epic.id);
|
||
assert.equal(without.task.goalId, null);
|
||
assert.deepEqual((await core.listEpics(db, p.id)).map((e) => e.title), ["Оплата картой"]);
|
||
assert.match((await import("../../mcp/src/format.ts")).formatTask(await core.getTaskDetails(db, withEpic)), /## Эпик #\d+: Оплата картой\n\nПриём оплат/);
|
||
|
||
await core.updateEpic(db, p.id, epic.id, { status: "archived" });
|
||
assert.deepEqual(await core.listEpics(db, p.id), []);
|
||
assert.equal((await core.resolveTask(db, withEpic.key)).task.goalId, epic.id, "the story keeps its epic");
|
||
});
|
||
|
||
test("эпик чужого проекта не ставится на стори", async () => {
|
||
const a = await tabsProject("MTEPA", null);
|
||
const b = await tabsProject("MTEPB", null);
|
||
const foreign = await core.createEpic(db, b.id, "Чужой");
|
||
await assert.rejects(core.createTask(db, { projectId: a.id, title: "x", goalId: foreign.id }));
|
||
});
|
||
});
|