peppa/packages/testkit/test/product-link.test.ts

246 lines
13 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-145, spec product-link: the product of a project always opens by a link — the system
// story when there is no link, «Показывать всем: сам / по кнопке», the card's honest status and
// the link in the message about an accepted story. Provisioning scenarios — web.test.ts.
import assert from "node:assert/strict";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, before, describe, test } from "node:test";
import { questions, releases } from "@peppa/db";
import { and, eq, isNull } from "drizzle-orm";
import { core, db, runner, teardown } from "./helpers.ts";
import { MockGitea } from "../src/mock-gitea.ts";
process.env.PEPPA_SECRET = "mock-secret-for-tests";
delete process.env.PEPPA_PRODUCT_LINK;
const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-plink-")), "gitea"));
const BOT = { id: 81, login: "peppa-bot", token: "mock-token-bot" };
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();
});
let n = 0;
async function proj() {
n++;
const slug = `mock-shop-${n}`;
const p = await core.createProject(db, { slug, key: `SH${String.fromCharCode(64 + n)}`, name: `Магазин ${n}`, giteaOwner: BOT.login, giteaRepo: slug, workspacePath: `/tmp/${slug}` });
gitea.addRepo(BOT.login, slug, { files: { "README.md": "# shop\n" } });
return p;
}
const story = async (projectId: number, title: string, status?: "done" | "review") => {
const ref = await core.createTask(db, { projectId, title });
if (status) await core.updateTask(db, ref, { status });
return ref;
};
const rel = (projectId: number, env: "preview" | "staging" | "prod", sha: string, status: "healthy" | "failed" | "rolled_back" | "deploying" = "healthy", extra: Partial<typeof releases.$inferInsert> = {}) =>
db.insert(releases).values({ projectId, env, sha, status, host: `shop-${env}.mock.test`, ...extra }).returning().then((r) => r[0]!);
const linkTasks = async (projectId: number) => (await core.listTasks(db, { projectId })).filter((t) => t.title === core.PRODUCT_LINK_TITLE);
const openQuestions = (projectId: number) => db.select().from(questions).where(and(eq(questions.projectId, projectId), isNull(questions.answeredAt)));
const HOUR = 3_600_000;
describe("PEP-145: системная задача при отсутствии ссылки", () => {
test("Принятые задачи без выкладки", async () => {
const p = await proj();
await story(p.id, "Каталог", "done");
await story(p.id, "Корзина", "done");
const waiting = await story(p.id, "Оплата");
await runner.productLinkTick(db);
const backlog = await core.listTasks(db, { projectId: p.id, statuses: ["backlog"] });
assert.equal(backlog[0]!.title, "Продукт должен открываться по ссылке", "first in the backlog");
assert.match(backlog[0]!.description ?? "", /принято задач: 2/);
// PEP-295: a system story waits for «Делать» like any story not from a person.
assert.equal(backlog[0]!.proposed, true);
assert.ok(!(await runner.readyBacklog(db, p.id)).some((t) => t.id === backlog[0]!.id), "the dispatcher does not take it alone");
await core.approveProposal(db, backlog[0]!.id);
assert.equal((await runner.readyBacklog(db, p.id))[0]!.id, backlog[0]!.id, "after «Делать» it goes before the rest");
assert.ok(backlog.some((t) => t.id === waiting.task.id));
});
test("Упавшая выкладка", async () => {
const p = await proj();
await rel(p.id, "staging", "aaa1111", "failed", { reason: "сборка образа не удалась", logTail: "step 3/7: npm ERR! missing script: build" });
await runner.productLinkTick(db);
const [t] = await linkTasks(p.id);
assert.ok(t, "filed without any accepted story: the deploy itself failed");
assert.match(t.description ?? "", /сборка образа не удалась/);
assert.match(t.description ?? "", /missing script: build/, "the log of the failure is in the story");
});
test("Вторая задача не заводится", async () => {
const p = await proj();
await story(p.id, "Каталог", "done");
await runner.productLinkTick(db);
await runner.productLinkTick(db);
await runner.productLinkTick(db, { now: new Date(Date.now() + 30 * HOUR) });
assert.equal((await linkTasks(p.id)).length, 1, "one open story, however much time passes");
});
test("Не чаще раза в сутки", async () => {
const p = await proj();
await story(p.id, "Каталог", "done");
await runner.productLinkTick(db);
const [t] = await linkTasks(p.id);
await core.updateTask(db, await core.resolveTask(db, `${p.key}-${t!.number}`), { status: "done" });
await rel(p.id, "staging", "bbb2222", "rolled_back", { reason: "проверка /healthz не прошла за 120 с" });
await runner.productLinkTick(db, { now: new Date(Date.now() + 2 * HOUR) });
assert.equal((await linkTasks(p.id)).length, 1, "2 hours after the first: nothing new");
await runner.productLinkTick(db, { now: new Date(Date.now() + 25 * HOUR) });
assert.equal((await linkTasks(p.id)).length, 2, "a day later the product still has no healthy update");
});
test("Здоровая версия или идущее обновление: задача не нужна", async () => {
const healthy = await proj();
await story(healthy.id, "Каталог", "done");
await rel(healthy.id, "staging", "ccc3333");
const starting = await proj();
await story(starting.id, "Каталог", "done");
await rel(starting.id, "staging", "ddd4444", "deploying");
const empty = await proj();
await story(empty.id, "Каталог");
await runner.productLinkTick(db);
for (const p of [healthy, starting, empty]) assert.equal((await linkTasks(p.id)).length, 0, p.key);
});
});
/** The commit a version of the project runs: the head of its repository in mock-gitea. */
const head = (p: { giteaOwner: string; giteaRepo: string }) => gitea.sha(p.giteaOwner, p.giteaRepo, "main");
describe("PEP-145: показ всем без нажатий", () => {
const stagingHealthy = (p: Awaited<ReturnType<typeof proj>>, sha: string, commits: string[]) =>
runner.recordRelease(db, p, { env: "staging", sha, status: "healthy", host: "shop-staging.mock.test", commits });
test("Режим «сам»", async () => {
const p = await proj();
await core.setPublishMode(db, p.id, "auto");
const t = await story(p.id, "Каталог", "done");
await stagingHealthy(p, head(p), [`Merge task/${t.key} into main`]);
const [prod] = await db.select().from(releases).where(and(eq(releases.projectId, p.id), eq(releases.env, "prod")));
assert.equal(prod?.status, "deploying");
assert.equal(prod?.sha, head(p), "the same commit goes to everyone");
assert.equal(prod?.deployedBy, "FORGE");
const tag = gitea.repo(p.giteaOwner, p.giteaRepo).tags.at(-1)!;
assert.match(tag.name, /^deploy-prod-/);
assert.ok(!(await openQuestions(p.id)).some((q) => /Показать её всем/.test(q.text)), "no question about it");
});
test("Режим «по кнопке»", async () => {
const p = await proj();
await core.setPublishMode(db, p.id, "button");
const t = await story(p.id, "Каталог", "done");
await stagingHealthy(p, head(p), [`Merge task/${t.key} into main`]);
await runner.productLinkTick(db);
assert.equal((await db.select().from(releases).where(and(eq(releases.projectId, p.id), eq(releases.env, "prod")))).length, 0);
const [q] = await openQuestions(p.id);
assert.deepEqual(q?.options, [runner.PROD_OPTION]);
assert.equal(runner.PROD_OPTION, "🚀 Показать всем");
});
test("Не все задачи приняты", async () => {
const p = await proj();
await core.setPublishMode(db, p.id, "auto");
const t = await story(p.id, "Оплата", "review");
await stagingHealthy(p, head(p), [`Merge task/${t.key} into main`]);
await runner.productLinkTick(db);
const prods = () => db.select().from(releases).where(and(eq(releases.projectId, p.id), eq(releases.env, "prod")));
assert.equal((await prods()).length, 0, "the story is still in review");
await core.updateTask(db, t, { status: "done" });
await runner.productLinkTick(db);
assert.equal((await prods())[0]?.sha, head(p), "accepted later: the watchdog carries it through");
await runner.productLinkTick(db);
assert.equal((await prods()).length, 1, "once per version");
});
test("Существующему проекту — предложение один раз", async () => {
const p = await proj();
await rel(p.id, "staging", head(p));
await runner.productLinkTick(db);
await runner.productLinkTick(db);
const offers = (await openQuestions(p.id)).filter((q) => (q.options ?? []).includes(core.PUBLISH_AUTO_OPTION));
assert.equal(offers.length, 1);
assert.deepEqual(offers[0]!.options, ["Показывать сразу", "Оставить по кнопке"]);
assert.equal(await core.getPublishMode(db, p.id), "button", "nothing changes until the owner chooses");
await runner.answerAndDeliver(db, offers[0]!.id, "Показывать сразу", "web");
assert.equal(await core.getPublishChoice(db, p.id), "auto");
const [prod] = await db.select().from(releases).where(and(eq(releases.projectId, p.id), eq(releases.env, "prod")));
assert.equal(prod?.sha, head(p), "the waiting version goes to everyone right away");
});
test("Проект без версии для проверки предложения не получает", async () => {
const p = await proj();
await runner.productLinkTick(db);
assert.equal((await openQuestions(p.id)).length, 0);
});
});
describe("PEP-145: карточка «Ваш продукт» с честным статусом", () => {
test("Ссылка есть", async () => {
const p = await proj();
await rel(p.id, "staging", "5555555eeee", "healthy", { tasks: [`${p.key}-1`] });
await rel(p.id, "preview", "5555555eeee", "healthy", { prNumber: 1, screenshots: [{ path: "/about", file: "r1-0.png" }, { path: "/", file: "r1-1.png" }] });
const v = await core.projectProduct(db, p.id);
assert.equal((v.live ?? v.check)?.url, "https://shop-staging.mock.test");
assert.equal(v.preparing, false);
assert.equal(v.broken, false);
assert.equal(v.shot?.n, 1, "the screenshot of the first page");
});
test("Ссылки нет", async () => {
const p = await proj();
await story(p.id, "Каталог", "done");
await runner.productLinkTick(db);
const v = await core.projectProduct(db, p.id);
assert.equal(v.live ?? v.check, null);
assert.equal(v.preparing, true);
assert.deepEqual(v.fix, { key: `${p.key}-2`, working: false });
const row = (await core.progressOverview(db, -1)).mine.concat((await core.progressOverview(db, -1)).others).find((r) => r.key === p.key);
assert.ok(!row || row.productFix === `${p.key}-2`);
});
test("Выкладка упала, прошлая версия работает", async () => {
const p = await proj();
await rel(p.id, "staging", "6666666ffff");
await rel(p.id, "staging", "7777777aaaa", "rolled_back", { reason: "проверка /healthz не прошла за 120 с" });
await runner.productLinkTick(db);
const v = await core.projectProduct(db, p.id);
assert.equal(v.check?.url, "https://shop-staging.mock.test", "the earlier version still opens");
assert.equal(v.broken, true);
assert.equal(v.fix?.key, `${p.key}-1`, "and the fix is on its way");
});
test("Новый проект: выкладка заглушки идёт — «Готовим ссылку»", async () => {
const p = await proj();
await rel(p.id, "staging", "8888888bbbb", "deploying");
const v = await core.projectProduct(db, p.id);
assert.equal(v.preparing, true);
assert.equal(v.fix, null);
});
});
describe("PEP-145: ссылка на продукт у принятой задачи", () => {
test("Сообщение о принятой задаче", async () => {
const p = await proj();
await rel(p.id, "prod", "9999999cccc", "healthy", { host: "shop-prod.mock.test" });
assert.match(await core.productLookLine(db, p.id), /https:\/\/shop-prod\.mock\.test/);
});
test("Ссылки нет", async () => {
const p = await proj();
assert.equal(await core.productLookLine(db, p.id), "");
});
});
describe("PEP-145: тексты", () => {
test("описание системной задачи — без слов из «Нельзя» в части для владельца", () => {
const text = core.productLinkDescription({ doneStories: 3 }).split("## Для агента")[0]!;
for (const word of ["деплой", "выкат", "релиз", "staging", "прод ", "репозитор"]) assert.ok(!text.toLowerCase().includes(word), word);
});
});