summaryrefslogtreecommitdiffhomepage
path: root/gui/standalone-tests.ts
blob: c2572311d47efb66c351765e97d9097f8fb3e510 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import { spawn } from 'child_process';
import fs from 'fs';
import os from 'os';
import path from 'path';

// This file is bundled into a standalone executable able to run e2e tests against an installed
// version of the app. This file is the entrypoint in the executable and extracts the required
// assets and performs the tests. More info in /gui/README.md.

const tmpDir = path.join(os.tmpdir(), 'mullvad-standalone-tests');

async function main() {
  extract();
  const code = await runTests();

  removeTmpDir();
  process.exit(code);
}

function extract() {
  const rootDir = path.join(__dirname, '..');
  const nodeModulesDir = path.join(rootDir, 'node_modules');
  const srcDir = path.join(rootDir, 'build', 'src');
  const testDir = path.join(rootDir, 'build', 'test');

  // Remove old directory if already existing and create new clean one
  removeTmpDir();
  fs.mkdirSync(tmpDir);

  extractDirectory(srcDir);
  extractDirectory(testDir);
  extractDirectory(nodeModulesDir);
}

function extractDirectory(source: string) {
  copyRecursively(source, path.join(tmpDir, path.basename(source)));
}

function copyRecursively(source: string, target: string) {
  if (fs.statSync(source).isDirectory()) {
    fs.mkdirSync(target);
    fs.readdirSync(source, { encoding: 'utf8' }).forEach((item) =>
      copyRecursively(path.join(source, item), path.join(target, item)),
    );
  } else {
    fs.copyFileSync(source, target);
  }
}

function runTests(): Promise<number> {
  const nodeBin = process.argv[0];
  const playwrightBin = path.join(tmpDir, 'node_modules', '@playwright', 'test', 'cli.js');
  const configPath = path.join(tmpDir, 'test', 'e2e', 'installed', 'playwright.config.js');

  return new Promise((resolve) => {
    // Tests need to be run sequentially since they interact with the same daemon instance.
    // Arguments are forwarded to playwright to make it possible to run specific tests.
    const args = [playwrightBin, 'test', '-x', '-c', configPath, ...process.argv.slice(2)];
    const proc = spawn(nodeBin, args, { cwd: tmpDir });

    proc.stdout.on('data', (data) => console.log(data.toString()));
    proc.stderr.on('data', (data) => console.error(data.toString()));
    proc.on('close', (code, signal) => {
      if (signal) {
        console.log('Received signal:', signal);
      }

      resolve(code ?? (signal ? 1 : 0));
    });
  });
}

function removeTmpDir() {
  if (fs.existsSync(tmpDir)) {
    try {
      fs.rmSync(tmpDir, { recursive: true });
    } catch (e) {
      const error = e as Error;
      console.error('Failed to remove tmp dir:', error.message);
    }
  }
}

void main();