Просмотр исходного кода

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.
Michael Bromley 1 год назад
Родитель
Сommit
72befaa65d
1 измененных файлов с 41 добавлено и 18 удалено
  1. 41 18
      e2e-common/test-config.ts

+ 41 - 18
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) {