chore(test): добавить test:changed для регресса только затронутых тестов

Скрипт берёт изменённые файлы из Git и запускает только тесты, которые на них ссылаются. Тесты на PostgreSQL он не запускает, а выводит нужный npm-профиль.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
DenozordecandClaude Sonnet 5.5 committed 2026-11-15 21:59:48 +07:00
1 parent d3a347a8ca
commit 64cfb07c22
2 files changed
+64

No files matched your search

+63
View File
@@ -0,0 +1,63 @@
// Runs only the backend tests that import a changed file (regression of what was touched).
// npm --prefix backend run test:changed -- [--since=<git-ref>] [--list]
// Default scope: uncommitted and untracked files. --since=<ref> uses `git diff <ref>` instead.
// shortcut: one-level import match by file basename, not a real module graph; upgrade if basenames collide.
// PostgreSQL-backed tests are listed with their npm profile, never run here.
import { execFileSync, spawnSync } from "node:child_process"
import { readdirSync, readFileSync } from "node:fs"
import { basename, extname, join, relative, sep } from "node:path"
const flag = name => process.argv.find(arg => arg.startsWith(`--${name}=`))?.slice(name.length + 3)
const listOnly = process.argv.includes("--list")
const since = flag("since")
const backend = new URL("../", import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, "$1").replace(/\/$/, "")
const git = (...args) => execFileSync("git", args, { encoding: "utf8", maxBuffer: 1 << 28 }).split("\n").filter(Boolean)
const top = git("-C", backend, "rev-parse", "--show-toplevel")[0]
const changed = [...new Set(since ? git("-C", top, "diff", "--name-only", since)
: [...git("-C", top, "diff", "--name-only", "HEAD"), ...git("-C", top, "ls-files", "--others", "--exclude-standard")])]
.filter(file => file.startsWith("backend/") && /\.(ts|mts|mjs|js)$/.test(file))
const isTest = file => /\.test\.(ts|mts|mjs)$/.test(file)
const tests = []
const walk = dir => {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
if (entry.name === "node_modules" || entry.name.startsWith("dist")) continue
const path = join(dir, entry.name)
if (entry.isDirectory()) walk(path)
else if (isTest(entry.name)) tests.push({ path, rel: relative(top, path).split(sep).join("/"), text: readFileSync(path, "utf8") })
}
}
walk(join(backend, "src")); walk(join(backend, "scripts"))
const escape = text => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
const selected = new Map()
for (const file of changed) {
const base = basename(file, extname(file))
const importer = new RegExp(`[/"'\`]${escape(base)}(\\.(js|ts|mjs))?["'\`]`)
for (const test of tests) if (test.rel === file || basename(test.rel).startsWith(base + ".") || importer.test(test.text)) selected.set(test.rel, test)
}
const scripts = JSON.parse(readFileSync(join(backend, "package.json"), "utf8")).scripts
const needsPostgres = test => /\.(sql|owned|pg)\.test\./.test(test.rel) || /embedded-postgres|EmbeddedPostgres/.test(test.text) || test.rel.endsWith("modules/mcp/integration.test.ts")
const profileFor = test => Object.entries(scripts).find(([, command]) => command.includes(basename(test.rel)))?.[0]
const runnable = [], database = []
for (const test of selected.values()) (needsPostgres(test) ? database : runnable).push(test)
console.log(`changed backend files: ${changed.length}; matching tests: ${selected.size} (run here: ${runnable.length}, PostgreSQL: ${database.length})`)
const profiles = new Set()
for (const test of database) {
const profile = test.rel.endsWith("modules/mcp/integration.test.ts") ? "test:mcp:pg" : profileFor(test)
profiles.add(profile ?? "test:mcp:pg:all")
console.log(` PostgreSQL: ${test.rel} -> ${profile ? `npm --prefix backend run ${profile}` : "no profile found, see test:mcp:pg:all"}`)
}
if (profiles.size) console.log(`PostgreSQL profiles to run separately: ${[...profiles].join(", ")}`)
if (listOnly || !runnable.length) { for (const test of runnable) console.log(` run: ${test.rel}`); process.exit(0) }
let failed = 0
for (const [runner, group] of [["tsx", runnable.filter(test => !test.rel.endsWith(".mjs"))], ["node", runnable.filter(test => test.rel.endsWith(".mjs"))]]) {
if (!group.length) continue
const args = runner === "tsx" ? ["tsx", "--test", ...group.map(test => test.path)] : ["--test", ...group.map(test => test.path)]
const result = spawnSync(runner === "tsx" ? "npx" : process.execPath, args, { cwd: backend, stdio: "inherit", shell: runner === "tsx", env: { ...process.env, NODE_ENV: "test" } })
if (result.status !== 0) failed = 1
}
process.exit(failed)