-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
416 lines (353 loc) · 12.8 KB
/
index.js
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
/*! @license
* Karma Local WebDriver Launcher
* Copyright 2022 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview
*
* Launches local web browsers using WebDriver, to enable screenshots and other
* advanced tests to be executed in-browser. If you don't need WebDriver to
* enable some test scenario in Karma, you can just use typical local browser
* launchers.
*
* Supports Chrome, Firefox, and Safari.
*/
const fs = require('fs');
const os = require('os');
const path = require('path');
const wd = require('wd');
const which = require('which');
const _ = require('lodash');
const {installWebDrivers} = require('webdriver-installer');
const DRIVER_CACHE = path.join(os.homedir(), '.webdriver-installer-cache');
fs.mkdirSync(DRIVER_CACHE, {recursive: true});
// Delay on startup to allow the WebDriver server to start.
const WEBDRIVER_STARTUP_DELAY_SECONDS = 2;
// If it takes longer than this to close our WebDriver session, give up.
const CLOSE_WEBDRIVER_SESSION_TIMEOUT_SECONDS = 5;
let driversInstalledPromise = null;
// Map nodejs OS names to Selenium platform names.
const PLATFORM_MAP = {
'darwin': 'Mac',
'win32': 'Windows',
'linux': 'Linux',
};
function mergeOptions(base, custom) {
// _.mergeWith modifies the first argument, so clone the base structure first.
const output = _.cloneDeep(base);
return _.mergeWith(output, custom,
// Concatenate arrays instead of overwriting them.
(objValue, srcValue) => {
if (Array.isArray(objValue)) {
return objValue.concat(srcValue);
}
});
}
// Subclasses must define these static members:
// - BROWSER_NAME: browser name as presented to WebDriver
// - LAUNCHER_NAME: launcher name as presented to Karma
// - EXTRA_WEBDRIVER_SPECS: an object containing any extra WebDriver specs
// - getDriverArgs(port): take port as string, return driver command arguments
const LocalWebDriverBase = function(baseBrowserDecorator, args, logger) {
baseBrowserDecorator(this);
this.name = `${this.constructor.LAUNCHER_NAME} via WebDriver`;
const log = logger.create(this.name);
this.browserName = this.constructor.BROWSER_NAME;
const port = Math.floor((Math.random() * 1000)) + 4000;
// Called by the base class to get arguments to pass to the driver command.
this._getOptions = () => this.constructor.getDriverArgs(port.toString());
const config = {
protocol: 'http:',
hostname: '127.0.0.1',
port,
pathname: '/'
};
log.debug('config:', JSON.stringify(config));
const extraSpecs = mergeOptions(
this.constructor.EXTRA_WEBDRIVER_SPECS,
args.config);
log.debug('extraSpecs:', extraSpecs);
// These names ("browser" and "spec") are needed for compatibility with
// karma-webdriver-launcher.
this.browser = wd.remote(config);
this.spec = {
browserName: this.browserName.toLowerCase(),
platform: PLATFORM_MAP[os.platform()],
// This is necessary for safaridriver:
allowW3C: true,
// This allows extra configuration for headless variants:
...extraSpecs,
};
this.browser.on('status', (info) => {
log.debug('Status: ' + info);
});
this.browser.on('command', (eventType, command, response) => {
log.debug('[command] ' + eventType + ' ' + command + ' ' + (response || ''));
});
this.browser.on('http', (meth, path, data) => {
log.debug('[http] ' + meth + ' ' + path + ' ' + (data || ''));
});
this.on('start', async (url) => {
await delay(WEBDRIVER_STARTUP_DELAY_SECONDS);
this.browser.init(this.spec, (error) => {
if (error) {
log.error(`Could not connect to ${this.browserName} WebDriver`);
log.error(error);
} else {
log.debug(`Connected to ${this.browserName} WebDriver`);
log.debug('Connecting to ' + url);
this.browser.get(url);
}
});
});
// The base decorators will listen for the 'kill' event to close the process
// for the driver. Once that happens, we can no longer stop the webdriver
// connection and close the open browser window. There is no way to register
// a listener ahead of the base class's, so to shut down the browser
// properly, we need to reimplement all the methods that could trigger a
// 'kill' event.
this.kill = async () => {
this.state = 'BEING_KILLED';
await this.stopWebdriver_();
};
this.forceKillOperation_ = null;
this.forceKill = async () => {
// Don't nest force-kill operations. If forceKill() was already called,
// just return the same Promise again.
if (this.state == 'BEING_FORCE_KILLED') {
return this.forceKillOperation_;
}
this.state = 'BEING_FORCE_KILLED';
this.forceKillOperation_ = this.stopWebdriver_();
await this.forceKillOperation_;
};
const originalStart = this.start;
let previousUrl = null;
this.start = async (url) => {
// If we haven't installed drivers yet in this session, start the
// installation process now.
if (!driversInstalledPromise) {
// TODO: Tie logging for this to karma log settings.
driversInstalledPromise =
installWebDrivers(DRIVER_CACHE, /* logging= */ false);
}
// Wait for drivers to be installed for all local browsers.
await driversInstalledPromise;
previousUrl = url;
originalStart.call(this, url);
};
const originalOnProcessExit = this._onProcessExit;
this._onProcessExit = (code, signal, errorOutput) => {
originalOnProcessExit.call(this, code, signal, errorOutput);
if (code == -1 && errorOutput.includes('Can not find')) {
// Failed to find the driver. Is it in the cache? Debug to help the
// user find out what's wrong.
try {
const contents = fs.readdirSync(DRIVER_CACHE);
log.error(
`Failed to find driver for ${this.browserName}`);
log.error(
`${DRIVER_CACHE} contains:`, JSON.stringify(contents, null, ' '));
} catch (error) {}
}
};
this.restart = async () => {
if (this.state == 'BEING_FORCE_KILLED') {
return;
}
this.state = 'RESTARTING';
await this.stopWebdriver_();
if (this.state != 'BEING_FORCE_KILLED') {
log.debug(`Restarting ${this.name}`)
this.start(previousUrl);
}
};
this.stopWebdriver_ = async () => {
if (this.browser) {
// If it takes too long to close the session, give up and move on.
await Promise.race([
delay(CLOSE_WEBDRIVER_SESSION_TIMEOUT_SECONDS),
new Promise(resolve => this.browser.quit(resolve)),
]);
}
// Now that the driver connection and browser are closed (or have timed
// out), emit the signal that shuts down the driver executable.
await this.emitAsync('kill');
this.state = 'FINISHED';
};
}
async function delay(seconds) {
await new Promise((resolve) => setTimeout(resolve, seconds * 1000));
}
// Generate a subclass of LocalWebDriverBase and return it.
function generateSubclass(
browserName, launcherName, driverCommand, getDriverArgs,
extraWebDriverSpecs={}) {
if (driverCommand[0] == '/') {
// Absolute path. Keep it.
} else {
// File name. Assume it will be found in our driver cache.
driverCommand = path.join(DRIVER_CACHE, driverCommand);
}
// Karma will not use "new" to construct our class, so it can't be a true ES6
// class. Use the old function syntax instead.
const subclass = function(baseBrowserDecorator, args, logger) {
LocalWebDriverBase.call(this, baseBrowserDecorator, args, logger);
};
// These are needed by our base class, LocalWebDriverBase.
subclass.BROWSER_NAME = browserName;
subclass.LAUNCHER_NAME = launcherName;
subclass.EXTRA_WEBDRIVER_SPECS = extraWebDriverSpecs;
subclass.getDriverArgs = getDriverArgs;
// These are needed by Karma's base class for command-based launchers, and
// will also facilitate auto-detection of available browsers by Shaka Player:
const anyPathSeparator = /[\/\\]/; // Windows (backslash) or POSIX (slash)
const driverCommandName = driverCommand.split(anyPathSeparator).pop();
subclass.prototype.ENV_CMD =
driverCommandName.toUpperCase().replace('-', '_') + '_PATH';
subclass.prototype.DEFAULT_CMD = {
linux: driverCommand,
darwin: driverCommand,
win32: driverCommand + '.exe',
};
// This configures Karma's dependency injection system:
subclass.$inject = ['baseBrowserDecorator', 'args', 'logger'];
return subclass;
}
function generateSafariDriver(name, device = 'mac', simulator = false) {
const config = device == 'mac' ? {} : {
platformName: 'iOS',
'safari:deviceType': device,
'safari:useSimulator': simulator,
};
return generateSubclass('Safari', name,
'/usr/bin/safaridriver',
(port) => ['--port=' + port],
config);
}
const LocalWebDriverChrome = generateSubclass(
'Chrome', 'Chrome',
'chromedriver',
(port) => ['--port=' + port]);
const LocalWebDriverChromeHeadless = generateSubclass(
'Chrome', 'ChromeHeadless',
'chromedriver',
(port) => ['--port=' + port],
{
'goog:chromeOptions': {
args: [
'--headless',
'--no-sandbox',
'--disable-gpu',
'--disable-dev-shm-usage',
],
},
});
// TODO: Add Chrome on android?
// If a binary is found with the name "microsoft-edge" in the PATH, specify
// that explicitly. This works around the following edgedriver bug:
// https://github.com/MicrosoftEdge/EdgeWebDriver/issues/102#issuecomment-1710724173
const edgeOptions = {};
let edgeBinary = which.sync('microsoft-edge', {nothrow: true});
if (!edgeBinary) {
// Since v120 or v121, msedgedriver always fails if you do not specify the
// Edge binary path. Assume some platform-specific defaults. Only use these
// paths if they exist.
switch (os.platform()) {
case 'darwin':
edgeBinary = '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge';
break;
case 'win32':
edgeBinary = 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe';
break;
case 'linux':
edgeBinary = '/opt/microsoft/msedge/microsoft-edge';
break;
}
// If that platform-specific binary doesn't exist, don't try to use it.
if (edgeBinary && !fs.existsSync(edgeBinary)) {
edgeBinary = null;
}
}
if (edgeBinary) {
edgeOptions['ms:edgeOptions'] = {
binary: edgeBinary,
};
}
const LocalWebDriverEdge = generateSubclass(
'MSEdge', 'MSEdge',
'msedgedriver',
(port) => ['--port=' + port],
edgeOptions);
const LocalWebDriverEdgeHeadless = generateSubclass(
'MSEdge', 'MSEdgeHeadless',
'msedgedriver',
(port) => ['--port=' + port],
mergeOptions(edgeOptions, {
'ms:edgeOptions': {
args: [
'--headless',
'--disable-gpu',
],
},
}));
const LocalWebDriverFirefox = generateSubclass(
'Firefox', 'Firefox',
'geckodriver',
(port) => ['-p', port],
{
'moz:firefoxOptions': {
prefs: {
'media.eme.enabled': true,
'media.gmp-manager.updateEnabled': true,
},
},
});
const LocalWebDriverFirefoxHeadless = generateSubclass(
'Firefox', 'FirefoxHeadless',
'geckodriver',
(port) => ['-p', port],
{
'moz:firefoxOptions': {
prefs: {
'media.eme.enabled': true,
'media.gmp-manager.updateEnabled': true,
},
args: [
'-headless',
],
},
});
const LocalWebDriverSafari = generateSafariDriver('Safari');
const LocalWebDriverSafariIOS = generateSafariDriver('SafariIOS', 'iPhone');
const LocalWebDriverSafariIOSSim =
generateSafariDriver('SafariIOSSim', 'iPhone', true);
const LocalWebDriverSafariIPadOS =
generateSafariDriver('SafariIPadOS', 'iPad');
const LocalWebDriverSafariIPadOSSim =
generateSafariDriver('SafariIPadOSSim', 'iPad', true);
const LocalWebDriverSafariTP = generateSubclass(
'Safari Technology Preview', 'Safari Technology Preview',
'/Applications/Safari Technology Preview.app/Contents/MacOS/safaridriver',
(port) => ['-p', port]);
module.exports = {
'launcher:Chrome': ['type', LocalWebDriverChrome],
'launcher:ChromeHeadless': ['type', LocalWebDriverChromeHeadless],
'launcher:Edge': ['type', LocalWebDriverEdge],
'launcher:EdgeHeadless': ['type', LocalWebDriverEdgeHeadless],
'launcher:Firefox': ['type', LocalWebDriverFirefox],
'launcher:FirefoxHeadless': ['type', LocalWebDriverFirefoxHeadless],
};
// Safari is only supported on Mac.
if (os.platform() == 'darwin') {
module.exports['launcher:Safari'] = ['type', LocalWebDriverSafari];
module.exports['launcher:SafariIOS'] = ['type', LocalWebDriverSafariIOS];
module.exports['launcher:SafariIOSSim'] =
['type', LocalWebDriverSafariIOSSim];
module.exports['launcher:SafariIPadOS'] =
['type', LocalWebDriverSafariIPadOS];
module.exports['launcher:SafariIPadOSSim'] =
['type', LocalWebDriverSafariIPadOSSim];
module.exports['launcher:SafariTP'] = ['type', LocalWebDriverSafariTP];
}