diff --git a/scripts/jest-setup.ts b/scripts/jest-setup.ts index 9ebada5f16..953cdd1335 100644 --- a/scripts/jest-setup.ts +++ b/scripts/jest-setup.ts @@ -1,21 +1,26 @@ import { Client, type ClientConfig } from 'pg'; import { migrateDb } from '../src/migrator'; import { getDbConfig } from '../src/test/e2e/helpers/database-config'; +import { testDbPrefix } from '../src/test/e2e/helpers/database-init'; let initializationPromise: Promise | null = null; + const initializeTemplateDb = (db: ClientConfig): Promise => { if (!initializationPromise) { initializationPromise = (async () => { const testDBTemplateName = process.env.TEST_DB_TEMPLATE_NAME; + const client = new Client(db); await client.connect(); console.log(`Initializing template database ${testDBTemplateName}`); - // code to clean up, but only on next run, we could do it at tear down... but is it really needed? - // const result = await client.query(`select datname from pg_database where datname like 'unleashtestdb_%';`) - // result.rows.forEach(async (row: any) => { - // console.log(`Dropping test database ${row.datname}`); - // await client.query(`DROP DATABASE ${row.datname}`); - // }); + // first clean up databases from previous runs + const result = await client.query( + `select datname from pg_database where datname like '${testDbPrefix}%';`, + ); + result.rows.forEach(async (row: any) => { + console.log(`Dropping test database ${row.datname}`); + await client.query(`DROP DATABASE ${row.datname}`); + }); await client.query(`DROP DATABASE IF EXISTS ${testDBTemplateName}`); await client.query(`CREATE DATABASE ${testDBTemplateName}`); await client.end(); diff --git a/src/test/e2e/helpers/database-init.ts b/src/test/e2e/helpers/database-init.ts index fbf032c1d6..49bdb943a7 100644 --- a/src/test/e2e/helpers/database-init.ts +++ b/src/test/e2e/helpers/database-init.ts @@ -24,6 +24,8 @@ import { v4 as uuidv4 } from 'uuid'; // because of db-migrate bug (https://github.com/Unleash/unleash/issues/171) process.setMaxListeners(0); +export const testDbPrefix = 'unleashtestdb_'; + async function getDefaultEnvRolePermissions(knex) { return knex.table('role_permission').whereIn('environment', ['default']); } @@ -108,7 +110,7 @@ export default async function init( getLogger: LogProvider = noLoggerProvider, configOverride: Partial = {}, ): Promise { - const testDbName = `unleashtestdb_${uuidv4().replace(/-/g, '')}`; + const testDbName = `${testDbPrefix}${uuidv4().replace(/-/g, '')}`; const useDbTemplate = (configOverride.dbInitMethod ?? 'template') === 'template'; const testDBTemplateName = process.env.TEST_DB_TEMPLATE_NAME;