peppa/packages/testkit/test/done-requires-merge.test.ts

113 lines
6.1 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-175: «Готово» = смержено — перенос в «Готово», защита done, «Закрыть без изменений», сверка.
// mock-claude runners, mock Gitea.
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, teardown, waitFor, type TestProject } from "./helpers.ts";
import { MockGitea } from "../src/mock-gitea.ts";
import { events } from "@peppa/db";
import { and, eq } from "drizzle-orm";
process.env.PEPPA_SECRET = "mock-secret-for-tests";
const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-donepr-")), "gitea"));
const BOT = { id: 71, login: "peppa-bot", token: "mock-token-bot" };
const CHECKS = { typecheck: "pnpm typecheck", test: "pnpm test" };
before(async () => {
await gitea.start();
process.env.GITEA_URL = gitea.url;
process.env.GITEA_TOKEN = BOT.token;
gitea.addUser(BOT);
});
after(async () => {
await gitea.stop();
await teardown();
});
type Turns = Parameters<typeof project>[0]["turns"];
/** A story with an open green PR (task/<KEY>-1) in mock Gitea; `review` puts it in review right away. */
async function prTask(turns: Turns, review = true) {
const tp: TestProject = 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: CHECKS });
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";
let n = 0;
const push = () => gitea.commit(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`, { [`f${n++}.txt`]: String(n) });
const green = (s: string) => {
for (const c of Object.keys(CHECKS)) gitea.setStatus(proj.giteaOwner, proj.giteaRepo, s, `peppa/${c}`, "success");
};
green(push());
const pr = gitea.openPull(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`);
const prUrl = `${gitea.url}/${proj.giteaOwner}/${proj.giteaRepo}/pulls/${pr.number}`;
const ref = () => core.resolveTask(db, tp.taskKey);
if (review) await core.updateTask(db, await ref(), { status: "review", prUrl });
const pull = () => gitea.repo(proj.giteaOwner, proj.giteaRepo).pulls[pr.number - 1]!;
const status = async () => (await ref()).task.status;
const toReview = async () => core.updateTask(db, await ref(), { status: "review" });
const stopAll = async () => {
for (const s of (await core.listSessions(db, { active: true })).filter((s) => s.projectId === proj.id)) await runner.stopSession(db, s.id);
};
/** Someone else's story lands in main: the PR branch is behind now (no conflict). */
const mainMoves = () => gitea.commit(proj.giteaOwner, proj.giteaRepo, "main", { [`main${n++}.txt`]: "m" });
const head = () => gitea.sha(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`);
const contains = (sha: string) => gitea.ahead(gitea.repo(proj.giteaOwner, proj.giteaRepo), `task/${tp.taskKey}`, sha) === 0;
const taskEvents = async (type: string) => db.select().from(events).where(and(eq(events.taskId, (await ref()).task.id), eq(events.type, type)));
return { tp, proj, prUrl, push, green, ref, pull, status, toReview, stopAll, taskEvents, mainMoves, head, contains };
}
describe("«Готово» = смержено", () => {
test("Сценарий: зелёный PR без конфликта — перенос в «Готово» мержит и закрывает", async () => {
const t = await prTask([]);
const r = await runner.moveTask(db, await t.ref(), "done");
assert.equal(r.pending, undefined);
assert.equal(t.pull().merged, true);
assert.equal(await t.status(), "done");
});
test("Сценарий: конфликт — «принято», агенту ушло задание, после мержа done", async () => {
const t = await prTask([]);
t.pull().mergeable = false;
const r = await runner.moveTask(db, await t.ref(), "done");
assert.equal(r.pending, true);
assert.notEqual(await t.status(), "done");
assert.ok(await core.getPendingAccept(db, (await t.ref()).task.id));
const ev = await t.tp.waitLog("rebase prompt", (e) => e.ev === "prompt" && String(e.prompt).includes("rebase"));
assert.match(String(ev.prompt), /force-with-lease/);
t.pull().mergeable = true;
await t.toReview();
await runner.pendingAcceptTick(db, { now: new Date() });
assert.equal(t.pull().merged, true);
assert.equal(await t.status(), "done");
await t.stopAll();
});
test("Сценарий: обход — done с открытым PR отказывает, «Закрыть без изменений» закрывает", async () => {
const t = await prTask([]);
await assert.rejects(core.updateTask(db, await t.ref(), { status: "done" }), /не приняты в код/);
assert.equal(await t.status(), "review");
await assert.rejects(runner.closeWithoutChanges(db, await t.ref(), { login: "mock-pm" }, " "), /почему/);
await runner.closeWithoutChanges(db, await t.ref(), { login: "mock-pm" }, "не нужна");
assert.equal(t.pull().state, "closed");
assert.equal(t.pull().merged, false);
assert.equal(await t.status(), "done");
const [ev] = await t.taskEvents("closed_without_merge");
assert.equal((ev!.payload as any).login, "mock-pm");
assert.equal((ev!.payload as any).reason, "не нужна");
});
test("Сверка: «Готово» с открытым PR находится раз в час", async () => {
const t = await prTask([]);
await core.updateTask(db, await t.ref(), { status: "done" }, undefined, undefined, { closeUnmerged: true });
const now = new Date();
const found = await runner.doneOpenPrTick(db, { now });
assert.ok(found.some((x) => x.startsWith(t.tp.taskKey)));
assert.deepEqual(await runner.doneOpenPrTick(db, { now: new Date(now.getTime() + 60_000) }), [], "не чаще раза в час");
});
});