PEP-282: отчёт проверки называет упавшие тесты; тесты main повторяются один раз

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-26 21:10:38 +00:00
parent a1717939da
commit d2372c631b
4 changed files with 141 additions and 8 deletions

View File

@ -20,7 +20,7 @@ jobs:
# The runner has the host's docker.sock: only branches of this repository, never forks.
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
runs-on: peppa-trusted
timeout-minutes: 30
timeout-minutes: 45
env:
# Peppa's data is SQLite (a temp file per test file). Postgres on the host is only the source
# for the Postgres → SQLite migration test, which makes and drops its own database.

View File

@ -4,9 +4,9 @@
- [x] 1.3 Тесты: пауза процесса не обрывает ответ; зависший сервер обрывается
## 2. Отчёт проверок
- [ ] 2.1 Список упавших тестов в конце хвоста журнала (`peppa-check.sh`)
- [ ] 2.2 Один повтор `test` на основной ветке, пометка в отчёте
- [ ] 2.3 Тест скрипта: список из журнала node:test, повтор на main
- [x] 2.1 Список упавших тестов в конце хвоста журнала (`peppa-check.sh`)
- [x] 2.2 Один повтор `test` на основной ветке, пометка в отчёте
- [x] 2.3 Тест скрипта: список из журнала node:test, повтор на main
## 3. Завершение
- [ ] 3.1 Проверки локально, память, archive, PR

View File

@ -2,6 +2,8 @@
// 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";
@ -102,10 +104,10 @@ describe("CI: connect a project", () => {
describe("CI: check step (.gitea/peppa-check.sh)", () => {
const script = join(ROOT, "template/.gitea/peppa-check.sh");
function workdir(checks: Record<string, string>) {
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 }));
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.
@ -141,4 +143,86 @@ describe("CI: check step (.gitea/peppa-check.sh)", () => {
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");
});
});

View File

@ -12,11 +12,60 @@ if [[ -z "$cmd" ]]; then
echo "peppa: проверка «$check» не настроена — пропуск"
exit 0
fi
# PEP-282: упавшие тесты из журнала — одна строка на тест (имя — файл:строка: ошибка), ≤30.
# node:test (spec: раздел «✖ failing tests:»; TAP: «not ok»), vitest/jest «FAIL», pytest «FAILED», go «--- FAIL:».
failed_tests() {
awk '
function out(s) { if (n < 30 && !(s in seen)) { seen[s] = 1; n++; print "- " substr(s, 1, 200) } }
/^✖ failing tests:/ { spec = 1; next }
spec && /^test at / { loc = substr($0, 9); next }
spec && /^✖ / {
name = $0; sub(/^✖ /, "", name); sub(/ \([0-9.]+m?s\)$/, "", name)
err = ""; if ((getline line) > 0) { err = line; sub(/^[ \t]+/, "", err) }
out(name (loc != "" ? " — " loc : "") (err != "" ? ": " err : "")); loc = ""; next
}
spec { next }
/^[ \t]*not ok [0-9]+ - / { s = $0; sub(/^[ \t]*not ok [0-9]+ - /, "", s); sub(/ # .*$/, "", s); tap[++t] = s; next }
/^[ \t]*(FAIL|FAILED) / { s = $0; sub(/^[ \t]*(FAIL|FAILED) /, "", s); other[++o] = s; next }
/^--- FAIL: / { s = $0; sub(/^--- FAIL: /, "", s); other[++o] = s; next }
END {
if (!spec) { for (i = 1; i <= t; i++) out(tap[i]); for (i = 1; i <= o; i++) out(other[i]) }
}
' "$1"
}
log=$(mktemp)
started=$(date +%s)
bash -o pipefail -c "$cmd" 2>&1 | tee "$log"
code=${PIPESTATUS[0]}
# PEP-282: случайный тест на основной ветке стопорит выкатку до следующего слияния — тесты
# push в main при провале повторяются один раз. Первый провал остаётся в отчёте.
retry_note=""
main_branch="${PEPPA_MAIN_BRANCH:-main}"
if [[ $code -ne 0 && $check == test && -z "${PEPPA_PR:-}" && "${PEPPA_BRANCH:-}" == "$main_branch" ]]; then
first=$(failed_tests "$log")
echo "peppa: тесты основной ветки упали — повторяю один раз"
bash -o pipefail -c "$cmd" 2>&1 | tee "$log"
code=${PIPESTATUS[0]}
if [[ $code -eq 0 ]]; then
retry_note=$'\n'"peppa: первый прогон упал, повтор прошёл. Упавшие в первом прогоне:"$'\n'"${first:-- (не удалось выделить из журнала)}"
else
retry_note=$'\n'"peppa: упали оба прогона. Упавшие в первом прогоне:"$'\n'"${first:-- (не удалось выделить из журнала)}"
fi
echo "$retry_note"
fi
took=$(($(date +%s) - started))
# Хвост журнала обрезан раньше списка упавших — список дописывается в конец отчёта.
failed_block=""
if [[ $code -ne 0 ]]; then
list=$(failed_tests "$log")
if [[ -n "$list" ]]; then
failed_block=$'\n'"Упавшие тесты ($(printf '%s\n' "$list" | wc -l | tr -d ' ')):"$'\n'"$list"
echo "$failed_block"
fi
fi
[[ -n "${GITHUB_ACTIONS:-}" ]] || exit "$code"
state=success
@ -27,7 +76,7 @@ sha="${PEPPA_SHA:-$GITHUB_SHA}"
run_url="/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_NUMBER"
if [[ -n "${GITEA_TOKEN:-}" ]]; then
jq -n --arg s "$state" --arg c "peppa/$check" --arg u "$run_url" --arg d "$check: $state за ${took}с" \
jq -n --arg s "$state" --arg c "peppa/$check" --arg u "$run_url" --arg d "$check: $state за ${took}с${retry_note:+ (с повтором)}" \
'{state:$s, context:$c, target_url:$u, description:$d}' |
curl -fsS -o /dev/null -X POST -H "Authorization: token $GITEA_TOKEN" -H "Content-Type: application/json" \
--data-binary @- "$GITHUB_SERVER_URL/api/v1/repos/$GITHUB_REPOSITORY/statuses/$sha" ||
@ -36,7 +85,7 @@ fi
peppa_url=$(jq -r '.peppaUrl // empty' "$cfg")
if [[ -n "$peppa_url" && -n "${PEPPA_CI_SECRET:-}" ]]; then
body=$(tail -n 200 "$log" | jq -Rs --arg repo "$GITHUB_REPOSITORY" --arg sha "$sha" --arg branch "${PEPPA_BRANCH:-}" \
body=$({ tail -n 200 "$log"; [[ -n "$retry_note" ]] && printf '%s\n' "$retry_note"; [[ -n "$failed_block" ]] && printf '%s\n' "$failed_block"; } | jq -Rs --arg repo "$GITHUB_REPOSITORY" --arg sha "$sha" --arg branch "${PEPPA_BRANCH:-}" \
--arg pr "${PEPPA_PR:-}" --arg check "$check" --arg state "$state" --arg url "$run_url" --argjson took "$took" \
'{repository:$repo, sha:$sha, branch:$branch, pr:($pr|tonumber? // null), check:$check, state:$state, run_url:$url, duration_sec:$took, log_tail:.}')
sig=$(printf '%s' "$body" | openssl dgst -sha256 -hmac "$PEPPA_CI_SECRET" | awk '{print $NF}')