159 lines
11 KiB
TypeScript
159 lines
11 KiB
TypeScript
// PEP-209, spec product-acceptance: acceptance on one screen — stories in review grouped by
|
||
// product page, «Принять всё» one by one (a failure of one doesn't stop the others), «Поправить»
|
||
// with text, «Объединить в одну» for proposals, one Telegram summary instead of many «готово».
|
||
import assert from "node:assert/strict";
|
||
import { 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, project, runner, setDefaultOwner, teardown } from "./helpers.ts";
|
||
import { MockGitea } from "../src/mock-gitea.ts";
|
||
import { questions, releases, tasks, telegramOutbox, users } from "@peppa/db";
|
||
import { eq, sql } from "drizzle-orm";
|
||
import { stripAsIs } from "@peppa/shared/i18n";
|
||
|
||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||
const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-accept-")), "gitea"));
|
||
const BOT = { id: 73, login: "peppa-bot", token: "mock-token-bot" };
|
||
const OWNER_CHAT = 9301;
|
||
let owner: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
|
||
before(async () => {
|
||
await gitea.start();
|
||
process.env.GITEA_URL = gitea.url;
|
||
process.env.GITEA_TOKEN = BOT.token;
|
||
gitea.addUser(BOT);
|
||
owner = await core.upsertUserFromGitea(db, { id: 9301, login: "mock-owner-accept" }, { access_token: "x" });
|
||
await db.update(users).set({ telegramChatId: OWNER_CHAT, telegramUserId: OWNER_CHAT }).where(eq(users.id, owner.id));
|
||
setDefaultOwner(owner.id);
|
||
});
|
||
after(async () => {
|
||
await gitea.stop();
|
||
await teardown();
|
||
});
|
||
|
||
/** A project with `n` stories in review, each with an open PR; `red` — indexes with red checks. */
|
||
async function inReview(n: number, red: number[] = []) {
|
||
const tp = await project({ turns: [] });
|
||
const proj = await core.getProject(db, tp.key);
|
||
const pj = JSON.stringify({ slug: proj.slug, key: tp.key, name: tp.key, peppaUrl: "http://test", checks: { test: "pnpm test" } });
|
||
writeFileSync(join(tp.dir, ".peppa/project.json"), pj);
|
||
gitea.addRepo(proj.giteaOwner, proj.giteaRepo, { files: { "README.md": "x\n", ".peppa/project.json": pj } });
|
||
gitea.repo(proj.giteaOwner, proj.giteaRepo).collaborators[BOT.login] = "write";
|
||
const refs = [];
|
||
for (let i = 0; i < n; i++) {
|
||
const ref = i === 0 ? await core.resolveTask(db, tp.taskKey) : await core.createTask(db, { projectId: proj.id, title: `Подпись кнопки ${i}` });
|
||
const branch = `task/${ref.key}`;
|
||
const sha = gitea.commit(proj.giteaOwner, proj.giteaRepo, branch, { [`f${i}.txt`]: String(i) });
|
||
const pr = gitea.openPull(proj.giteaOwner, proj.giteaRepo, branch);
|
||
gitea.setStatus(proj.giteaOwner, proj.giteaRepo, sha, "peppa/test", red.includes(i) ? "failure" : "success");
|
||
await core.updateTask(db, ref, { status: "review", prUrl: `${gitea.url}/${proj.giteaOwner}/${proj.giteaRepo}/pulls/${pr.number}` });
|
||
refs.push(await core.resolveTask(db, ref.key));
|
||
}
|
||
return { tp, proj, refs };
|
||
}
|
||
|
||
describe("Приёмка одним экраном", () => {
|
||
test("Scenario: Задачи на ревью — по странице, с описанием, снимками или ссылкой", async () => {
|
||
const { proj, refs } = await inReview(3);
|
||
await core.setTaskResult(db, refs[0]!.task.id, { summary: "На главной кнопка теперь называется «Заказать». Ещё одна фраза." });
|
||
// The first story has a version to check with a screenshot of «/»; the working version too.
|
||
const [pre] = await db.insert(releases).values({ projectId: proj.id, env: "preview", sha: "a1", prNumber: 1, status: "healthy", host: "x-pr1.test", screenshots: [{ path: "/", file: "r1-0.png" }] }).returning();
|
||
const [stg] = await db.insert(releases).values({ projectId: proj.id, env: "staging", sha: "s1", status: "healthy", host: "x-staging.test", screenshots: [{ path: "/", file: "r2-0.png" }] }).returning();
|
||
await db.insert(releases).values({ projectId: proj.id, env: "preview", sha: "a2", prNumber: 2, status: "healthy", host: "x-pr2.test" });
|
||
const screen = await core.acceptScreen(db, proj);
|
||
assert.equal(screen.total, 3);
|
||
assert.equal(screen.checkUrl, "https://x-staging.test");
|
||
const first = screen.groups.flatMap((g) => g.items).find((i) => i.key === refs[0]!.key)!;
|
||
assert.equal(stripAsIs(first.summary), "На главной кнопка теперь называется «Заказать».", "one sentence");
|
||
assert.equal(first.page, "/");
|
||
assert.deepEqual(first.shots, [{ path: "/", before: `/api/releases/${stg!.id}/shots/0`, after: `/api/releases/${pre!.id}/shots/0` }]);
|
||
const second = screen.groups.flatMap((g) => g.items).find((i) => i.key === refs[1]!.key)!;
|
||
assert.equal(second.shots.length, 0);
|
||
assert.equal(second.previewUrl, "https://x-pr2.test", "no screenshot — a link to the version to check");
|
||
assert.deepEqual(screen.groups.map((g) => g.page), ["/", ""], "grouped by page, unknown last");
|
||
});
|
||
|
||
test("Scenario: Нет задач на ревью", async () => {
|
||
const tp = await project({ turns: [] });
|
||
const screen = await core.acceptScreen(db, await core.getProject(db, tp.key));
|
||
assert.equal(screen.total, 0);
|
||
});
|
||
|
||
test("Scenario: «Принять всё» — одна не принялась, остальные приняты, у неё причина", async () => {
|
||
const { proj, refs } = await inReview(3, [1]);
|
||
const r = await runner.acceptAll(db, refs, "web");
|
||
// After the first merge the third is behind the main branch: accepted, Peppa carries it through (PEP-127).
|
||
assert.deepEqual([...r.accepted, ...r.pending], [refs[0]!.key, refs[2]!.key]);
|
||
assert.equal(r.failed.length, 1);
|
||
assert.equal(r.failed[0]!.key, refs[1]!.key);
|
||
assert.match(stripAsIs(r.failed[0]!.reason), /проверки не пройдены/);
|
||
assert.equal((await core.resolveTask(db, refs[0]!.key)).task.status, "done");
|
||
const third = (await core.resolveTask(db, refs[2]!.key)).task;
|
||
assert.ok(third.status === "done" || (await core.getPendingAccept(db, third.id)), "accepted (or carried to the merge)");
|
||
assert.equal((await core.resolveTask(db, refs[1]!.key)).task.status, "review");
|
||
const item = (await core.acceptScreen(db, proj)).groups.flatMap((g) => g.items)[0]!;
|
||
assert.match(stripAsIs(item.failed!), /проверки не пройдены/, "the page shows why it stayed");
|
||
assert.equal(stripAsIs(core.acceptAllSummary({ accepted: 2, pending: 0, failed: 1 })), "Принято 2, на доработке 1. Рабочая версия обновится через несколько минут");
|
||
});
|
||
|
||
test("Scenario: «Поправить» с текстом возвращает задачу агенту с этим текстом", async () => {
|
||
const { refs, tp } = await inReview(1);
|
||
const r = await runner.fixStory(db, refs[0]!, owner, "Кнопка должна быть синей");
|
||
assert.equal((await tp.task()).status, "in_progress");
|
||
assert.ok(r.delivered, "an agent got it");
|
||
await tp.waitLog("the remark reached the agent", (e) => e.ev === "prompt" && String((e as { prompt?: unknown }).prompt ?? "").includes("Кнопка должна быть синей"));
|
||
for (const s of await core.listSessions(db, { active: true, taskId: refs[0]!.task.id })) await runner.stopSession(db, s.id);
|
||
});
|
||
});
|
||
|
||
describe("Объединить предложения в одну задачу", () => {
|
||
test("Scenario: Три правки подписей", async () => {
|
||
const tp = await project({ turns: [] });
|
||
const proj = await core.getProject(db, tp.key);
|
||
const made = [];
|
||
for (const title of ["Подпись «Купить»", "Подпись «Корзина»", "Подпись «Оплатить»"]) made.push(await core.createTask(db, { projectId: proj.id, title, description: `Поменять ${title}`, origin: "acceptance" }));
|
||
await db.update(tasks).set({ proposed: true }).where(eq(tasks.projectId, proj.id));
|
||
const r = await runner.mergeProposals(db, owner, made.map((x) => x.task.id));
|
||
assert.equal(r.key, made[0]!.key);
|
||
const main = (await core.resolveTask(db, made[0]!.key)).task;
|
||
assert.equal(main.proposed, false, "in the backlog");
|
||
assert.equal(main.status, "backlog");
|
||
assert.match(main.description ?? "", /Подпись «Корзина»[\s\S]*Подпись «Оплатить»/);
|
||
for (const x of made.slice(1)) assert.ok((await core.resolveTask(db, x.key)).task.archivedAt, "archived");
|
||
await assert.rejects(runner.mergeProposals(db, owner, [made[0]!.task.id]), /хотя бы две/);
|
||
});
|
||
});
|
||
|
||
describe("Сводка готовых в Telegram", () => {
|
||
test("Scenario: Пять готовых задач — одна сводка, отдельных «готово» нет", async () => {
|
||
process.env.PEPPA_ACCEPT_DIGEST = "on";
|
||
process.env.PEPPA_ACCEPT_DIGEST_SETTLE_SEC = "300";
|
||
const { proj, refs } = await inReview(5);
|
||
const t0 = Date.now();
|
||
for (const ref of refs) await core.sendReviewCard(db, ref, { text: `${ref.key} готова` }, null, null as never).catch(() => null);
|
||
const cards = (await db.select().from(questions).where(eq(questions.projectId, proj.id))).filter((q) => q.msgType === "done");
|
||
assert.equal(cards.length, 5);
|
||
for (const q of cards) assert.equal(await core.acceptDigestHold(db, q, new Date(t0 + 60_000)), "wait", "within the pause");
|
||
for (const q of cards) assert.equal(await core.acceptDigestHold(db, q, new Date(t0 + 400_000)), "held", "more than two within an hour");
|
||
assert.equal(await core.acceptDigestTick(db, { now: new Date(t0 + 60_000) }), 0, "not before the pause");
|
||
assert.equal(await core.acceptDigestTick(db, { now: new Date(t0 + 400_000) }), 1);
|
||
assert.equal(await core.acceptDigestTick(db, { now: new Date(t0 + 460_000) }), 0, "the same stories — no second summary");
|
||
const tg = (await db.select().from(telegramOutbox).where(eq(sql`json_extract(${telegramOutbox.params}, '$.chat_id')`, OWNER_CHAT))).filter((r) => r.dedupeKey.startsWith(`acc:${proj.id}:`));
|
||
assert.equal(tg.length, 1, "one summary");
|
||
assert.match(stripAsIs(String(tg[0]!.params.text)), /готово к приёмке — задач: 5/);
|
||
assert.match(JSON.stringify(tg[0]!.params.reply_markup), new RegExp(`/p/${proj.key}/accept`), "the button opens «Приёмка»");
|
||
delete process.env.PEPPA_ACCEPT_DIGEST;
|
||
delete process.env.PEPPA_ACCEPT_DIGEST_SETTLE_SEC;
|
||
});
|
||
|
||
test("Scenario: Одна готовая задача — обычное сообщение после паузы", async () => {
|
||
process.env.PEPPA_ACCEPT_DIGEST = "on";
|
||
const { proj, refs } = await inReview(1);
|
||
await core.sendReviewCard(db, refs[0]!, { text: "готова" }, null, null as never).catch(() => null);
|
||
const [q] = (await db.select().from(questions).where(eq(questions.projectId, proj.id))).filter((x) => x.msgType === "done");
|
||
assert.equal(await core.acceptDigestHold(db, q!, new Date(q!.createdAt.getTime() + 400_000)), "send");
|
||
delete process.env.PEPPA_ACCEPT_DIGEST;
|
||
});
|
||
});
|