summaryrefslogtreecommitdiffstats
path: root/tests/manual/wasm/shared/testrunner.js
blob: 197e3bfa6d2a08ce427c6e328f12e1390862c810 (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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only

function parseQuery()
{
    const trimmed = window.location.search.substring(1);
    return new Map(
        trimmed.length === 0 ?
            [] :
            trimmed.split('&').map(paramNameAndValue =>
            {
                const [name, value] = paramNameAndValue.split('=');
                return [decodeURIComponent(name), value ? decodeURIComponent(value) : ''];
            }));
}

export class assert
{
    static isFalse(value)
    {
        if (value !== false)
            throw new Error(`Assertion failed, expected to be false, was ${value}`);
    }

    static isTrue(value)
    {
        if (value !== true)
            throw new Error(`Assertion failed, expected to be true, was ${value}`);
    }

    static isUndefined(value)
    {
        if (typeof value !== 'undefined')
            throw new Error(`Assertion failed, expected to be undefined, was ${value}`);
    }

    static isNotUndefined(value)
    {
        if (typeof value === 'undefined')
            throw new Error(`Assertion failed, expected not to be undefined, was ${value}`);
    }

    static equal(expected, actual)
    {
        if (expected !== actual)
            throw new Error(`Assertion failed, expected to be ${expected}, was ${actual}`);
    }

    static notEqual(expected, actual)
    {
        if (expected === actual)
            throw new Error(`Assertion failed, expected not to be ${expected}`);
    }
}

export class Mock extends Function
{
    #calls = [];

    constructor()
    {
        super()
        const proxy = new Proxy(this, {
            apply: (target, _, args) => target.onCall(...args)
        });
        proxy.thisMock = this;

        return proxy;
    }

    get calls()
    {
        return this.thisMock.#calls;
    }

    onCall(...args)
    {
        this.#calls.push(args);
    }
}

function output(message)
{
    const outputLine = document.createElement('div');
    outputLine.style.fontFamily = 'monospace';
    outputLine.innerText = message;

    document.body.appendChild(outputLine);

    console.log(message);
}

export class TestRunner
{
    #testClassInstance
    #timeoutSeconds

    constructor(testClassInstance, config)
    {
        this.#testClassInstance = testClassInstance;
        this.#timeoutSeconds = config?.timeoutSeconds ?? 2;
    }

    async run(testCase)
    {
        const prototype = Object.getPrototypeOf(this.#testClassInstance);
        try {
            output(`Running ${testCase}`);
            if (!prototype.hasOwnProperty(testCase))
                throw new Error(`No such testcase ${testCase}`);

            if (prototype.beforeEach) {
                await prototype.beforeEach.apply(this.#testClassInstance);
            }

            await new Promise((resolve, reject) =>
            {
                let rejected = false;
                const timeout = window.setTimeout(() =>
                {
                    rejected = true;
                    reject(new Error(`Timeout after ${this.#timeoutSeconds} seconds`));
                }, this.#timeoutSeconds * 1000);
                prototype[testCase].apply(this.#testClassInstance).then(() =>
                {
                    if (!rejected) {
                        window.clearTimeout(timeout);
                        output(`✅ Test passed ${testCase}`);
                        resolve();
                    }
                }).catch(reject);
            });
        } catch (e) {
            output(`❌ Failed ${testCase}: exception ${e} ${e.stack}`);
        } finally {
            if (prototype.afterEach) {
                await prototype.afterEach.apply(this.#testClassInstance);
            }
        }
    }

    async runAll()
    {
        const query = parseQuery();
        const testFilter = query.has('testfilter') ? new RegExp(query.get('testfilter')) : undefined;

        const SPECIAL_FUNCTIONS =
            ['beforeEach', 'afterEach', 'beforeAll', 'afterAll', 'constructor'];
        const prototype = Object.getPrototypeOf(this.#testClassInstance);
        const testFunctions =
            Object.getOwnPropertyNames(prototype).filter(
                entry => SPECIAL_FUNCTIONS.indexOf(entry) === -1 && (!testFilter || entry.match(testFilter)));

        if (prototype.beforeAll)
            await prototype.beforeAll.apply(this.#testClassInstance);
        for (const fn of testFunctions)
            await this.run(fn);
        if (prototype.afterAll)
            await prototype.afterAll.apply(this.#testClassInstance);
    }
}