Skip to content

Commit

Permalink
test: Improve port assignment in e2e tests
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
michaelbromley committed Dec 17, 2024
1 parent 02bcdba commit 72befaa
Showing 1 changed file with 41 additions and 18 deletions.
59 changes: 41 additions & 18 deletions e2e-common/test-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -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'),
Expand All @@ -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) {
Expand Down

0 comments on commit 72befaa

Please sign in to comment.