peppa/packages/testkit/test/stack-tools.test.ts

154 lines
7.9 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-314, spec peppa-ci «Go и временная база для проверок без нового образа»: the template's
// .gitea/peppa-tools.sh runs for real — Go comes from a file:// "go.dev/dl" with a mock archive,
// PostgreSQL from mock initdb/pg_ctl/createdb (mock-pg-*), no docker anywhere.
import assert from "node:assert/strict";
import { execFileSync, spawnSync } from "node:child_process";
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { createServer } from "node:net";
import type { AddressInfo } from "node:net";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { describe, test } from "node:test";
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
const TOOLS = join(ROOT, "template/.gitea/peppa-tools.sh");
const TMP = mkdtempSync(join(tmpdir(), "peppa-stack-tools-"));
const ARCH = ({ x64: "amd64", arm64: "arm64" } as Record<string, string>)[process.arch] ?? process.arch;
const SYS_PATH = "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin";
function exe(path: string, body: string) {
writeFileSync(path, `#!/usr/bin/env bash\n${body}\n`);
chmodSync(path, 0o755);
}
/** A mock go.dev/dl: go<ver>.linux-<arch>.tar.gz with go/bin/go answering `go version`. */
function mockGoDl(version: string): string {
const dl = mkdtempSync(join(TMP, "mock-go-dl-"));
const src = join(dl, "src");
mkdirSync(join(src, "go/bin"), { recursive: true });
exe(join(src, "go/bin/go"), `echo "go version go${version} linux/${ARCH}"`);
execFileSync("tar", ["-czf", join(dl, `go${version}.linux-${ARCH}.tar.gz`), "-C", src, "go"]);
return dl;
}
/** Mock PostgreSQL binaries: initdb makes data/, pg_ctl start/status/stop, createdb; all log to calls.log. */
function mockPgBin(): string {
const bin = mkdtempSync(join(TMP, "mock-pg-"));
exe(join(bin, "initdb"), `echo "initdb $*" >> "${bin}/calls.log"; while [ $# -gt 0 ]; do [ "$1" = -D ] && mkdir -p "$2" && echo 18 > "$2/PG_VERSION"; shift; done`);
exe(
join(bin, "pg_ctl"),
`echo "pg_ctl $*" >> "${bin}/calls.log"; d=""; cmd=""; for a in "$@"; do [ "$prev" = -D ] && d="$a"; prev="$a"; cmd="$a"; done
case "$cmd" in
start) touch "$d/running" ;;
status) [ -f "$d/running" ] ;;
stop) rm -f "$d/running" ;;
esac`,
);
exe(join(bin, "createdb"), `echo "createdb $*" >> "${bin}/calls.log"`);
return bin;
}
/** `source peppa-tools.sh <args>` in a fresh bash; prints PATH, DATABASE_URL and `command -v go`. */
function source(args: string[], env: Record<string, string>, cwd = TMP) {
const script = `source "${TOOLS}" ${args.join(" ")}; code=$?; echo "CODE=$code"; echo "URL=\${DATABASE_URL:-}"; echo "GO=$(command -v go)"; exit 0`;
const r = spawnSync("bash", ["-c", script], { cwd, encoding: "utf8", env: { HOME: TMP, TMPDIR: TMP, PATH: SYS_PATH, ...env } });
const line = (k: string) => (r.stdout.match(new RegExp(`^${k}=(.*)$`, "m")) ?? [])[1] ?? "";
return { code: Number(line("CODE")), url: line("URL"), go: line("GO"), err: r.stderr };
}
describe("Go для проверок", () => {
test("Scenario: Задание проверок без Go", () => {
const dl = mockGoDl("1.27.0");
const work = mkdtempSync(join(TMP, "work-"));
writeFileSync(join(work, "go.mod"), "module example.com/shop\n\ngo 1.27\n");
const ghPath = join(work, "github_path");
const cache = join(work, "cache");
const r = source(["go"], { PEPPA_GO_DL_BASE: `file://${dl}`, PEPPA_TOOLS_CACHE: cache, GITHUB_PATH: ghPath }, work);
assert.equal(r.code, 0, r.err);
assert.match(r.err, new RegExp(`скачиваю go1\\.27\\.0\\.linux-${ARCH}\\.tar\\.gz`));
assert.equal(r.go, join(cache, "go/1.27.0/go/bin/go"));
assert.equal(readFileSync(ghPath, "utf8").trim(), join(cache, "go/1.27.0/go/bin"));
// the second call takes the cache, nothing is downloaded
const again = source(["go"], { PEPPA_GO_DL_BASE: "file:///nonexistent", PEPPA_TOOLS_CACHE: cache }, work);
assert.equal(again.code, 0, again.err);
assert.doesNotMatch(again.err, /скачиваю/);
});
test("Scenario: Go уже есть (песочница агента)", () => {
const bin = mkdtempSync(join(TMP, "image-bin-"));
exe(join(bin, "go"), 'echo "go version go1.27.3 linux/amd64"');
const r = source(["go"], { PATH: `${bin}:${SYS_PATH}`, PEPPA_GO_DL_BASE: "file:///nonexistent" });
assert.equal(r.code, 0, r.err);
assert.equal(r.go, join(bin, "go"));
assert.doesNotMatch(r.err, /скачиваю/);
});
test("go.mod с полной версией и строкой toolchain — качается версия строки go", () => {
const dl = mockGoDl("1.27.2");
const work = mkdtempSync(join(TMP, "work-"));
writeFileSync(join(work, "go.mod"), "module m\n\ngo 1.27.2\n\ntoolchain go1.27.4\n");
const r = source(["go"], { PEPPA_GO_DL_BASE: `file://${dl}`, PEPPA_TOOLS_CACHE: join(work, "c") }, work);
assert.equal(r.code, 0, r.err);
assert.match(r.go, /go\/1\.27\.2\/go\/bin\/go$/);
});
test("Go не скачался — ошибка, а не тишина", () => {
const r = source(["go"], { PEPPA_GO_DL_BASE: `file://${TMP}/no-such-dl`, PEPPA_TOOLS_CACHE: join(TMP, "c-fail") });
assert.equal(r.code, 1);
assert.match(r.err, /не удалось скачать Go 1\.27\.0/);
assert.equal(r.go, "");
});
});
describe("Временная база для тестов", () => {
test("Scenario: Временная база для тестов", () => {
const bin = mockPgBin();
const dir = join(TMP, "pg-1");
const ghEnv = join(TMP, "github_env-1");
const env = { PEPPA_PG_BINDIR: bin, PEPPA_PG_DIR: dir, GITHUB_ENV: ghEnv };
const first = source(["postgres"], env);
assert.equal(first.code, 0, first.err);
const m = first.url.match(/^postgres:\/\/app@127\.0\.0\.1:(\d+)\/app\?sslmode=disable$/);
assert.ok(m, first.url);
assert.ok(Number(m[1]) >= 18432);
assert.equal(readFileSync(ghEnv, "utf8").trim(), `DATABASE_URL=${first.url}`);
const calls = readFileSync(join(bin, "calls.log"), "utf8");
assert.match(calls, /initdb -D .* -U app --auth=trust/);
assert.match(calls, new RegExp(`listen_addresses=127\\.0\\.0\\.1 -p ${m[1]}`));
assert.match(calls, new RegExp(`createdb -h 127\\.0\\.0\\.1 -p ${m[1]} -U app app`));
const second = source(["postgres"], env);
assert.equal(second.url, first.url);
assert.equal(readFileSync(join(bin, "calls.log"), "utf8").match(/^initdb /gm)?.length, 1, "no second cluster");
// stop removes the cluster; the next call makes a new one
spawnSync("bash", [TOOLS, "stop"], { env: { PATH: SYS_PATH, TMPDIR: TMP, ...env } });
assert.ok(!existsSync(dir));
});
test("занятый порт пропускается", async () => {
const busy = createServer();
await new Promise<void>((r) => busy.listen(0, "127.0.0.1", r));
const port = (busy.address() as AddressInfo).port;
try {
const r = source(["postgres"], { PEPPA_PG_BINDIR: mockPgBin(), PEPPA_PG_DIR: join(TMP, "pg-2"), PEPPA_PG_PORT_FROM: String(port) });
assert.equal(r.code, 0, r.err);
assert.notEqual(r.url, `postgres://app@127.0.0.1:${port}/app?sslmode=disable`);
} finally {
busy.close();
}
});
test("Scenario: Нет PostgreSQL и нельзя поставить", { skip: process.getuid?.() === 0 }, () => {
const r = source(["postgres"], { PEPPA_PG_DIR: join(TMP, "pg-3") });
assert.notEqual(r.code, 0);
assert.match(r.err, /PostgreSQL не найден/);
assert.equal(r.url, "");
});
test("запуск без source печатает export для eval", () => {
const env = { PEPPA_PG_BINDIR: mockPgBin(), PEPPA_PG_DIR: join(TMP, "pg-4") };
const out = execFileSync("bash", [TOOLS, "postgres"], { encoding: "utf8", env: { PATH: SYS_PATH, TMPDIR: TMP, ...env } });
assert.match(out, /^export DATABASE_URL=postgres:\/\/app@127\.0\.0\.1:\d+\/app\\\?sslmode=disable$/m);
});
});