Skip to content

Commit 9f0155e

Browse files
chore: cleanup old test dbs (#9539)
This cleans up old dbs before running a new test
1 parent f9c1529 commit 9f0155e

File tree

2 files changed

+14
-7
lines changed

2 files changed

+14
-7
lines changed

scripts/jest-setup.ts

+11-6
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,26 @@
11
import { Client, type ClientConfig } from 'pg';
22
import { migrateDb } from '../src/migrator';
33
import { getDbConfig } from '../src/test/e2e/helpers/database-config';
4+
import { testDbPrefix } from '../src/test/e2e/helpers/database-init';
45

56
let initializationPromise: Promise<void> | null = null;
7+
68
const initializeTemplateDb = (db: ClientConfig): Promise<void> => {
79
if (!initializationPromise) {
810
initializationPromise = (async () => {
911
const testDBTemplateName = process.env.TEST_DB_TEMPLATE_NAME;
12+
1013
const client = new Client(db);
1114
await client.connect();
1215
console.log(`Initializing template database ${testDBTemplateName}`);
13-
// code to clean up, but only on next run, we could do it at tear down... but is it really needed?
14-
// const result = await client.query(`select datname from pg_database where datname like 'unleashtestdb_%';`)
15-
// result.rows.forEach(async (row: any) => {
16-
// console.log(`Dropping test database ${row.datname}`);
17-
// await client.query(`DROP DATABASE ${row.datname}`);
18-
// });
16+
// first clean up databases from previous runs
17+
const result = await client.query(
18+
`select datname from pg_database where datname like '${testDbPrefix}%';`,
19+
);
20+
result.rows.forEach(async (row: any) => {
21+
console.log(`Dropping test database ${row.datname}`);
22+
await client.query(`DROP DATABASE ${row.datname}`);
23+
});
1924
await client.query(`DROP DATABASE IF EXISTS ${testDBTemplateName}`);
2025
await client.query(`CREATE DATABASE ${testDBTemplateName}`);
2126
await client.end();

src/test/e2e/helpers/database-init.ts

+3-1
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ import { v4 as uuidv4 } from 'uuid';
2424
// because of db-migrate bug (https://github.com/Unleash/unleash/issues/171)
2525
process.setMaxListeners(0);
2626

27+
export const testDbPrefix = 'unleashtestdb_';
28+
2729
async function getDefaultEnvRolePermissions(knex) {
2830
return knex.table('role_permission').whereIn('environment', ['default']);
2931
}
@@ -108,7 +110,7 @@ export default async function init(
108110
getLogger: LogProvider = noLoggerProvider,
109111
configOverride: Partial<IUnleashOptions & DBTestOptions> = {},
110112
): Promise<ITestDb> {
111-
const testDbName = `unleashtestdb_${uuidv4().replace(/-/g, '')}`;
113+
const testDbName = `${testDbPrefix}${uuidv4().replace(/-/g, '')}`;
112114
const useDbTemplate =
113115
(configOverride.dbInitMethod ?? 'template') === 'template';
114116
const testDBTemplateName = process.env.TEST_DB_TEMPLATE_NAME;

0 commit comments

Comments
 (0)