aboutsummaryrefslogtreecommitdiff
path: root/test/integ-test/frontend_smoke.js
blob: 3810166fb975d89aa1f981b5d564a677f18ccb58 (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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
#!/usr/bin/env node

/*
  Copyright 2018 ThousandEyes Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

'use strict';

const fs = require('fs');
const http = require('http');
const os = require('os');
const path = require('path');
const { spawn } = require('child_process');

const apiURL = process.argv[2] || 'http://localhost:18888';
const chromiumBin = process.env.CHROMIUM_BIN || 'chromium';
const smokeMac = '02:00:00:00:00:42';
const smokeMacPath = smokeMac.replace(/:/g, '-');

class CDPClient {
    constructor(webSocketURL) {
        this.nextID = 1;
        this.pending = new Map();
        this.handlers = new Map();
        this.ws = new WebSocket(webSocketURL);

        this.opened = new Promise((resolve, reject) => {
            this.ws.addEventListener('open', resolve, { once: true });
            this.ws.addEventListener('error', reject, { once: true });
        });

        this.ws.addEventListener('message', (event) => {
            const message = JSON.parse(event.data);
            if (message.id && this.pending.has(message.id)) {
                const pending = this.pending.get(message.id);
                this.pending.delete(message.id);
                if (message.error) {
                    pending.reject(new Error(message.error.message));
                } else {
                    pending.resolve(message.result || {});
                }
                return;
            }

            const handlers = this.handlers.get(message.method) || [];
            handlers.forEach((handler) => handler(message));
        });
    }

    async send(method, params, sessionID) {
        await this.opened;

        const id = this.nextID++;
        const message = {
            id: id,
            method: method,
            params: params || {},
        };

        if (sessionID) {
            message.sessionId = sessionID;
        }

        return new Promise((resolve, reject) => {
            this.pending.set(id, { resolve: resolve, reject: reject });
            this.ws.send(JSON.stringify(message));
        });
    }

    on(method, handler) {
        if (!this.handlers.has(method)) {
            this.handlers.set(method, []);
        }
        this.handlers.get(method).push(handler);
    }

    close() {
        this.ws.close();
    }
}

function requestURL(url) {
    return new Promise((resolve, reject) => {
        http.get(url, (response) => {
            let body = '';
            response.setEncoding('utf8');
            response.on('data', (chunk) => {
                body += chunk;
            });
            response.on('end', () => {
                if (response.statusCode < 200 || response.statusCode >= 300) {
                    reject(new Error('GET ' + url + ' failed with ' + response.statusCode));
                    return;
                }
                resolve(body);
            });
        }).on('error', reject);
    });
}

async function requestJSON(url) {
    return JSON.parse(await requestURL(url));
}

async function waitFor(description, check, timeoutMS = 5000) {
    const deadline = Date.now() + timeoutMS;

    while (Date.now() < deadline) {
        if (await check()) {
            return;
        }
        await new Promise((resolve) => setTimeout(resolve, 100));
    }

    throw new Error('Timed out waiting for ' + description);
}

async function waitForDevToolsURL(chromium) {
    let stderr = '';

    return new Promise((resolve, reject) => {
        const timeout = setTimeout(() => {
            reject(new Error('Timed out waiting for Chromium DevTools URL. stderr: ' + stderr));
        }, 10000);

        chromium.stderr.on('data', (chunk) => {
            stderr += chunk.toString();
            const match = stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/);
            if (match) {
                clearTimeout(timeout);
                resolve(match[1]);
            }
        });

        chromium.once('exit', (code) => {
            clearTimeout(timeout);
            reject(new Error('Chromium exited before DevTools was ready with code ' + code + '. stderr: ' + stderr));
        });
    });
}

function stopProcess(child) {
    return new Promise((resolve) => {
        if (child.exitCode !== null || child.signalCode !== null) {
            resolve();
            return;
        }

        const timeout = setTimeout(() => {
            child.kill('SIGKILL');
        }, 5000);

        child.once('exit', () => {
            clearTimeout(timeout);
            resolve();
        });

        child.kill('SIGTERM');
    });
}

function formatExceptionDetails(details) {
    const parts = [details.text || 'Unhandled browser exception'];

    if (details.exception) {
        parts.push(details.exception.description || details.exception.value || '');
    }

    if (details.stackTrace && details.stackTrace.callFrames) {
        details.stackTrace.callFrames.forEach((frame) => {
            parts.push(frame.url + ':' + frame.lineNumber + ':' + frame.columnNumber);
        });
    }

    return parts.filter(Boolean).join(' ');
}

async function evaluate(cdp, sessionID, expression) {
    const result = await cdp.send('Runtime.evaluate', {
        expression: expression,
        awaitPromise: true,
        returnByValue: true,
    }, sessionID);

    if (result.exceptionDetails) {
        const exception = result.exceptionDetails.exception;
        throw new Error(
            (exception && (exception.description || exception.value)) ||
            result.exceptionDetails.text ||
            'Runtime evaluation failed'
        );
    }

    return result.result.value;
}

async function waitForPage(cdp, sessionID, expression, description) {
    await waitFor(description, async () => {
        return Boolean(await evaluate(cdp, sessionID, expression));
    });
}

async function run() {
    const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'shoelaces-chromium-'));
    const chromium = spawn(chromiumBin, [
        '--headless=new',
        '--disable-gpu',
        '--disable-dev-shm-usage',
        '--disable-breakpad',
        '--disable-component-extensions-with-background-pages',
        '--disable-crash-reporter',
        '--disable-crashpad',
        '--disable-extensions',
        '--no-first-run',
        '--no-default-browser-check',
        '--no-crash-upload',
        '--no-sandbox',
        '--remote-debugging-port=0',
        '--user-data-dir=' + userDataDir,
        'about:blank',
    ]);

    let cdp;

    try {
        const browserWS = await waitForDevToolsURL(chromium);
        cdp = new CDPClient(browserWS);
        await cdp.opened;

        const target = await cdp.send('Target.createTarget', { url: 'about:blank' });
        const attached = await cdp.send('Target.attachToTarget', {
            targetId: target.targetId,
            flatten: true,
        });
        const sessionID = attached.sessionId;
        const pageErrors = [];

        cdp.on('Runtime.exceptionThrown', (message) => {
            if (message.sessionId === sessionID) {
                pageErrors.push(formatExceptionDetails(message.params.exceptionDetails));
            }
        });
        cdp.on('Runtime.consoleAPICalled', (message) => {
            if (message.sessionId === sessionID && message.params.type === 'error') {
                pageErrors.push(message.params.args.map((arg) => arg.value || arg.description).join(' '));
            }
        });

        await cdp.send('Runtime.enable', {}, sessionID);
        await cdp.send('Page.enable', {}, sessionID);

        await requestURL(apiURL + '/poll/1/' + smokeMacPath + '?host=frontend-smoke');
        await cdp.send('Page.navigate', { url: apiURL + '/' }, sessionID);

        await waitForPage(cdp, sessionID, 'document.readyState === "complete"', 'home page load');
        await waitForPage(
            cdp,
            sessionID,
            'Boolean(document.querySelector("#mac option[value=\\"' + smokeMac + '\\"]"))',
            'unknown server option'
        );

        const homeState = await evaluate(cdp, sessionID, `(() => {
            const systems = document.getElementById('systems');
            const loading = document.getElementById('loading');
            return {
                systemsDisplay: systems ? getComputedStyle(systems).display : null,
                loadingDisplay: loading ? getComputedStyle(loading).display : null,
                macText: document.querySelector('#mac option[value="${smokeMac}"]')?.textContent || '',
            };
        })()`);

        if (homeState.systemsDisplay === 'none') {
            throw new Error('Server form did not become visible');
        }
        if (homeState.loadingDisplay !== 'none') {
            throw new Error('Loading panel did not become hidden');
        }
        if (!homeState.macText.includes('frontend-smoke')) {
            throw new Error('Unknown server option did not include hostname: ' + homeState.macText);
        }

        await evaluate(cdp, sessionID, `(() => {
            const mac = document.getElementById('mac');
            const target = document.getElementById('target');
            mac.value = '${smokeMac}';
            target.value = 'coreos.ipxe';
            target.dispatchEvent(new Event('change', { bubbles: true }));
            return true;
        })()`);

        await waitForPage(
            cdp,
            sessionID,
            'document.querySelectorAll(".params-container input[type=text]").length >= 2',
            'template parameter inputs'
        );

        const paramNames = await evaluate(cdp, sessionID, `Array.from(
            document.querySelectorAll('.params-container input[type=text]'),
            (input) => input.name
        ).sort()`);

        if (JSON.stringify(paramNames) !== JSON.stringify(['cloudconfig', 'version'])) {
            throw new Error('Unexpected parameter inputs: ' + JSON.stringify(paramNames));
        }

        const submitState = await evaluate(cdp, sessionID, `(async () => {
            const form = document.getElementById('systems');
            document.querySelector('input[name="cloudconfig"]').value = 'virtual';
            document.querySelector('input[name="version"]').value = '777.0';
            const response = await fetch(form.action, {
                method: form.method,
                body: new URLSearchParams(new FormData(form)),
            });
            return {
                ok: response.ok,
                status: response.status,
            };
        })()`);

        if (!submitState.ok) {
            throw new Error('Manual selection form POST failed with ' + submitState.status);
        }

        await waitFor('manual selection to leave ajax server list', async () => {
            const servers = await requestJSON(apiURL + '/ajax/servers');
            return !servers.some((server) => server.Mac === smokeMac);
        });

        await cdp.send('Page.navigate', { url: apiURL + '/events' }, sessionID);
        await waitForPage(cdp, sessionID, 'document.readyState === "complete"', 'events page load');
        await waitForPage(
            cdp,
            sessionID,
            'document.querySelector(".event-log .card") && document.body.textContent.includes("' + smokeMac + '")',
            'event history card'
        );

        const eventText = await evaluate(cdp, sessionID, 'document.querySelector(".event-log").textContent');
        if (!eventText.includes('A user selected coreos.ipxe')) {
            throw new Error('Event history did not render user selection: ' + eventText);
        }

        if (pageErrors.length > 0) {
            throw new Error('Browser console errors: ' + pageErrors.join('; '));
        }
    } finally {
        if (cdp) {
            cdp.close();
        }
        await stopProcess(chromium);
        fs.rmSync(userDataDir, { recursive: true, force: true });
    }
}

run().catch((error) => {
    console.error(error.stack || error.message);
    process.exit(1);
});
nihil fit ex nihilo