From 549f2e94b2fbf6b3cb9e3497d16e34ba3a32fb1f Mon Sep 17 00:00:00 2001 From: Iain Sproat <68657+iainsproat@users.noreply.github.com> Date: Fri, 6 Sep 2024 12:18:47 +0100 Subject: [PATCH] Allow database name to be passed in to acceptance test --- .../workflows/preview-service-acceptance.yml | 1 + .../preview-service/tests/hooks/globalSetup.ts | 17 ++++++++++++----- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/.github/workflows/preview-service-acceptance.yml b/.github/workflows/preview-service-acceptance.yml index 4b79fa4275..7ad7bca53f 100644 --- a/.github/workflows/preview-service-acceptance.yml +++ b/.github/workflows/preview-service-acceptance.yml @@ -103,6 +103,7 @@ jobs: run: yarn test:acceptance env: NODE_ENV: test + TEST_DB: preview_service_test # note that the host is localhost, but the port is the port mapped to the postgres service PG_CONNECTION_STRING: postgres://preview_service_test:preview_service_test@localhost:5432/preview_service_test OUTPUT_FILE_PATH: /tmp/preview-service-output.png diff --git a/packages/preview-service/tests/hooks/globalSetup.ts b/packages/preview-service/tests/hooks/globalSetup.ts index 205de35e15..775e87ff4a 100644 --- a/packages/preview-service/tests/hooks/globalSetup.ts +++ b/packages/preview-service/tests/hooks/globalSetup.ts @@ -15,10 +15,12 @@ declare module 'vitest' { } } -const dbName = `preview_service_${cryptoRandomString({ - length: 10, - type: 'alphanumeric' -})}`.toLocaleLowerCase() //postgres will automatically lower case new db names +const dbName = + process.env.TEST_DB || // in the acceptance tests we need to use a database name that is known prior to the test running + `preview_service_${cryptoRandomString({ + length: 10, + type: 'alphanumeric' + })}`.toLocaleLowerCase() //postgres will automatically lower case new db names /** * Global setup hook @@ -28,12 +30,17 @@ const dbName = `preview_service_${cryptoRandomString({ export async function setup({ provide }: GlobalSetupContext) { logger.info('🏃🏻‍♀️‍➡️ Running vitest setup global hook') const superUserDbClient = getTestDb() - await superUserDbClient.raw(`CREATE DATABASE ${dbName} + const dbAlreadyExists = await superUserDbClient + .select('pg_database') + .where('datname', dbName) + if (!dbAlreadyExists.length) { + await superUserDbClient.raw(`CREATE DATABASE ${dbName} WITH OWNER = preview_service_test ENCODING = 'UTF8' TABLESPACE = pg_default CONNECTION LIMIT = -1;`) + } await superUserDbClient.destroy() // need to explicitly close the connection in clients to prevent hanging tests // this provides the dbName to all tests, and can be accessed via inject('dbName'). NB: The test extensions already implement this, so use a test extension.