import { CrossKvDB, } from "./cross-kv.js"; import { MemDB, } from "./mem-db.js"; import type { Database, } from "./types.js"; /** * Database type for testing. * Can be set via TEST_DB_TYPE environment variable. * Defaults to 'memory' for fast in-memory tests. */ export type TestDbType = "memory" | "crosskv"; /** * Get the database type to use for tests from environment variable. * Defaults to 'memory' if not set or invalid. */ export function getTestDbType(): TestDbType { const envType = process.env.TEST_DB_TYPE?.toLowerCase(); if (envType === "crosskv" || envType === "cross-kv") { return "crosskv"; } return "memory"; } /** * Context for managing test database lifecycle. * Use this to ensure proper cleanup of resources. */ export interface TestDbContext { db: Database cleanup: () => Promise } /** * Counter for generating unique database paths for CrossKV. */ let dbCounter = 0; /** * Create a test database instance based on TEST_DB_TYPE environment variable. * * This factory function creates either a MemDB (in-memory) or CrossKvDB (persistent) * based on the TEST_DB_TYPE environment variable. This allows running the entire * test suite against both database implementations to ensure compatibility. * * @returns TestDbContext containing the database instance and cleanup function * * @example * ```typescript * describe("MyComponent", () => { * let ctx: TestDbContext; * * beforeEach(async () => { * ctx = await createTestDb(); * }); * * afterEach(async () => { * await ctx.cleanup(); * }); * * it("should work", async () => { * await ctx.db.set(key, value); * // ... rest of test * }); * }); * ``` */ export async function createTestDb(): Promise { const dbType = getTestDbType(); if (dbType === "crosskv") { const dbPath = `./test-db-${process.hrtime.bigint()}-${dbCounter++}.db`; const db = new CrossKvDB(); await db.open(dbPath, true); return { db, cleanup: async () => { await db.close(); try { const fs = await import("node:fs/promises"); await fs.unlink(dbPath); } catch (error) { // Ignore if file doesn't exist if ((error as NodeJS.ErrnoException).code !== "ENOENT") { console.warn(`Failed to cleanup test database: ${dbPath}`, error); } } }, }; } // Default to MemDB const db = new MemDB(); return { db, cleanup: async () => { await db.close(); }, }; } /** * Helper function to create a test database for synchronous setup. * Note: This still returns a Promise that must be awaited. * * @deprecated Use createTestDb() instead for better naming clarity */ export const getTestDb = createTestDb; /** * Check if tests are running with CrossKV database. * Useful for conditional test logic or expectations. */ export function isUsingCrossKv(): boolean { return getTestDbType() === "crosskv"; } /** * Check if tests are running with MemDB database. * Useful for conditional test logic or expectations. */ export function isUsingMemDb(): boolean { return getTestDbType() === "memory"; }