229 lines
12 KiB
TypeScript
229 lines
12 KiB
TypeScript
// PEP-57: CI for factory projects — runner registration, Actions secret, "connect CI" PR,
|
||
// and the template's check step (.gitea/peppa-check.sh) against mock Gitea.
|
||
import assert from "node:assert/strict";
|
||
import { execFile, execFileSync } from "node:child_process";
|
||
import { createServer } from "node:http";
|
||
import type { AddressInfo } from "node:net";
|
||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
|
||
import { tmpdir } from "node:os";
|
||
import { join, resolve } from "node:path";
|
||
import { fileURLToPath } from "node:url";
|
||
import { after, before, describe, test } from "node:test";
|
||
import { core, db, runner, teardown } from "./helpers.ts";
|
||
import { CHECK_NAMES } from "@peppa/shared";
|
||
import { MockGitea } from "../src/mock-gitea.ts";
|
||
|
||
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
|
||
const TMP = mkdtempSync(join(tmpdir(), "peppa-ci-"));
|
||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||
|
||
const gitea = new MockGitea(join(TMP, "gitea"));
|
||
const BOT = { id: 61, login: "peppa-bot", token: "mock-token-bot" };
|
||
const OWNER = { id: 62, login: "mock-dana", token: "mock-token-dana" };
|
||
let templateUrl = "";
|
||
let owner: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
let seq = 0;
|
||
|
||
before(async () => {
|
||
await gitea.start();
|
||
process.env.GITEA_URL = gitea.url;
|
||
process.env.GITEA_TOKEN = BOT.token;
|
||
gitea.addUser(BOT);
|
||
gitea.addUser(OWNER);
|
||
const tpl = gitea.addRepo("peppa-bot", "template");
|
||
execFileSync("bash", ["-c", `cd ${JSON.stringify(join(ROOT, "template"))} && T=$(mktemp -d) && cp -R . "$T" && cd "$T" && git init -q -b main && git add -A && git -c user.name=t -c user.email=t@t commit -qm tpl && git push -q ${JSON.stringify(tpl.path)} main`]);
|
||
templateUrl = tpl.path;
|
||
owner = await core.upsertUserFromGitea(db, OWNER, { access_token: OWNER.token });
|
||
});
|
||
after(async () => {
|
||
await gitea.stop();
|
||
await teardown();
|
||
});
|
||
|
||
const registrations = () => {
|
||
const f = join(process.env.PEPPA_HOME!, "mock-ci-register.jsonl");
|
||
return existsSync(f) ? readFileSync(f, "utf8").trim().split("\n").map((l) => JSON.parse(l) as { name: string; token: string }) : [];
|
||
};
|
||
|
||
/** A project whose repo (with an initial commit) lives in mock Gitea under `ns`. */
|
||
async function ciProject(ns: string, files: Record<string, string> = {}) {
|
||
const key = `CI${String.fromCharCode(65 + seq++)}`;
|
||
const slug = key.toLowerCase();
|
||
gitea.addRepo(ns, slug, {
|
||
admins: [ns],
|
||
files: { "README.md": "# x\n", ".peppa/project.json": JSON.stringify({ slug, key, name: key, peppaUrl: "http://peppa.test" }), ...files },
|
||
});
|
||
if (ns !== BOT.login) gitea.repo(ns, slug).collaborators[BOT.login] = "write";
|
||
const p = await core.createProject(db, { slug, key, name: key, giteaOwner: ns, workspacePath: join(TMP, "ws", slug), ownerId: ns === BOT.login ? null : owner.id });
|
||
return p;
|
||
}
|
||
|
||
describe("CI: connect a project", () => {
|
||
test("peppa-bot's repo: covered by the bot runner, secret set, PR with the workflow and empty checks", async () => {
|
||
const p = await ciProject(BOT.login);
|
||
const before = registrations().length;
|
||
const r = await runner.connectCi(db, p, { templateUrl });
|
||
assert.equal(r.runner, "bot");
|
||
assert.equal(registrations().length, before, "no per-repo runner for peppa-bot's repos");
|
||
const repo = gitea.repo(BOT.login, p.giteaRepo);
|
||
assert.equal(repo.secrets.PEPPA_CI_SECRET, core.projectHookSecret(p.id));
|
||
assert.deepEqual(repo.hooks.map((h) => [h.url, h.secret, h.events]), [[runner.giteaHookUrl(), core.projectHookSecret(p.id), runner.GITEA_HOOK_EVENTS]]);
|
||
assert.match(runner.giteaHookUrl(), /\/api\/hooks\/gitea$/);
|
||
assert.ok(r.prUrl?.endsWith("/pulls/1"));
|
||
const pr = repo.pulls[0]!;
|
||
assert.equal(pr.head, runner.CI_BRANCH);
|
||
const files = gitea.filesAt(BOT.login, p.giteaRepo, pr.head);
|
||
for (const f of runner.CI_FILES) assert.ok(files.includes(f), f);
|
||
const pj = JSON.parse(execFileSync("git", ["--git-dir", repo.path, "show", `${pr.head}:.peppa/project.json`], { encoding: "utf8" }));
|
||
assert.deepEqual(pj.checks, {});
|
||
assert.equal(pj.key, p.key, "the project's own fields are kept");
|
||
|
||
// Running again re-uses the open PR; after the merge there is nothing to connect.
|
||
assert.equal((await runner.connectCi(db, p, { templateUrl })).prUrl, r.prUrl);
|
||
await core.giteaForBot().mergePullRequest(BOT.login, p.giteaRepo, 1);
|
||
assert.equal((await runner.connectCi(db, p, { templateUrl })).prUrl, null);
|
||
});
|
||
|
||
test("repo in the owner's namespace: per-repo runner registered with the owner's token", async () => {
|
||
const p = await ciProject(OWNER.login);
|
||
const r = await runner.connectCi(db, p, { templateUrl });
|
||
assert.equal(r.runner, "repo");
|
||
const reg = registrations().at(-1)!;
|
||
assert.equal(reg.name, `repo-${OWNER.login}--${p.giteaRepo}`);
|
||
assert.ok(gitea.runnerTokens.some((t) => t.token === reg.token && t.scope === `repo:${OWNER.login}/${p.giteaRepo}`));
|
||
assert.equal(gitea.repo(OWNER.login, p.giteaRepo).secrets.PEPPA_CI_SECRET, core.projectHookSecret(p.id));
|
||
});
|
||
|
||
test("template workflow: trusted runner, no fork PRs, every check as its own step", () => {
|
||
const wf = readFileSync(join(ROOT, "template/.gitea/workflows/ci.yml"), "utf8");
|
||
assert.match(wf, /runs-on: peppa-trusted/);
|
||
assert.match(wf, /head\.repo\.full_name == github\.repository/);
|
||
for (const c of ["install", ...CHECK_NAMES]) assert.match(wf, new RegExp(`peppa-check\\.sh ${c}\\b`));
|
||
});
|
||
});
|
||
|
||
describe("CI: check step (.gitea/peppa-check.sh)", () => {
|
||
const script = join(ROOT, "template/.gitea/peppa-check.sh");
|
||
function workdir(checks: Record<string, string>, peppaUrl = "") {
|
||
const d = mkdtempSync(join(TMP, "job-"));
|
||
mkdirSync(join(d, ".peppa"));
|
||
writeFileSync(join(d, ".peppa/project.json"), JSON.stringify({ slug: "x", key: "X", name: "x", peppaUrl, checks }));
|
||
return d;
|
||
}
|
||
// Async: the script talks to mock Gitea, which runs in this process.
|
||
const step = (cwd: string, check: string, env: Record<string, string> = {}) =>
|
||
new Promise<{ status: number; stdout: string }>((done) => {
|
||
execFile("bash", [script, check], { cwd, encoding: "utf8", env: { ...process.env, GITHUB_ACTIONS: "", ...env } }, (err, stdout) =>
|
||
done({ status: err ? Number((err as { code?: number }).code ?? 1) : 0, stdout }),
|
||
);
|
||
});
|
||
|
||
test("locally: runs the command, keeps its exit code; a missing command is skipped", async () => {
|
||
const d = workdir({ test: "echo testing; exit 3", lint: "echo fine" });
|
||
const t = await step(d, "test");
|
||
assert.equal(t.status, 3);
|
||
assert.match(t.stdout, /testing/);
|
||
assert.equal((await step(d, "lint")).status, 0);
|
||
const b = await step(d, "build");
|
||
assert.equal(b.status, 0);
|
||
assert.match(b.stdout, /не настроена/);
|
||
});
|
||
|
||
test("in CI: writes the commit status peppa/<check> to Gitea", async () => {
|
||
const p = await ciProject(BOT.login);
|
||
const sha = gitea.sha(BOT.login, p.giteaRepo, "main");
|
||
const d = workdir({ test: "exit 1", build: "true" });
|
||
const env = { GITHUB_ACTIONS: "true", GITHUB_SERVER_URL: gitea.url, GITHUB_REPOSITORY: `${BOT.login}/${p.giteaRepo}`, GITHUB_RUN_NUMBER: "7", PEPPA_SHA: sha, GITEA_TOKEN: BOT.token };
|
||
assert.equal((await step(d, "test", env)).status, 1);
|
||
assert.equal((await step(d, "build", env)).status, 0);
|
||
const st = await core.giteaForBot().combinedStatus(BOT.login, p.giteaRepo, sha);
|
||
assert.equal(st.state, "failure");
|
||
const byCtx = Object.fromEntries(st.statuses!.map((s) => [s.context, s]));
|
||
assert.equal(byCtx["peppa/test"]?.status, "failure");
|
||
assert.equal(byCtx["peppa/build"]?.status, "success");
|
||
assert.equal(byCtx["peppa/test"]?.target_url, `/${BOT.login}/${p.giteaRepo}/actions/runs/7`);
|
||
});
|
||
|
||
// PEP-282: what FORGE receives — the check report (X-Peppa-Event: check).
|
||
async function reportSink() {
|
||
const bodies: Array<Record<string, unknown>> = [];
|
||
const srv = createServer((req, res) => {
|
||
let b = "";
|
||
req.on("data", (c) => (b += c));
|
||
req.on("end", () => {
|
||
if (req.headers["x-peppa-event"] === "check") bodies.push(JSON.parse(b));
|
||
res.end("{}");
|
||
});
|
||
});
|
||
await new Promise<void>((r) => srv.listen(0, "127.0.0.1", r));
|
||
return { url: `http://127.0.0.1:${(srv.address() as AddressInfo).port}`, bodies, close: () => new Promise<void>((r) => srv.close(() => r())) };
|
||
}
|
||
// A node:test spec failure, as the test step prints it: the list sits after hundreds of log lines.
|
||
const NODE_FAIL = [
|
||
"for i in $(seq 1 300); do echo \"log line $i\"; done",
|
||
"echo '✖ failing tests:'", "echo", "echo 'test at test/a.test.mjs:2:28'", "echo '✖ Scenario: падает (1.4ms)'", "echo ' AssertionError [ERR_ASSERTION]: 4 == 5'",
|
||
"echo", "echo 'test at test/a.test.mjs:3:1'", "echo '✖ второй падает (1.2ms)'", "echo ' Error: boom'",
|
||
].join("; ");
|
||
const ciEnv = (extra: Record<string, string> = {}) => ({ GITHUB_ACTIONS: "true", GITHUB_REPOSITORY: "x/x", GITHUB_RUN_NUMBER: "9", PEPPA_SHA: "abc1234", PEPPA_CI_SECRET: "s", GITEA_TOKEN: "", PEPPA_PR: "", PEPPA_BRANCH: "task/x-1", ...extra });
|
||
|
||
test("Scenario: Упали два теста node:test — список в конце отчёта", async () => {
|
||
const sink = await reportSink();
|
||
const d = workdir({ test: `${NODE_FAIL}; exit 1` }, sink.url);
|
||
assert.equal((await step(d, "test", ciEnv({ PEPPA_PR: "12" }))).status, 1);
|
||
await sink.close();
|
||
const tail = String(sink.bodies[0]!.log_tail).trimEnd().split("\n");
|
||
assert.deepEqual(tail.slice(-3), [
|
||
"Упавшие тесты (2):",
|
||
"- Scenario: падает — test/a.test.mjs:2:28: AssertionError [ERR_ASSERTION]: 4 == 5",
|
||
"- второй падает — test/a.test.mjs:3:1: Error: boom",
|
||
]);
|
||
});
|
||
|
||
test("Scenario: Проверка прошла — блока «Упавшие тесты» нет", async () => {
|
||
const sink = await reportSink();
|
||
const d = workdir({ test: "echo all good" }, sink.url);
|
||
assert.equal((await step(d, "test", ciEnv())).status, 0);
|
||
await sink.close();
|
||
assert.doesNotMatch(String(sink.bodies[0]!.log_tail), /Упавшие тесты|повтор/);
|
||
});
|
||
|
||
// The command fails on the first run and passes on the second (a flaky test).
|
||
const flaky = `n=$(cat runs 2>/dev/null || echo 0); echo $((n + 1)) > runs; if [ "$n" = 0 ]; then ${NODE_FAIL}; exit 1; fi; echo passed`;
|
||
|
||
test("Scenario: Случайный тест на main — один повтор, статус зелёный, первый провал в отчёте", async () => {
|
||
const p = await ciProject(BOT.login);
|
||
const sha = gitea.sha(BOT.login, p.giteaRepo, "main");
|
||
const sink = await reportSink();
|
||
const d = workdir({ test: flaky }, sink.url);
|
||
const env = ciEnv({ PEPPA_BRANCH: "main", GITHUB_SERVER_URL: gitea.url, GITHUB_REPOSITORY: `${BOT.login}/${p.giteaRepo}`, PEPPA_SHA: sha, GITEA_TOKEN: BOT.token });
|
||
assert.equal((await step(d, "test", env)).status, 0);
|
||
await sink.close();
|
||
assert.equal(readFileSync(join(d, "runs"), "utf8").trim(), "2", "the command ran twice");
|
||
assert.equal(sink.bodies[0]!.state, "success");
|
||
const log = String(sink.bodies[0]!.log_tail);
|
||
assert.match(log, /первый прогон упал, повтор прошёл/);
|
||
assert.match(log, /- Scenario: падает — test\/a.test.mjs:2:28/);
|
||
const st = (await core.giteaForBot().combinedStatus(BOT.login, p.giteaRepo, sha)).statuses!.find((x) => x.context === "peppa/test");
|
||
assert.equal(st?.status, "success");
|
||
assert.match(String(st?.description), /с повтором/);
|
||
});
|
||
|
||
test("Scenario: Провал в PR не повторяется", async () => {
|
||
const sink = await reportSink();
|
||
const d = workdir({ test: flaky }, sink.url);
|
||
assert.equal((await step(d, "test", ciEnv({ PEPPA_PR: "12", PEPPA_BRANCH: "main" }))).status, 1);
|
||
await sink.close();
|
||
assert.equal(readFileSync(join(d, "runs"), "utf8").trim(), "1");
|
||
assert.equal(sink.bodies[0]!.state, "failure");
|
||
assert.doesNotMatch(String(sink.bodies[0]!.log_tail), /повтор/);
|
||
});
|
||
|
||
test("lint on main is not retried", async () => {
|
||
const sink = await reportSink();
|
||
const d = workdir({ lint: flaky }, sink.url);
|
||
assert.equal((await step(d, "lint", ciEnv({ PEPPA_BRANCH: "main" }))).status, 1);
|
||
await sink.close();
|
||
assert.equal(readFileSync(join(d, "runs"), "utf8").trim(), "1");
|
||
});
|
||
});
|