test(vitest): parallel forks with per-worker database clones
Stage 2 of the int-suite speedup: pool=forks with fileParallelism and a default cap of 8 (VITEST_MAX_FORKS), each fork cloning the template into ptf_*_test_w<ID> via tests/vitest-worker-setup.ts; environment defaults to node with jsdom opt-in docblocks on the six DOM-consuming specs; a tiny reporter writes a failure marker so post-run cleanup keeps clones after red runs (KEEP_TEST_DBS=1 forces keeping); pg pools cap at TEST_PG_POOL_MAX=3 per boot in workers mode. Legacy serial mode stays reachable by setting TEST_DATABASE_URI. Notes from the gate G2 runs (Vitest 4.0.16): globalTeardown config was removed in Vitest 4 entirely - cleanup now returns from globalSetup. The pool scheduler only reuses worker processes when isolate:false, so this per-file-fork stage lands short of the wall-time target and is expected to be superseded by the gated isolate:false stage. Gate G2 warm serial equivalent stays green via TEST_DATABASE_URI bisect mode.
This commit is contained in:
parent
15177b7765
commit
cc8a911502
19 changed files with 200 additions and 49 deletions
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -48,6 +48,8 @@ npm-debug.log*
|
||||||
/src/generated/
|
/src/generated/
|
||||||
# testing
|
# testing
|
||||||
/test-results/
|
/test-results/
|
||||||
|
# test-db template cache + int failure marker (see tests/test-db.ts, tests/vitest-marker.ts)
|
||||||
|
/.cache/
|
||||||
*.tsbuildinfo
|
*.tsbuildinfo
|
||||||
# typescript
|
# typescript
|
||||||
# vercel
|
# vercel
|
||||||
|
|
|
||||||
|
|
@ -595,6 +595,9 @@ export default buildConfig({
|
||||||
db: postgresAdapter({
|
db: postgresAdapter({
|
||||||
pool: {
|
pool: {
|
||||||
connectionString: process.env.DATABASE_URI || "",
|
connectionString: process.env.DATABASE_URI || "",
|
||||||
|
// Test workers cap the pg pool per boot (tests/vitest-worker-setup.ts
|
||||||
|
// sets TEST_PG_POOL_MAX); unset in dev/prod, zero behavior change there.
|
||||||
|
...(process.env.TEST_PG_POOL_MAX ? { max: Number(process.env.TEST_PG_POOL_MAX) } : {}),
|
||||||
},
|
},
|
||||||
// push: process.env.NODE_ENV === "development",
|
// push: process.env.NODE_ENV === "development",
|
||||||
// Env-gated drizzle push: only the test-database bootstrap (DB_PUSH=1) uses
|
// Env-gated drizzle push: only the test-database bootstrap (DB_PUSH=1) uses
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,4 @@
|
||||||
|
// @vitest-environment jsdom (specs clear window.localStorage via the Shims evaluator)
|
||||||
import { getPayload, Payload } from "payload";
|
import { getPayload, Payload } from "payload";
|
||||||
import config from "@/payload.config";
|
import config from "@/payload.config";
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
// @vitest-environment node
|
|
||||||
// Node realm on purpose: this drives the real http/ws server, and jose's
|
// Node realm on purpose: this drives the real http/ws server, and jose's
|
||||||
// key-type checks are realm-sensitive (a jsdom realm's Uint8Array intrinsics
|
// key-type checks are realm-sensitive (a jsdom realm's Uint8Array intrinsics
|
||||||
// differ from the externalized jose module's).
|
// differ from the externalized jose module's).
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
// @vitest-environment node
|
|
||||||
// jose (via payload's jwtSign) fails under jsdom: its module-level TextEncoder and
|
// jose (via payload's jwtSign) fails under jsdom: its module-level TextEncoder and
|
||||||
// the global Uint8Array come from different realms, so signing throws a TypeError.
|
// the global Uint8Array come from different realms, so signing throws a TypeError.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,4 @@
|
||||||
|
// @vitest-environment jsdom
|
||||||
import { createElement } from "react";
|
import { createElement } from "react";
|
||||||
import { cleanup, render, screen } from "@testing-library/react";
|
import { cleanup, render, screen } from "@testing-library/react";
|
||||||
import { afterEach, describe, expect, it } from "vitest";
|
import { afterEach, describe, expect, it } from "vitest";
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,4 @@
|
||||||
|
// @vitest-environment jsdom
|
||||||
import { createElement } from "react";
|
import { createElement } from "react";
|
||||||
import { act, cleanup, render, waitFor } from "@testing-library/react";
|
import { act, cleanup, render, waitFor } from "@testing-library/react";
|
||||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
// @vitest-environment node
|
|
||||||
// jose (via payload's jwtSign) fails under jsdom: its module-level TextEncoder and
|
// jose (via payload's jwtSign) fails under jsdom: its module-level TextEncoder and
|
||||||
// the global Uint8Array come from different realms, so signing throws a TypeError.
|
// the global Uint8Array come from different realms, so signing throws a TypeError.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
// @vitest-environment node
|
|
||||||
// jose (via payload's jwtSign) fails under jsdom: its module-level TextEncoder and
|
// jose (via payload's jwtSign) fails under jsdom: its module-level TextEncoder and
|
||||||
// the global Uint8Array come from different realms, so signing throws a TypeError.
|
// the global Uint8Array come from different realms, so signing throws a TypeError.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,4 @@
|
||||||
|
// @vitest-environment jsdom
|
||||||
import { createElement as h } from "react";
|
import { createElement as h } from "react";
|
||||||
import { afterEach, describe, expect, it } from "vitest";
|
import { afterEach, describe, expect, it } from "vitest";
|
||||||
import { cleanup, render, screen, within } from "@testing-library/react";
|
import { cleanup, render, screen, within } from "@testing-library/react";
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,4 @@
|
||||||
|
// @vitest-environment jsdom
|
||||||
import { createElement } from "react";
|
import { createElement } from "react";
|
||||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,4 @@
|
||||||
|
// @vitest-environment jsdom (specs stub window.localStorage accessors)
|
||||||
import { beforeEach, describe, expect, it } from "vitest";
|
import { beforeEach, describe, expect, it } from "vitest";
|
||||||
import {
|
import {
|
||||||
DEFAULT_GATES,
|
DEFAULT_GATES,
|
||||||
|
|
|
||||||
|
|
@ -103,15 +103,21 @@ function withDatabaseName(testUri: string, dbName: string): string {
|
||||||
return url.toString();
|
return url.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Template database URI (`ptf_app_test` -> `ptf_app_test_template`). */
|
/**
|
||||||
export function templateDatabaseUri(): string {
|
* Template database URI for a given serial test URI (`ptf_app_test` ->
|
||||||
const base = resolveTestDatabaseUri();
|
* `ptf_app_test_template`). Defaults to resolving from the environment; pass
|
||||||
|
* an explicit URI when the caller's `process.env.DATABASE_URI` has already
|
||||||
|
* been repointed at the serial test db (worker setup files do exactly that,
|
||||||
|
* so re-resolving there would append `_test` twice).
|
||||||
|
*/
|
||||||
|
export function templateDatabaseUri(serialTestUri?: string): string {
|
||||||
|
const base = serialTestUri ?? resolveTestDatabaseUri();
|
||||||
return withDatabaseName(base, `${testDatabaseName(base)}_template`);
|
return withDatabaseName(base, `${testDatabaseName(base)}_template`);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Per-vitest-worker clone URI (`ptf_app_test` -> `ptf_app_test_w<ID>`). */
|
/** Per-vitest-worker clone URI (`ptf_app_test` -> `ptf_app_test_w<ID>`). */
|
||||||
export function workerDatabaseUri(workerId: string | number): string {
|
export function workerDatabaseUri(workerId: string | number, serialTestUri?: string): string {
|
||||||
const base = resolveTestDatabaseUri();
|
const base = serialTestUri ?? resolveTestDatabaseUri();
|
||||||
return withDatabaseName(base, `${testDatabaseName(base)}_w${workerId}`);
|
return withDatabaseName(base, `${testDatabaseName(base)}_w${workerId}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -132,12 +138,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> {
|
* Drop a database even while client pools keep reconnecting to it. Postgres
|
||||||
await admin.query(
|
* >= 13 (`WITH (FORCE)`) terminates conflicting sessions itself and waits for
|
||||||
"SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = $1 AND pid <> pg_backend_pid()",
|
* the lock, removing the terminate-then-drop race against vitest forks that
|
||||||
[dbName],
|
* are still shutting down when post-run cleanup runs.
|
||||||
);
|
*/
|
||||||
|
async function forceDropDatabase(admin: Client, dbName: string): Promise<void> {
|
||||||
|
await admin.query(`DROP DATABASE IF EXISTS ${quotedIdentifier(dbName)} WITH (FORCE)`);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -149,8 +157,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 terminateBackends(admin, dbName);
|
await forceDropDatabase(admin, dbName);
|
||||||
await admin.query(`DROP DATABASE ${quotedIdentifier(dbName)}`);
|
|
||||||
existing.rows.length = 0;
|
existing.rows.length = 0;
|
||||||
}
|
}
|
||||||
if (existing.rows.length === 0) {
|
if (existing.rows.length === 0) {
|
||||||
|
|
@ -166,8 +173,7 @@ export async function dropDatabaseIfPresent(uri: string): Promise<boolean> {
|
||||||
await withAdminClient(uri, async (admin) => {
|
await withAdminClient(uri, 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 (existing.rows.length === 0) return;
|
if (existing.rows.length === 0) return;
|
||||||
await terminateBackends(admin, dbName);
|
await forceDropDatabase(admin, dbName);
|
||||||
await admin.query(`DROP DATABASE ${quotedIdentifier(dbName)}`);
|
|
||||||
dropped = true;
|
dropped = true;
|
||||||
});
|
});
|
||||||
return dropped;
|
return dropped;
|
||||||
|
|
@ -427,17 +433,19 @@ export async function ensureTemplateDatabase(): Promise<string> {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Replace the target database with an exact copy of the template. Terminate
|
* Replace the target database with an exact copy of the template. The
|
||||||
* leftover backends and drop first so a crashed run's state can never leak
|
* template is addressed by name derived from the target (clone `_w<N>` suffix
|
||||||
* into a fresh clone. Subject to the CLONING INVARIANT at the top of this
|
* stripped, `_template` appended), so this never re-resolves the environment
|
||||||
* file: nothing may be connected to the template while this runs.
|
* and works after DATABASE_URI mutations. 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> {
|
export async function cloneTemplateInto(targetUri: string): Promise<void> {
|
||||||
const target = testDatabaseName(targetUri);
|
const target = testDatabaseName(targetUri);
|
||||||
const template = testDatabaseName(templateDatabaseUri());
|
const template = `${target.replace(/_w[0-9]+$/, "")}_template`;
|
||||||
await withAdminClient(targetUri, async (admin) => {
|
await withAdminClient(targetUri, async (admin) => {
|
||||||
await terminateBackends(admin, target);
|
await forceDropDatabase(admin, target);
|
||||||
await admin.query(`DROP DATABASE IF EXISTS ${quotedIdentifier(target)}`);
|
|
||||||
await admin.query(`CREATE DATABASE ${quotedIdentifier(target)} TEMPLATE ${quotedIdentifier(template)}`);
|
await admin.query(`CREATE DATABASE ${quotedIdentifier(target)} TEMPLATE ${quotedIdentifier(template)}`);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -454,8 +462,7 @@ export async function dropStaleWorkerDatabases(): Promise<number> {
|
||||||
[`^${base}_w[0-9]+$`],
|
[`^${base}_w[0-9]+$`],
|
||||||
);
|
);
|
||||||
for (const row of rows as { datname: string }[]) {
|
for (const row of rows as { datname: string }[]) {
|
||||||
await terminateBackends(admin, row.datname);
|
await forceDropDatabase(admin, row.datname);
|
||||||
await admin.query(`DROP DATABASE ${quotedIdentifier(row.datname)}`);
|
|
||||||
dropped += 1;
|
dropped += 1;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,29 @@
|
||||||
import { bootstrapTestDatabase } from "./test-db";
|
import { bootstrapTestDatabase, dropStaleWorkerDatabases, ensureTemplateDatabase } from "./test-db";
|
||||||
|
import { clearFailureMarker } from "./vitest-marker";
|
||||||
|
import vitestTeardown from "./vitest-teardown";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Vitest global setup: point the suite at the dedicated test database and
|
* Vitest global setup. Two modes:
|
||||||
* leave it in a known state (ensured, migrated, truncated, seeded, sequences
|
*
|
||||||
* repaired) before any test file loads. Stage 2 rewires this entry point to
|
* - Workers mode (default): guarantee the template database, then drop any
|
||||||
* the template + per-fork clone lifecycle; until then it bootstraps the one
|
* `<base>_w<N>` clones left behind by crashed runs. Per-fork cloning lives
|
||||||
* serial test database exactly as before.
|
* in tests/vitest-worker-setup.ts; nothing here truncates. After this
|
||||||
|
* function returns no further connections touch the template until the next
|
||||||
|
* build (CLONING INVARIANT in tests/test-db.ts).
|
||||||
|
* - Legacy serial mode (`TEST_DATABASE_URI` set): today's single-database
|
||||||
|
* truncate bootstrap, for bisecting flakes.
|
||||||
|
*
|
||||||
|
* The returned function is executed after the run: Vitest 4 removed the
|
||||||
|
* `globalTeardown` config option, returning a teardown from globalSetup is
|
||||||
|
* the supported contract (see tests/vitest-teardown.ts).
|
||||||
*/
|
*/
|
||||||
export default async function globalSetup(): Promise<void> {
|
export default async function globalSetup(): Promise<() => Promise<void>> {
|
||||||
await bootstrapTestDatabase();
|
clearFailureMarker();
|
||||||
|
if (process.env.TEST_DATABASE_URI) {
|
||||||
|
await bootstrapTestDatabase();
|
||||||
|
} else {
|
||||||
|
await ensureTemplateDatabase();
|
||||||
|
await dropStaleWorkerDatabases();
|
||||||
|
}
|
||||||
|
return vitestTeardown;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
25
tests/vitest-marker.ts
Normal file
25
tests/vitest-marker.ts
Normal file
|
|
@ -0,0 +1,25 @@
|
||||||
|
import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
|
||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Failure marker shared by the custom vitest reporter (writer) and global
|
||||||
|
* teardown (reader). Vitest's globalTeardown cannot portably see pass/fail
|
||||||
|
* state, so the reporter leaves this file behind on failure and clears it on
|
||||||
|
* success; teardown keeps worker clones while it exists. globalSetup deletes
|
||||||
|
* a stale marker at startup so a run killed before reporting cannot keep
|
||||||
|
* clones alive forever.
|
||||||
|
*/
|
||||||
|
export const FAILURE_MARKER_FILE = path.resolve(".cache", "test-int-failed");
|
||||||
|
|
||||||
|
export function clearFailureMarker(): void {
|
||||||
|
rmSync(FAILURE_MARKER_FILE, { force: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function writeFailureMarker(reason: string): void {
|
||||||
|
mkdirSync(path.dirname(FAILURE_MARKER_FILE), { recursive: true });
|
||||||
|
writeFileSync(FAILURE_MARKER_FILE, `${new Date().toISOString()} ${reason}\n`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function failureMarkerPresent(): boolean {
|
||||||
|
return existsSync(FAILURE_MARKER_FILE);
|
||||||
|
}
|
||||||
16
tests/vitest-reporter.ts
Normal file
16
tests/vitest-reporter.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
||||||
|
import { clearFailureMarker, writeFailureMarker } from "./vitest-marker";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Minimal custom reporter: records run outcome in the failure marker file so
|
||||||
|
* globalTeardown can keep worker database clones after a failed run (and drop
|
||||||
|
* them after a green one). See tests/vitest-marker.ts for why the reporter is
|
||||||
|
* the reliable channel. Vitest 4 calls onTestRunEnd(modules, errors, state)
|
||||||
|
* with state "passed" | "failed" | "interrupted".
|
||||||
|
*/
|
||||||
|
export default class FailureMarkerReporter {
|
||||||
|
onTestRunEnd(_modules: unknown[], errors: unknown[], state?: string): void {
|
||||||
|
const passed = (state ?? "passed") === "passed" && (!errors || errors.length === 0);
|
||||||
|
if (passed) clearFailureMarker();
|
||||||
|
else writeFailureMarker(state ?? "failed");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,14 +1,30 @@
|
||||||
import { resolveTestDatabaseUri, truncateAllData } from "./test-db";
|
import { dropStaleWorkerDatabases, resolveTestDatabaseUri, truncateAllData } from "./test-db";
|
||||||
|
import { failureMarkerPresent } from "./vitest-marker";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Vitest global teardown: leave the test database empty after the run. The
|
* Post-run cleanup returned by tests/vitest-global.ts (Vitest 4 removed the
|
||||||
* next run truncates again anyway, so this is hygiene, not correctness:
|
* `globalTeardown` config option entirely; the supported contract is that
|
||||||
* failures here must never fail the suite.
|
* globalSetup returns this function). Failures here must never fail the run;
|
||||||
|
* leftovers are dropped by the next run's globalSetup sweep regardless.
|
||||||
|
*
|
||||||
|
* - Workers mode: drop every `<base>_w<N>` clone after a green run; keep them
|
||||||
|
* when the failure marker exists (postmortem) or `KEEP_TEST_DBS=1`. The
|
||||||
|
* template itself survives across runs and is only rebuilt on hash mismatch
|
||||||
|
* or `TEST_DB_HARD_RESET=1`.
|
||||||
|
* - Legacy serial mode (`TEST_DATABASE_URI` set): truncate for hygiene.
|
||||||
*/
|
*/
|
||||||
export default async function globalTeardown(): Promise<void> {
|
export default async function vitestTeardown(): Promise<void> {
|
||||||
try {
|
try {
|
||||||
await truncateAllData(resolveTestDatabaseUri());
|
if (process.env.TEST_DATABASE_URI) {
|
||||||
|
await truncateAllData(resolveTestDatabaseUri());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (process.env.KEEP_TEST_DBS === "1" || failureMarkerPresent()) {
|
||||||
|
console.log("[test-db] keeping worker clones (failed run or KEEP_TEST_DBS=1)");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await dropStaleWorkerDatabases();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn("[test-db] teardown truncate failed:", error);
|
console.warn("[test-db] teardown cleanup failed:", error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
44
tests/vitest-worker-setup.ts
Normal file
44
tests/vitest-worker-setup.ts
Normal file
|
|
@ -0,0 +1,44 @@
|
||||||
|
import { cloneTemplateInto, workerDatabaseUri } from "./test-db";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Per-fork vitest setup, appended AFTER vitest.setup.ts in setupFiles. Gives
|
||||||
|
* every fork its own clone of the template database (`<base>_w<ID>`),
|
||||||
|
* repoints DATABASE_URI at it, and caps the pg pool per Payload boot so N
|
||||||
|
* forks stay far below Postgres' max_connections.
|
||||||
|
*
|
||||||
|
* No-ops outside workers mode: with `TEST_DATABASE_URI` set the suite runs in
|
||||||
|
* legacy serial mode against the single override db (bisect hatch), and a
|
||||||
|
* missing VITEST_WORKER_ID means this is not a vitest worker process.
|
||||||
|
*
|
||||||
|
* NOTE: vitest imports setupFiles but never calls their default export, so
|
||||||
|
* the work happens in a top-level IIFE below. The vite-node SSR transform
|
||||||
|
* hoists top-level await into an async wrapper, so side effects MUST live
|
||||||
|
* inside the awaited function, not before it.
|
||||||
|
*
|
||||||
|
* The clone happens ONCE PER FORK, not per test file: setup files re-run
|
||||||
|
* before every file under isolate:true, but process.env survives those module
|
||||||
|
* resets, so the marker env var short-circuits repeats. Within a fork, files
|
||||||
|
* keep running sequentially against one database that started empty plus the
|
||||||
|
* seeded baseline, exactly mirroring the old cross-file semantics while two
|
||||||
|
* forks never share tables.
|
||||||
|
*/
|
||||||
|
const CLONED_MARKER_ENV = "PTF_WORKER_DB_CLONED";
|
||||||
|
|
||||||
|
async function attachWorkerDatabase(): Promise<void> {
|
||||||
|
if (process.env.TEST_DATABASE_URI || !process.env.VITEST_WORKER_ID) return;
|
||||||
|
|
||||||
|
// vitest.setup.ts already repointed DATABASE_URI at the serial test db, so
|
||||||
|
// derive names from THAT (re-resolving would append `_test` twice).
|
||||||
|
const uri = workerDatabaseUri(process.env.VITEST_WORKER_ID, process.env.DATABASE_URI);
|
||||||
|
if (process.env[CLONED_MARKER_ENV] === uri) return;
|
||||||
|
|
||||||
|
await cloneTemplateInto(uri);
|
||||||
|
process.env[CLONED_MARKER_ENV] = uri;
|
||||||
|
process.env.DATABASE_URI = uri;
|
||||||
|
if (!process.env.TEST_PG_POOL_MAX) {
|
||||||
|
// Reads as pg PoolConfig.max in src/payload.config.ts (unset elsewhere).
|
||||||
|
process.env.TEST_PG_POOL_MAX = "3";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await attachWorkerDatabase();
|
||||||
|
|
@ -2,16 +2,31 @@ import { defineConfig } from "vitest/config";
|
||||||
import react from "@vitejs/plugin-react";
|
import react from "@vitejs/plugin-react";
|
||||||
import tsconfigPaths from "vite-tsconfig-paths";
|
import tsconfigPaths from "vite-tsconfig-paths";
|
||||||
|
|
||||||
|
// Setting TEST_DATABASE_URI forces the legacy single-database serial mode
|
||||||
|
// (bisect hatch): shared db, truncate per run, no forks and no clones.
|
||||||
|
const serialMode = Boolean(process.env.TEST_DATABASE_URI);
|
||||||
|
const maxForks = Number(process.env.VITEST_MAX_FORKS ?? 8);
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
plugins: [tsconfigPaths(), react()],
|
plugins: [tsconfigPaths(), react()],
|
||||||
test: {
|
test: {
|
||||||
environment: "jsdom",
|
// Node by default; component specs opt into jsdom with a
|
||||||
setupFiles: ["./vitest.setup.ts"],
|
// `// @vitest-environment jsdom` docblock.
|
||||||
|
environment: "node",
|
||||||
|
setupFiles: ["./vitest.setup.ts", "./tests/vitest-worker-setup.ts"],
|
||||||
include: ["tests/int/**/*.int.spec.ts"],
|
include: ["tests/int/**/*.int.spec.ts"],
|
||||||
// Serial test files: every spec shares one test database, and parallel
|
|
||||||
// workers against it produced flaky cross-file interference.
|
|
||||||
fileParallelism: false,
|
|
||||||
globalSetup: ["./tests/vitest-global.ts"],
|
globalSetup: ["./tests/vitest-global.ts"],
|
||||||
globalTeardown: ["./tests/vitest-teardown.ts"],
|
reporters: ["default", "./tests/vitest-reporter.ts"],
|
||||||
|
...(serialMode
|
||||||
|
? { fileParallelism: false }
|
||||||
|
: {
|
||||||
|
// Per-fork worker databases (tests/vitest-worker-setup.ts) replace
|
||||||
|
// the old serial execution: cross-file data interference is gone by
|
||||||
|
// construction because two forks never share tables. Fork cap stays
|
||||||
|
// conservative: Postgres max_connections=100 on this box plus IO.
|
||||||
|
fileParallelism: true,
|
||||||
|
pool: "forks" as const,
|
||||||
|
maxWorkers: maxForks,
|
||||||
|
}),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue