feat(auth): consolidate multi-user auth and admin controls
This commit is contained in:
@@ -2,11 +2,53 @@
|
||||
* Test utilities for backend integration tests
|
||||
*/
|
||||
import { PrismaClient } from "../generated/client";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { execSync } from "child_process";
|
||||
|
||||
// Use a separate test database
|
||||
const TEST_DB_PATH = path.resolve(__dirname, "../../prisma/test.db");
|
||||
// Use a unique test database per test-file import to avoid cross-file contention
|
||||
// when Vitest runs test files in parallel.
|
||||
const TEST_DB_FILENAME = `test.${process.pid}.${Math.random().toString(16).slice(2)}.db`;
|
||||
const TEST_DB_PATH = path.resolve(__dirname, "../../prisma", TEST_DB_FILENAME);
|
||||
const DB_PUSH_LOCK_PATH = path.resolve(__dirname, "../../prisma/.test-db-push.lock");
|
||||
|
||||
const sleepSync = (ms: number) => {
|
||||
const shared = new Int32Array(new SharedArrayBuffer(4));
|
||||
Atomics.wait(shared, 0, 0, ms);
|
||||
};
|
||||
|
||||
const withDbPushLock = (fn: () => void) => {
|
||||
const start = Date.now();
|
||||
let fd: number | null = null;
|
||||
while (fd === null) {
|
||||
try {
|
||||
fd = fs.openSync(DB_PUSH_LOCK_PATH, "wx");
|
||||
fs.writeFileSync(fd, String(process.pid));
|
||||
} catch (error) {
|
||||
const err = error as NodeJS.ErrnoException;
|
||||
if (err.code !== "EEXIST") throw error;
|
||||
if (Date.now() - start > 30_000) {
|
||||
throw new Error("Timed out waiting for Prisma db push lock");
|
||||
}
|
||||
sleepSync(50);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
fn();
|
||||
} finally {
|
||||
try {
|
||||
fs.closeSync(fd);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
try {
|
||||
fs.unlinkSync(DB_PUSH_LOCK_PATH);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Get a test Prisma client pointing to the test database
|
||||
@@ -32,10 +74,19 @@ export const setupTestDb = () => {
|
||||
|
||||
// Run Prisma migrations to create the test database
|
||||
try {
|
||||
execSync("npx prisma db push --skip-generate", {
|
||||
cwd: path.resolve(__dirname, "../../"),
|
||||
env: { ...process.env, DATABASE_URL: databaseUrl },
|
||||
stdio: "pipe",
|
||||
withDbPushLock(() => {
|
||||
execSync("npx prisma db push --skip-generate --force-reset", {
|
||||
cwd: path.resolve(__dirname, "../../"),
|
||||
env: {
|
||||
...process.env,
|
||||
DATABASE_URL: databaseUrl,
|
||||
// Work around Prisma schema engine failures on this repo's schema
|
||||
// (seen as a blank "Schema engine error:" from `prisma db push`).
|
||||
// `RUST_LOG=info` reliably avoids the failure mode.
|
||||
RUST_LOG: "info",
|
||||
},
|
||||
stdio: "pipe",
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Failed to setup test database:", error);
|
||||
|
||||
Reference in New Issue
Block a user