From 72befaa65ddffb8f0c5ca657594dae87242ba8f2 Mon Sep 17 00:00:00 2001 From: Michael Bromley Date: Tue, 17 Dec 2024 14:24:52 +0100 Subject: [PATCH] test: Improve port assignment in e2e tests Relates to #3247. This commit implements the approach of deriving a unique port number based on the index of the current test file in its parent directory. --- e2e-common/test-config.ts | 59 +++++++++++++++++++++++++++------------ 1 file changed, 41 insertions(+), 18 deletions(-) diff --git a/e2e-common/test-config.ts b/e2e-common/test-config.ts index 06f594a32a..b9bfc47d99 100644 --- a/e2e-common/test-config.ts +++ b/e2e-common/test-config.ts @@ -9,7 +9,6 @@ import { import fs from 'fs-extra'; import path from 'path'; import { DataSourceOptions } from 'typeorm'; -import { fileURLToPath } from 'url'; import { getPackageDir } from './get-package-dir'; @@ -36,25 +35,10 @@ registerInitializer('mysql', new MysqlInitializer()); registerInitializer('mariadb', new MysqlInitializer()); export const testConfig = () => { - // @ts-ignore - const portsFile = fileURLToPath(new URL('ports.json', import.meta.url)); - fs.ensureFileSync(portsFile); - let usedPorts: number[]; - try { - usedPorts = fs.readJSONSync(portsFile) ?? [3010]; - } catch (e: any) { - usedPorts = [3010]; - } - const nextPort = Math.max(...usedPorts) + 1; - usedPorts.push(nextPort); - if (100 < usedPorts.length) { - // reset the used ports after it gets 100 entries long - usedPorts = [3010]; - } - fs.writeJSONSync(portsFile, usedPorts); + const index = getIndexOfTestFileInParentDir(); return mergeConfig(defaultTestConfig, { apiOptions: { - port: nextPort, + port: 3010 + index, }, importExportOptions: { importAssetsDir: path.join(packageDir, 'fixtures/assets'), @@ -63,6 +47,45 @@ export const testConfig = () => { }); }; +/** + * Returns the index of the test file in the parent directory. + * This is used to ensure each test file has a unique + * port number. + */ +function getIndexOfTestFileInParentDir() { + const testFilePath = getCallerFilename(2); + const parentDir = path.dirname(testFilePath); + const files = fs.readdirSync(parentDir); + const index = files.indexOf(path.basename(testFilePath)); + return index; +} + +/** + * Returns the full path to the file which called the function. + * @param depth + */ +function getCallerFilename(depth: number): string { + let stack: any; + let file: any; + let frame: any; + + const pst = Error.prepareStackTrace; + Error.prepareStackTrace = (_, _stack) => { + Error.prepareStackTrace = pst; + return _stack; + }; + + stack = new Error().stack; + stack = stack.slice(depth + 1); + + do { + frame = stack.shift(); + file = frame && frame.getFileName(); + } while (stack.length && file === 'module.js'); + + return file; +} + function getDbConfig(): DataSourceOptions { const dbType = process.env.DB || 'sqljs'; switch (dbType) {