/
index.js
504 lines (426 loc) · 14.6 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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
"use strict";
/**
* @module cli
*/
var nopt = require("nopt");
var Configuration = require("./configuration");
var path = require("path");
var glob = require("glob");
var urlUtil = require("url");
var util = require("util");
var url = require("url");
var meta = require("../package-metadata").readPackageSync();
var Hub = require("../hub");
var color = require("./color").codes;
var FeedbackLineReporter = require("./reporter/feedback-line");
var JUnitReporter = require("./reporter/junit");
var hubClient = require("../client");
var getLocalIP = require("../local-ip");
var parseBrowsers = require("./parse-browsers");
var parseCaps = require("./parse-caps");
var Console = require("./console");
var good = "✓";
var bad = "✗";
var processSetupComplete = false;
var parseArgv = exports.parseArgv = function (argv) {
var knownOptions = {
"name": String,
"self-url": url,
"wd-url": url,
"wd-host": String, // 0.2.x back-compat
"wd-port": Number, // 0.2.x back-compat
"browser": [String, Array],
"caps": [String, Array],
"output": ["junit", "feedback"],
"server": Boolean,
"version": Boolean,
"loglevel": ["info", "debug"],
"query": String,
"debug": Boolean,
"port": Number,
"timeout": Number,
"hub": url,
"help" : Boolean
}, shortHands = {
"b": ["--browser"],
"junit": ["--output", "junit"],
"s": ["--server"],
"p": ["--port"],
"v": ["--loglevel", "info"],
"vv": ["--loglevel", "debug"]
},
parsed,
booleanParsed;
parsed = nopt(knownOptions, shortHands, argv);
// Workaround a nopt bug for `hub` option.
// Normally we'd want `hub` to be first parsed
// as a url, then fallback to Boolean.
//
// However, if we specify [url, Boolean] as
// `hub`'s type, nopt will coerce hub aggressively
// into a Boolean.
//
// https://github.com/isaacs/nopt/blob/19736d85ffd3f0eeffc0e8d2ca66c92d0825ebb7/lib/nopt.js#L276
if (!("hub" in parsed)) {
// If parsed.hub is undefined, either
// hub was not specified or was not a URL.
//
// Make a second pass of nopt's cooked args.
// Pass 0 to override the default 2 slice.
booleanParsed = nopt({
"hub": Boolean
}, null, parsed.argv.cooked, 0);
if ("hub" in booleanParsed) {
parsed.hub = booleanParsed.hub;
}
}
return parsed;
};
/**
* The Yeti command-line interface.
*
* @class CLI
* @constructor
* @extends Console
* @param {Object} config Configuration.
* @param {Function} config.exitFn Handler when process exit is requested, 1-arity.
* @param {ReadableStream} config.stdin Readable stream for creating a readline interface.
* @param {WritableStream} config.stdout Writable stream for creating a readline interface.
* @param {WritableStream} config.stderr Writable stream for creating a readline interface.
* @param {process} config.process Process object for setting up exception handlers.
*/
function CLI(config) {
Console.call(this, config);
/**
* For exception handler.
*
* @property process
* @type {process}
*/
this.process = config.process;
}
util.inherits(CLI, Console);
CLI.prototype.setupExceptionHandler = function () {
var self = this;
if (processSetupComplete) {
return;
}
self.process.on("uncaughtException", function (err) {
var message;
if ("string" !== typeof err && err.stack) {
err = err.stack;
}
if (self.stderr.isTTY) {
message = [
color.red(bad + " Whoops!") + " " + err, "",
"If you believe this is a bug in Yeti, please report it.",
" " + color.bold(meta.bugs.url),
" Yeti v" + meta.version,
" Node.js " + process.version
];
} else {
message = [
"Yeti v" + meta.version + " " +
"(Node.js " + process.version +
") Error: " + err,
"Report this bug at " + meta.bugs.url
];
}
self.panic(message.join("\n"));
});
processSetupComplete = true;
};
function getWebDriverConfigurationFromOptions(options) {
var url = urlUtil.parse(options.get("wd-url") || ""),
segments,
user,
pass;
// wd-host, wd-port, wd-user, wd-pass are 0.2.x back-compat options
if (!url.hostname) {
url.hostname = options.get("wd-host");
}
if (!url.port) {
url.port = options.get("wd-port");
}
if (url.auth) {
segments = url.auth.split(":");
user = segments[0];
pass = segments[1];
}
if (!user) {
user = options.get("wd-user");
}
if (!pass) {
pass = options.get("wd-pass");
}
return {
host: url.hostname,
port: url.port,
user: user,
pass: pass
};
}
CLI.prototype.createHub = function createHub(options) {
return new Hub({
loglevel: options.get("loglevel"),
selfUrl: options.get("self-url"),
webdriver: getWebDriverConfigurationFromOptions(options)
});
};
function createReporterForBatch(reporter, batch, console, options) {
var reporter = new reporter({
cli: console,
name: options.get("name"),
batch: batch
});
batch.on("agentResult", reporter.handleAgentResult.bind(reporter));
batch.on("agentScriptError", reporter.handleAgentScriptError.bind(reporter));
batch.on("agentError", reporter.handleAgentError.bind(reporter));
batch.on("agentComplete", reporter.handleAgentComplete.bind(reporter));
batch.on("agentProgress", reporter.updateFeedbackLine.bind(reporter));
batch.on("agentBeat", reporter.handleAgentBeat.bind(reporter));
batch.on("dispatch", reporter.handleDispatch.bind(reporter));
batch.on("complete", reporter.handleComplete.bind(reporter));
batch.on("end", reporter.handleEnd.bind(reporter));
}
function createStderrStatusReporter(cli, batch, options) {
var console = new Console({
exitFn: function () {},
stdin: cli.stdin,
stdout: cli.stderr,
stderr: cli.stderr
});
createReporterForBatch(FeedbackLineReporter, batch, console, options);
}
/**
* @method submitBatch
* @param {Client} client Connected client.
* @param {String} output Reporter output. "junit" selects the JUnitReporter,
* all others FeedbackLineReporter.
* @param {Object} options Options (see `Client.createBatch()`).
* @param {Function} cb Completion callback.
*/
CLI.prototype.submitBatch = function submitBatch(client, options, clientOptions, cb) {
var batch = client.createBatch(clientOptions);
var output = options.get("output");
var reporter = FeedbackLineReporter;
if (output === "junit") {
reporter = JUnitReporter;
createStderrStatusReporter(this, batch, options);
}
createReporterForBatch(reporter, batch, this, options);
};
CLI.prototype.prepareBatch = function prepareBatch(config, cb) {
var self = this,
pattern = config.get("glob"),
unit = "files";
if (pattern && !config.get("files")) {
glob(pattern, function (err, matches) {
if (matches) {
config.set("files", matches);
if (matches.length === 1) {
unit = "file";
}
self.error("Found", matches.length, unit, "to test.");
cb(config);
} else {
self.panic("Glob pattern", pattern, "matched zero files.");
}
});
} else {
cb(config);
}
};
// Used only by runBatch.
function resolveFilesToBasedir(config) {
var files = config.get("files"),
basedir = config.get("basedir"),
cwd = process.cwd(),
absoluteFiles,
relativeFiles;
absoluteFiles = files.map(function (file) {
return path.resolve(cwd, file);
});
relativeFiles = absoluteFiles.map(function (file) {
return path.relative(basedir, file);
});
config.debug("Resolved absoluteFiles:", absoluteFiles,
"to relativeFiles:", relativeFiles);
config.set("files", relativeFiles);
}
CLI.prototype.runBatch = function runBatch(options) {
// XXX put this after var
resolveFilesToBasedir(options);
var self = this,
webdriver = getWebDriverConfigurationFromOptions(options),
files = options.get("files"),
browsers = options.get("browser"),
caps = options.get("caps"),
port = options.get("port"),
url = options.get("hub"),
externalUrl = url,
query = options.get("query"),
debug = options.get("debug"),
batchOptions = {
basedir: options.get("basedir"),
query: query,
timeout: options.get("timeout"),
tests: files
};
if (!browsers) {
browsers = [];
}
browsers = browsers.concat(caps);
function prepareTests(client) {
// In this case, nobody is connected yet.
// If we connected to a server, we would list
// the current agents.
client.getAgents(function (err, agents) {
if (err) {
throw err;
}
agents.forEach(function (agent) {
client.emit("agentConnect", agent);
});
if (agents.length === 0 && browsers.length === 0) {
self.error("Waiting for agents to connect at " + externalUrl);
if (externalUrl !== url) {
self.error("...also available locally at " + url);
}
self.rl.question("When ready, press Enter to begin testing.\n", function () {
self.rl.close();
self.stdin.pause();
self.submitBatch(client, options, batchOptions);
});
} else {
if (browsers.length) {
self.error("Waiting for Hub to launch browsers...");
batchOptions.launchBrowsers = browsers;
batchOptions.webdriver = webdriver;
}
self.submitBatch(client, options, batchOptions);
}
});
client.on("agentConnect", function (agent) {
self.error(" Agent connected:", agent);
});
client.on("agentDisconnect", function (agent) {
self.error(" Agent disconnected:", agent);
});
}
function createHub() {
url = "http://localhost:" + port;
externalUrl = "http://" + getLocalIP() + ":" + port;
self.error("Creating a Hub. Open `yeti --server` in another " +
"Terminal to reuse browsers for future batches.");
var client,
hub = self.createHub(options);
hub.listen(port);
hub.once("error", function (err) {
throw err;
});
client = hubClient.createClient(url);
client.connect(function (err) {
if (err) {
throw err;
} else {
self.error(""); // Newline.
prepareTests(client);
}
});
}
function connectToURL(url) {
var client = hubClient.createClient(url);
client.connect(function (err) {
if (err) {
if (options.get("hub")) {
self.error("Unable to connect to Hub at", externalUrl,
"with", err.stack);
}
createHub();
} else {
prepareTests(client);
}
});
}
if (!url) {
url = "http://localhost:" + port;
externalUrl = "http://" + getLocalIP() + ":" + port;
}
connectToURL(url);
};
CLI.prototype.startServer = function startServer(options) {
var self = this,
port = options.get("port"),
ipAddress = "127.0.0.1",
hub = self.createHub(options);
hub.once("error", function (err) {
if (err.code === "EADDRINUSE") {
self.panic("Unable to start the Hub because port %s is in use.", port);
} else {
throw err;
}
});
hub.listen(port, function () {
self.error("Yeti Hub started. LAN: http://%s:%s\n" +
" Local: http://localhost:%s",
getLocalIP(), port, port);
});
};
CLI.prototype.route = function (argv) {
var parsedArgs = parseArgv(argv),
config = new Configuration(),
usage = "usage: " + argv[1] +
" [--version | -v] [--junit] [--server | -s] [--port=<n>]" +
" [--hub=<url>] [--loglevel <level>] [--timeout <seconds>]" +
" [--query <params>] [--basedir <directory>] [--browser <name[/version]>...]" +
" [--caps <capabilities>]" +
" [--wd-url <url>] [--self-url <url>]" +
" [--help] [--] [<HTML file>...]";
config.pipeLog(this);
if (parsedArgs.loglevel) {
this.printLogEventsForLevel("Yeti CLI", parsedArgs.loglevel);
}
// hub nopt type is url, with a Boolean fallback.
// If we get true, a URL was provided but failed to parse.
if (parsedArgs.hub === true) {
this.error("Command-line Hub option does not appear to be a valid URL. Ignoring.");
delete parsedArgs.hub;
}
config.import({
// Defaults.
port: 9000,
host: "127.0.0.1",
basedir: process.cwd()
}).setFilename(".yeti.json").home().find().env("YETI_").import(parsedArgs);
if (parsedArgs.argv.remain.length) {
config.set("files", parsedArgs.argv.remain);
}
if (parsedArgs.version || parsedArgs.argv.original[0] === "-v") {
this.puts(meta.version);
this.exit(0);
} else if (parsedArgs.help) {
this.puts(usage);
this.exit(0);
} else if (config.get("server")) {
if (config.get("files")) {
this.error("Ignoring files, only starting the server.");
}
this.startServer(config);
} else if (config.get("files") || config.get("glob")) {
try {
config.set("browser", parseBrowsers(config.get("browser")));
} catch (ex) {
return this.panic("Unable to parse browsers option: " + ex.message);
}
config.set("caps", parseCaps(config.get("caps")));
this.prepareBatch(config, this.runBatch.bind(this));
} else {
this.panic(
usage + "\n" +
"No files specified. " +
"To launch the Yeti server, specify --server."
);
}
};
exports.CLI = CLI;