/** * Test Database Setup and Cleanup Utilities * * This file provides utilities for setting up and cleaning up test databases * to ensure test isolation and prevent test data pollution. */ import { MongoClient, Db } from 'mongodb'; let testClient: MongoClient | null = null; let testDb: Db | null = null; /** * Get or create a connection to the test database */ export async function getTestDatabase(): Promise { if (testDb) { return testDb; } const mongoUrl = process.env.TEST_MONGO_URL || 'mongodb://localhost:27017'; const dbName = process.env.TEST_DB_NAME || 'flink_oauth_test'; testClient = await MongoClient.connect(mongoUrl); testDb = testClient.db(dbName); return testDb; } /** * Clean up all test collections */ export async function cleanupTestDatabase(): Promise { if (!testDb) { return; } const collections = await testDb.listCollections().toArray(); for (const collection of collections) { await testDb.collection(collection.name).deleteMany({}); } } /** * Close test database connection */ export async function closeTestDatabase(): Promise { if (testClient) { await testClient.close(); testClient = null; testDb = null; } } /** * Drop the entire test database (use with caution) */ export async function dropTestDatabase(): Promise { if (!testDb) { return; } await testDb.dropDatabase(); } /** * Insert test data into a collection */ export async function insertTestData( collectionName: string, documents: T[] ): Promise { const db = await getTestDatabase(); await db.collection(collectionName).insertMany(documents as any[]); } /** * Get all documents from a test collection */ export async function getTestData(collectionName: string): Promise { const db = await getTestDatabase(); return db.collection(collectionName).find({}).toArray() as Promise; } /** * Clear a specific test collection */ export async function clearTestCollection(collectionName: string): Promise { const db = await getTestDatabase(); await db.collection(collectionName).deleteMany({}); } /** * Setup function to run before each test */ export async function beforeEachTest(): Promise { await cleanupTestDatabase(); } /** * Teardown function to run after all tests */ export async function afterAllTests(): Promise { await cleanupTestDatabase(); await closeTestDatabase(); }