test(test-db): template database + schema-hash cache + clone primitives
Reworks the test-db module into explicit primitives: ensureTemplateDatabase (dropped/recreated + built once per schema hash change, cached in .cache/testdb-template.json), cloneTemplateInto, dropDatabaseIfPresent and dropStaleWorkerDatabases. bootstrapTestDatabase() keeps its export but is re-expressed as guarantee-template + fresh clone for the serial databases (vitest pre-stage-2, Playwright), so repeated runs skip drizzle push entirely. The legacy truncate+push flow survives verbatim as bootstrapSerialDatabase for the TEST_DATABASE_URI bisect mode. Nothing may connect to the template while clones run (loud invariant comment).
This commit is contained in:
parent
859f6d4310
commit
6be14c9815
3 changed files with 299 additions and 26 deletions
|
|
@ -2,10 +2,11 @@ import { bootstrapTestDatabase } from "../test-db";
|
||||||
import { resolveTestDatabaseUri } from "../test-db";
|
import { resolveTestDatabaseUri } from "../test-db";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Playwright global setup: ensure the dedicated test database exists, is
|
* Playwright global setup: ensure the dedicated test database exists and is
|
||||||
* migrated, seeded and emptied before the dev server (started by webServer
|
* freshly built from the cached schema template (push runs only when the
|
||||||
* with DATABASE_URI pointed at it) serves the e2e suite. Then seed the shared
|
* schema hash changed) before the dev server (started by webServer with
|
||||||
* e2e login ("dev" / "Test123"): every authed spec logs in with it, and the
|
* DATABASE_URI pointed at it) serves the e2e suite. Then seed the shared e2e
|
||||||
|
* login ("dev" / "Test123"): every authed spec logs in with it, and the
|
||||||
* dashboard smoke expects the "Welcome back, J. Fraley." heading.
|
* dashboard smoke expects the "Welcome back, J. Fraley." heading.
|
||||||
*/
|
*/
|
||||||
export default async function globalSetup(): Promise<void> {
|
export default async function globalSetup(): Promise<void> {
|
||||||
|
|
|
||||||
312
tests/test-db.ts
312
tests/test-db.ts
|
|
@ -1,4 +1,7 @@
|
||||||
import { execSync } from "node:child_process";
|
import { execSync } from "node:child_process";
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
||||||
|
import path from "node:path";
|
||||||
import { Client } from "pg";
|
import { Client } from "pg";
|
||||||
import { applyAnalyticsDdl, ANALYTICS_TABLE_NAMES } from "../src/lib/analytics/schema";
|
import { applyAnalyticsDdl, ANALYTICS_TABLE_NAMES } from "../src/lib/analytics/schema";
|
||||||
|
|
||||||
|
|
@ -10,21 +13,52 @@ import "dotenv/config";
|
||||||
/**
|
/**
|
||||||
* Dedicated test database machinery for the vitest and Playwright suites.
|
* Dedicated test database machinery for the vitest and Playwright suites.
|
||||||
*
|
*
|
||||||
* Tests never touch the development database: they run against a sibling
|
* Tests never touch the development database. The topology:
|
||||||
* `<name>_test` database that is ensured, migrated, seeded and truncated per
|
*
|
||||||
* run. All operations are idempotent, so a crashed run's leftovers are wiped
|
* - `ptf_app_test_template` is built once per schema change by globalSetup:
|
||||||
* by the next run no matter what leaked.
|
* ensure db, drop analytics tables, drizzle push (auto-accepting warnings),
|
||||||
|
* analytics DDL, seedRoles + baseline seed, sequence repair. A hash of all
|
||||||
|
* schema-relevant inputs is cached in `.cache/testdb-template.json`; warm
|
||||||
|
* runs skip the push entirely.
|
||||||
|
* - Vitest workers each clone it into `ptf_app_test_w<ID>` at startup
|
||||||
|
* (`CREATE DATABASE ... TEMPLATE`, milliseconds because it holds only the
|
||||||
|
* empty baseline schema) and drop the clones at teardown unless the run
|
||||||
|
* failed. Two workers therefore never share tables.
|
||||||
|
* - `ptf_app_test` (the serial database, used by Playwright and by legacy
|
||||||
|
* serial vitest when no override is set) is recreated fresh from the
|
||||||
|
* template on every bootstrap instead of being truncated in place.
|
||||||
|
*
|
||||||
|
* >>> CLONING INVARIANT - DO NOT BREAK <<<
|
||||||
|
* `CREATE DATABASE ... TEMPLATE` fails while anything is connected to the
|
||||||
|
* template. Every clone happens after globalSetup finished building it and
|
||||||
|
* before any worker's tests import the Payload config, and no test code ever
|
||||||
|
* connects to the template database. If future tooling wants to "just peek"
|
||||||
|
* at `ptf_app_test_template` during a run, it must go through a snapshot
|
||||||
|
* clone instead - peeks re-break parallel worker startup.
|
||||||
*
|
*
|
||||||
* Override points:
|
* Override points:
|
||||||
* - `TEST_DATABASE_URI` — use this exact connection string instead of the
|
* - `TEST_DATABASE_URI`: use this exact connection string instead of the
|
||||||
* derived one.
|
* derived one. This also forces LEGACY SERIAL behavior (single shared db,
|
||||||
* - `TEST_DB_HARD_RESET=1` — drop and recreate the test database (fresh
|
* truncate per run, no templates or clones) for bisecting flakes.
|
||||||
* schema from migrations) instead of the default truncate flow.
|
* - `TEST_DB_HARD_RESET=1`: ignore the template cache and rebuild the
|
||||||
|
* template from scratch.
|
||||||
|
* - `KEEP_TEST_DBS=1`: teardown keeps worker clones even after green runs
|
||||||
|
* (postmortem hatch).
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/** Tables that must survive truncation: PostGIS internals and migration journals. */
|
/** Tables that must survive truncation: PostGIS internals and migration journals. */
|
||||||
const SKIP_TRUNCATE = new Set(["spatial_ref_sys", "__drizzle_migrations", "payload_migrations"]);
|
const SKIP_TRUNCATE = new Set(["spatial_ref_sys", "__drizzle_migrations", "payload_migrations"]);
|
||||||
|
|
||||||
|
/** Template build cache; gitignored, disposable, rebuilt on hash mismatch. */
|
||||||
|
const TEMPLATE_CACHE_FILE = path.join(".cache", "testdb-template.json");
|
||||||
|
|
||||||
|
interface TemplateCache {
|
||||||
|
hash: string;
|
||||||
|
builtAt: string;
|
||||||
|
pgVersion: string;
|
||||||
|
dbName: string;
|
||||||
|
}
|
||||||
|
|
||||||
/** True when truncation should be skipped in favor of a full drop/recreate. */
|
/** True when truncation should be skipped in favor of a full drop/recreate. */
|
||||||
export function hardResetRequested(): boolean {
|
export function hardResetRequested(): boolean {
|
||||||
return process.env.TEST_DB_HARD_RESET === "1";
|
return process.env.TEST_DB_HARD_RESET === "1";
|
||||||
|
|
@ -59,6 +93,28 @@ function testDatabaseName(testUri: string): string {
|
||||||
return name;
|
return name;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Same connection string with its database name replaced. */
|
||||||
|
function withDatabaseName(testUri: string, dbName: string): string {
|
||||||
|
const url = new URL(testUri);
|
||||||
|
const segments = url.pathname.split("/").filter(Boolean);
|
||||||
|
if (segments.length === 0) throw new Error("Database URI has no database name");
|
||||||
|
segments[segments.length - 1] = dbName;
|
||||||
|
url.pathname = segments.join("/");
|
||||||
|
return url.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Template database URI (`ptf_app_test` -> `ptf_app_test_template`). */
|
||||||
|
export function templateDatabaseUri(): string {
|
||||||
|
const base = resolveTestDatabaseUri();
|
||||||
|
return withDatabaseName(base, `${testDatabaseName(base)}_template`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Per-vitest-worker clone URI (`ptf_app_test` -> `ptf_app_test_w<ID>`). */
|
||||||
|
export function workerDatabaseUri(workerId: string | number): string {
|
||||||
|
const base = resolveTestDatabaseUri();
|
||||||
|
return withDatabaseName(base, `${testDatabaseName(base)}_w${workerId}`);
|
||||||
|
}
|
||||||
|
|
||||||
function quotedIdentifier(identifier: string): string {
|
function quotedIdentifier(identifier: string): string {
|
||||||
return `"${identifier.replace(/"/g, '""')}"`;
|
return `"${identifier.replace(/"/g, '""')}"`;
|
||||||
}
|
}
|
||||||
|
|
@ -76,6 +132,14 @@ async function withAdminClient(testUri: string, fn: (client: Client) => Promise<
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Terminate every backend connected to `dbName` so it can be dropped/cloned. */
|
||||||
|
async function terminateBackends(admin: Client, dbName: string): Promise<void> {
|
||||||
|
await admin.query(
|
||||||
|
"SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = $1 AND pid <> pg_backend_pid()",
|
||||||
|
[dbName],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create the test database when missing. With `hardReset`, terminate
|
* Create the test database when missing. With `hardReset`, terminate
|
||||||
* connections, drop it and recreate from scratch instead.
|
* connections, drop it and recreate from scratch instead.
|
||||||
|
|
@ -85,10 +149,7 @@ export async function ensureTestDatabase(testUri: string, hardReset: boolean): P
|
||||||
await withAdminClient(testUri, async (admin) => {
|
await withAdminClient(testUri, async (admin) => {
|
||||||
const existing = await admin.query("SELECT 1 FROM pg_database WHERE datname = $1", [dbName]);
|
const existing = await admin.query("SELECT 1 FROM pg_database WHERE datname = $1", [dbName]);
|
||||||
if (hardReset && existing.rows.length > 0) {
|
if (hardReset && existing.rows.length > 0) {
|
||||||
await admin.query(
|
await terminateBackends(admin, dbName);
|
||||||
"SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = $1 AND pid <> pg_backend_pid()",
|
|
||||||
[dbName],
|
|
||||||
);
|
|
||||||
await admin.query(`DROP DATABASE ${quotedIdentifier(dbName)}`);
|
await admin.query(`DROP DATABASE ${quotedIdentifier(dbName)}`);
|
||||||
existing.rows.length = 0;
|
existing.rows.length = 0;
|
||||||
}
|
}
|
||||||
|
|
@ -98,10 +159,25 @@ export async function ensureTestDatabase(testUri: string, hardReset: boolean): P
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Drop the database when present, terminating any lingering backends. */
|
||||||
|
export async function dropDatabaseIfPresent(uri: string): Promise<boolean> {
|
||||||
|
const dbName = testDatabaseName(uri);
|
||||||
|
let dropped = false;
|
||||||
|
await withAdminClient(uri, async (admin) => {
|
||||||
|
const existing = await admin.query("SELECT 1 FROM pg_database WHERE datname = $1", [dbName]);
|
||||||
|
if (existing.rows.length === 0) return;
|
||||||
|
await terminateBackends(admin, dbName);
|
||||||
|
await admin.query(`DROP DATABASE ${quotedIdentifier(dbName)}`);
|
||||||
|
dropped = true;
|
||||||
|
});
|
||||||
|
return dropped;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create or diff the full schema via drizzle push. The migration chain
|
* Create or diff the full schema via drizzle push. The migration chain
|
||||||
* assumes a schema that push originally created (its first migration alters
|
* assumes a schema that push originally created (its first migration alters
|
||||||
* existing tables), so a fresh database is built by pushing, not migrating.
|
* existing tables), so a fresh database is built by pushing, not migrating.
|
||||||
|
* Warning/data-loss prompts are auto-accepted (see tests/push-schema.ts).
|
||||||
*/
|
*/
|
||||||
export function pushSchema(testUri: string): void {
|
export function pushSchema(testUri: string): void {
|
||||||
execSync("bun run tests/push-schema.ts", {
|
execSync("bun run tests/push-schema.ts", {
|
||||||
|
|
@ -149,8 +225,9 @@ export async function ensureAnalyticsTables(testUri: string): Promise<void> {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Truncate every table in the public schema except migration journals and
|
* Truncate every table in the public schema except migration journals and
|
||||||
* PostGIS internals. Idempotent by construction: the result is the same empty
|
* PostGIS internals. Only used by the legacy serial path (`TEST_DATABASE_URI`
|
||||||
* database no matter how many rows leaked from earlier runs.
|
* override) for bootstrap and teardown hygiene; template clones replace
|
||||||
|
* truncation everywhere else. Idempotent by construction.
|
||||||
*/
|
*/
|
||||||
export async function truncateAllData(testUri: string): Promise<void> {
|
export async function truncateAllData(testUri: string): Promise<void> {
|
||||||
const client = new Client({ connectionString: testUri });
|
const client = new Client({ connectionString: testUri });
|
||||||
|
|
@ -213,13 +290,190 @@ export function runSeedScripts(testUri: string): void {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Template database + schema-hash cache
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Full bootstrap, safe to call repeatedly: ensure the database (drop/recreate
|
* Deliberately broad input set for the template cache key. False positives
|
||||||
* on hard reset), apply migrations, truncate leftover data, reseed baselines
|
* (rebuild with no real change) cost one cold build; misses produce loud but
|
||||||
* and repair sequences.
|
* confusing "column does not exist" failures, recoverable via
|
||||||
|
* TEST_DB_HARD_RESET=1. When in doubt, add to the list.
|
||||||
*/
|
*/
|
||||||
export async function bootstrapTestDatabase(): Promise<string> {
|
const SCHEMA_HASH_FILES = [
|
||||||
const testUri = resolveTestDatabaseUri();
|
"src/payload.config.ts",
|
||||||
|
"src/payload-generated-schema.ts",
|
||||||
|
"drizzle.config.ts",
|
||||||
|
"package.json",
|
||||||
|
];
|
||||||
|
const SCHEMA_HASH_DIRS = ["src/collections", "src/globals", "src/utils", "src/migrations", "patches"];
|
||||||
|
const SCHEMA_HASH_PACKAGES = ["payload", "@payloadcms/drizzle", "drizzle-orm", "@payloadcms/plugin-mcp"];
|
||||||
|
|
||||||
|
function walkFiles(dir: string): string[] {
|
||||||
|
if (!existsSync(dir)) return [];
|
||||||
|
const out: string[] = [];
|
||||||
|
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||||
|
const full = path.join(dir, entry.name);
|
||||||
|
if (entry.isDirectory()) out.push(...walkFiles(full));
|
||||||
|
else if (entry.isFile()) out.push(full);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pgServerVersion(): Promise<string> {
|
||||||
|
let version = "unknown";
|
||||||
|
await withAdminClient(resolveTestDatabaseUri(), async (admin) => {
|
||||||
|
const { rows } = await admin.query("SHOW server_version");
|
||||||
|
version = String(rows[0]?.server_version ?? "unknown");
|
||||||
|
});
|
||||||
|
return version;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** sha256 over every schema-relevant input (see SCHEMA_HASH_* for the set). */
|
||||||
|
export async function schemaHash(): Promise<string> {
|
||||||
|
const pkg = JSON.parse(readFileSync(path.resolve("package.json"), "utf8")) as {
|
||||||
|
dependencies?: Record<string, string>;
|
||||||
|
devDependencies?: Record<string, string>;
|
||||||
|
};
|
||||||
|
const cwd = process.cwd();
|
||||||
|
const files = [
|
||||||
|
...SCHEMA_HASH_FILES.map((file) => path.resolve(cwd, file)),
|
||||||
|
...SCHEMA_HASH_DIRS.flatMap((dir) => walkFiles(path.resolve(cwd, dir))),
|
||||||
|
]
|
||||||
|
.filter((file) => existsSync(file))
|
||||||
|
.map((file) => path.relative(cwd, file))
|
||||||
|
.sort();
|
||||||
|
|
||||||
|
const hash = createHash("sha256");
|
||||||
|
for (const rel of files) {
|
||||||
|
hash.update(rel);
|
||||||
|
hash.update("\0");
|
||||||
|
hash.update(readFileSync(path.resolve(cwd, rel)));
|
||||||
|
hash.update("\0");
|
||||||
|
}
|
||||||
|
for (const dep of SCHEMA_HASH_PACKAGES) {
|
||||||
|
hash.update(`${dep}@${pkg.dependencies?.[dep] ?? pkg.devDependencies?.[dep] ?? "missing"}\n`);
|
||||||
|
}
|
||||||
|
hash.update(`pg:${await pgServerVersion()}\n`);
|
||||||
|
return hash.digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
|
function readTemplateCache(): TemplateCache | null {
|
||||||
|
try {
|
||||||
|
return JSON.parse(readFileSync(path.resolve(TEMPLATE_CACHE_FILE), "utf8")) as TemplateCache;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeTemplateCache(cache: TemplateCache): void {
|
||||||
|
const file = path.resolve(TEMPLATE_CACHE_FILE);
|
||||||
|
mkdirSync(path.dirname(file), { recursive: true });
|
||||||
|
writeFileSync(file, JSON.stringify(cache, null, 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Cheap liveness probe: does the template still exist and carry a schema? */
|
||||||
|
async function templateIsLive(templateUri: string): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
const client = new Client({ connectionString: templateUri });
|
||||||
|
await client.connect();
|
||||||
|
try {
|
||||||
|
const { rows } = await client.query(
|
||||||
|
"SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'payload_migrations'",
|
||||||
|
);
|
||||||
|
return rows.length > 0;
|
||||||
|
} finally {
|
||||||
|
await client.end();
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ensure `ptf_app_test_template` exists and matches the current schema hash.
|
||||||
|
* On cache miss (or `TEST_DB_HARD_RESET=1`, or a broken/missing template):
|
||||||
|
* drop/recreate it and run the full build (push, analytics DDL, seeds,
|
||||||
|
* sequence repair). On hit: return immediately after a liveness check.
|
||||||
|
* Never truncates - a template is a point-in-time image that clones inherit.
|
||||||
|
*/
|
||||||
|
export async function ensureTemplateDatabase(): Promise<string> {
|
||||||
|
const templateUri = templateDatabaseUri();
|
||||||
|
const templateName = testDatabaseName(templateUri);
|
||||||
|
const pgVersion = await pgServerVersion();
|
||||||
|
const hash = await schemaHash();
|
||||||
|
|
||||||
|
if (!hardResetRequested()) {
|
||||||
|
const cached = readTemplateCache();
|
||||||
|
if (cached && cached.hash === hash && cached.dbName === templateName && (await templateIsLive(templateUri))) {
|
||||||
|
console.log(`[test-db] template cache hit: ${templateName}`);
|
||||||
|
return templateUri;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const started = Date.now();
|
||||||
|
console.log(
|
||||||
|
`[test-db] building template ${templateName}${hardResetRequested() ? " (hard reset)" : ""}...`,
|
||||||
|
);
|
||||||
|
await ensureTestDatabase(templateUri, true);
|
||||||
|
await dropAnalyticsTables(templateUri);
|
||||||
|
pushSchema(templateUri);
|
||||||
|
await ensureAnalyticsTables(templateUri);
|
||||||
|
runSeedScripts(templateUri);
|
||||||
|
await repairSequences(templateUri);
|
||||||
|
writeTemplateCache({ hash, builtAt: new Date().toISOString(), pgVersion, dbName: templateName });
|
||||||
|
console.log(`[test-db] template ready: ${templateName} in ${((Date.now() - started) / 1000).toFixed(1)}s`);
|
||||||
|
return templateUri;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Replace the target database with an exact copy of the template. Terminate
|
||||||
|
* leftover backends and drop first so a crashed run's state can never leak
|
||||||
|
* into a fresh clone. Subject to the CLONING INVARIANT at the top of this
|
||||||
|
* file: nothing may be connected to the template while this runs.
|
||||||
|
*/
|
||||||
|
export async function cloneTemplateInto(targetUri: string): Promise<void> {
|
||||||
|
const target = testDatabaseName(targetUri);
|
||||||
|
const template = testDatabaseName(templateDatabaseUri());
|
||||||
|
await withAdminClient(targetUri, async (admin) => {
|
||||||
|
await terminateBackends(admin, target);
|
||||||
|
await admin.query(`DROP DATABASE IF EXISTS ${quotedIdentifier(target)}`);
|
||||||
|
await admin.query(`CREATE DATABASE ${quotedIdentifier(target)} TEMPLATE ${quotedIdentifier(template)}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Enumerate + drop `<base>_w<N>` clones left behind by crashed runs. */
|
||||||
|
export async function dropStaleWorkerDatabases(): Promise<number> {
|
||||||
|
const base = testDatabaseName(resolveTestDatabaseUri());
|
||||||
|
let dropped = 0;
|
||||||
|
await withAdminClient(resolveTestDatabaseUri(), async (admin) => {
|
||||||
|
// Postgres database names are [a-z0-9_]; none of those are regex
|
||||||
|
// specials, so the derived base can be interpolated directly.
|
||||||
|
const { rows } = await admin.query(
|
||||||
|
"SELECT datname FROM pg_database WHERE datname ~ $1",
|
||||||
|
[`^${base}_w[0-9]+$`],
|
||||||
|
);
|
||||||
|
for (const row of rows as { datname: string }[]) {
|
||||||
|
await terminateBackends(admin, row.datname);
|
||||||
|
await admin.query(`DROP DATABASE ${quotedIdentifier(row.datname)}`);
|
||||||
|
dropped += 1;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if (dropped > 0) console.log(`[test-db] dropped ${dropped} stale worker database(s)`);
|
||||||
|
return dropped;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Bootstrap entry points
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Legacy serial bootstrap against one shared database, safe to call
|
||||||
|
* repeatedly: ensure (drop/recreate on hard reset), push, truncate leftover
|
||||||
|
* data, reseed baselines, repair sequences. Used when `TEST_DATABASE_URI`
|
||||||
|
* explicitly points the suite at a single db (bisect mode).
|
||||||
|
*/
|
||||||
|
export async function bootstrapSerialDatabase(testUri: string): Promise<string> {
|
||||||
const hardReset = hardResetRequested();
|
const hardReset = hardResetRequested();
|
||||||
|
|
||||||
await ensureTestDatabase(testUri, hardReset);
|
await ensureTestDatabase(testUri, hardReset);
|
||||||
|
|
@ -230,7 +484,23 @@ export async function bootstrapTestDatabase(): Promise<string> {
|
||||||
runSeedScripts(testUri);
|
runSeedScripts(testUri);
|
||||||
await repairSequences(testUri);
|
await repairSequences(testUri);
|
||||||
|
|
||||||
const dbName = testDatabaseName(testUri);
|
console.log(`[test-db] ready: ${testDatabaseName(testUri)}${hardReset ? " (hard reset)" : ""}`);
|
||||||
console.log(`[test-db] ready: ${dbName}${hardReset ? " (hard reset)" : ""}`);
|
return testUri;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Full bootstrap for the serial databases (Playwright; legacy vitest bisect
|
||||||
|
* mode). Without an explicit override it guarantees the template and hands
|
||||||
|
* back a FRESH clone of it - no truncate, no push in the steady state.
|
||||||
|
*/
|
||||||
|
export async function bootstrapTestDatabase(): Promise<string> {
|
||||||
|
const testUri = resolveTestDatabaseUri();
|
||||||
|
if (process.env.TEST_DATABASE_URI) {
|
||||||
|
return bootstrapSerialDatabase(testUri);
|
||||||
|
}
|
||||||
|
|
||||||
|
await ensureTemplateDatabase();
|
||||||
|
await cloneTemplateInto(testUri);
|
||||||
|
console.log(`[test-db] ready: ${testDatabaseName(testUri)} (cloned from template)`);
|
||||||
return testUri;
|
return testUri;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,9 @@ import { bootstrapTestDatabase } from "./test-db";
|
||||||
/**
|
/**
|
||||||
* Vitest global setup: point the suite at the dedicated test database and
|
* Vitest global setup: point the suite at the dedicated test database and
|
||||||
* leave it in a known state (ensured, migrated, truncated, seeded, sequences
|
* leave it in a known state (ensured, migrated, truncated, seeded, sequences
|
||||||
* repaired) before any test file loads.
|
* repaired) before any test file loads. Stage 2 rewires this entry point to
|
||||||
|
* the template + per-fork clone lifecycle; until then it bootstraps the one
|
||||||
|
* serial test database exactly as before.
|
||||||
*/
|
*/
|
||||||
export default async function globalSetup(): Promise<void> {
|
export default async function globalSetup(): Promise<void> {
|
||||||
await bootstrapTestDatabase();
|
await bootstrapTestDatabase();
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue