forked from nightwatchjs/nightwatch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
463 lines (404 loc) · 13 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
var util = require("util"),
fs = require('fs'),
path = require('path'),
events = require("events"),
HttpRequest = require('./request.js'),
CommandQueue = require('./queue.js'),
Logger = require("./logger.js");
function Nightwatch(options) {
events.EventEmitter.call(this);
this.setMaxListeners(0);
this.options = options || {};
var self = this;
this.sessionId = null;
this.context = null;
this.terminated = false;
this.options.screenshots || (this.options.screenshots = {
"enabled" : false,
"path" : ""
});
this.options.output = this.options.output || typeof this.options.output == 'undefined';
this.screenshotPath = this.options.screenshotPath || "";
this.isRunning = false;
this.launch_url = this.options.launch_url || null;
if (this.options.silent) {
Logger.disable();
} else {
Logger.enable();
}
if (this.options.selenium_port) {
HttpRequest.setSeleniumPort(this.options.selenium_port);
}
if (this.options.selenium_host) {
HttpRequest.setSeleniumHost(this.options.selenium_host);
}
if (this.options.use_ssl) {
HttpRequest.useSSL(true);
}
if (this.options.username && this.options.access_key) {
HttpRequest.setCredentials({
username : this.options.username,
key : this.options.access_key
});
}
this.desiredCapabilities = {
browserName: "firefox",
javascriptEnabled: true,
acceptSslCerts: true,
platform: "ANY"
};
if (this.options.desiredCapabilities) {
for (prop in this.options.desiredCapabilities) {
this.desiredCapabilities[prop] = this.options.desiredCapabilities[prop];
}
}
this.errors = [];
this.results = {
passed:0,
failed:0,
errors:0,
skipped:0,
tests:[]
};
this.queue = CommandQueue;
this.queue.empty();
this.queue.reset();
this.loadProtocolActions()
.loadCommands()
.addVerifyTests()
.loadAssertions();
if (this.options.custom_commands_path) {
this.loadCustomCommands();
}
};
util.inherits(Nightwatch, events.EventEmitter);
Nightwatch.prototype.start = function() {
if (!this.sessionId) {
this.startSession().once('selenium:session_create', this.start);
return this;
}
var self = this;
this.queue.reset();
this.queue.run(function(error) {
if (error) {
self.results.errors++;
self.errors.push(error.name + ': ' + error.message);
self.terminate();
return;
}
Logger.info('FINISHED');
self.emit('queue:finished', self.results, self.errors);
self.printResult();
});
return this;
}
Nightwatch.prototype.terminate = function() {
var self = this;
this.results.skipped = this.queue.getSkipped();
this.terminated = true;
this.queue.reset();
this.queue.empty();
this.runCommand('session', ['delete'], function(result) {
self.emit('queue:finished', self.results, self.errors);
self.printResult();
});
return this;
}
Nightwatch.prototype.printResult = function() {
if (!this.options.output) {
return;
}
var ok = false;
if (this.results.failed == 0 && this.results.errors == 0) {
ok = true;
}
if (ok && this.results.passed > 0) {
console.log(Logger.colors.green('OK.'), Logger.colors.green(this.results.passed) + ' assertions passed.');
} else if (ok && this.results.passed == 0) {
console.log(Logger.colors.green('No assertions ran.'));
} else {
var errors = '';
if (this.results.errors) {
errors = this.results.errors + ' errors during the test. ';
for (var i = 0; i < this.errors.length; i++) {
console.log(Logger.colors.red(this.errors[i]));
}
}
var failure_msg = [];
if (this.results.failed > 0) {
failure_msg.push(Logger.colors.red(this.results.failed) + ' assertions failed');
}
if (this.results.errors > 0) {
failure_msg.push(Logger.colors.red(this.results.errors) + ' errors');
}
if (this.results.passed > 0) {
failure_msg.push(Logger.colors.green(this.results.passed) + ' passed');
}
if (this.results.skipped > 0) {
failure_msg.push(Logger.colors.blue(this.results.skipped) + ' skipped');
}
console.log(Logger.colors.red('FAILED: '), failure_msg.join(', ').replace(/,([^,]*)$/g, function($0, $1, index, str) {
return ' and' +$1;
}));
}
this.errors.length = 0;
this.results.passed = 0;
this.results.failed = 0;
this.results.errors = 0;
this.results.skipped = 0;
this.results.tests.length = 0;
}
Nightwatch.prototype.loadProtocolActions = function() {
var protocol = require('./selenium/protocol.js');
var actions = Object.keys(protocol.actions);
var self = this;
actions.forEach(function(command, index) {
self.addCommand(command, protocol.actions[command], self);
});
return this;
}
Nightwatch.prototype.loadCommands = function() {
require('./selenium/commands.js').addCommands.call(this);
return this;
}
Nightwatch.prototype.loadCustomCommands = function() {
var absPath = path.join(process.cwd(), this.options.custom_commands_path);
var commandFiles = fs.readdirSync(absPath);
var self = this;
commandFiles.forEach(function(file) {
if (path.extname(file) == ".js") {
var command = require(path.join(absPath, file));
var name = path.basename(file, '.js');
self.addCommand(name, command.command, self, self);
}
})
}
Nightwatch.prototype.loadAssertions = function() {
var self = this;
var assertModule = require('assert');
this.assert = {};
for (var prop in assertModule) {
if (assertModule.hasOwnProperty(prop)) {
this.assert[prop] = (function(prop) {
return function() {
var passed, message, expected = null;
var actual = arguments[0];
var message = typeof arguments[arguments.length-1] == 'string' &&
(arguments.length > 2 || typeof arguments[0] === "boolean") &&
arguments[arguments.length-1]
|| (typeof arguments[0] === "function" && '[Function]')
|| '' + actual;
try {
assertModule[prop].apply(null, arguments);
passed = true;
message = "Assertion passed: " + message;
} catch (ex) {
passed = false;
message = "Assertion failed: " + (ex.message || message);
actual = ex.actual;
expected = ex.expected
}
return self.assertion(passed, actual, expected, message, true);
}
})(prop);
}
}
this.loadAssetionFiles(this.assert, true);
}
Nightwatch.prototype.addVerifyTests = function() {
this.verify = {};
this.loadAssetionFiles(this.verify, false);
return this;
}
Nightwatch.prototype.loadAssetionFiles = function(parent, abortOnFailure) {
var relativePath = './selenium/assertions/';
var commandFiles = fs.readdirSync(path.join(__dirname, relativePath));
var AbstractAssertion = function(abortOnFailure, client) {
this.abortOnFailure = abortOnFailure;
this.client = client;
}
for (var i = 0, len = commandFiles.length; i < len; i++) {
if (path.extname(commandFiles[i]) == ".js") {
var commandName = path.basename(commandFiles[i], '.js');
var Module = require(path.join(__dirname, relativePath) + commandFiles[i]);
var m = new Module();
AbstractAssertion.call(m, abortOnFailure, this);
this.addCommand(commandName, m.command, m, parent);
}
}
}
Nightwatch.prototype.addCommand = function(name, command, context, parent) {
parent = parent || this;
if (parent[name]) {
this.results.errors++;
var error = new Error("The command '" + name + "' is already defined!");
this.errors.push(error.stack)
throw error;
}
var self = this;
parent[name] = (function(internalCommandName) {
return function() {
var args = Array.prototype.slice.call(arguments);
CommandQueue.add(internalCommandName, command, context, args);
return self;
};
})(name);
return this;
};
/**
*
* @param {Object} requestOptions
* @param {Function} callback
*/
Nightwatch.prototype.runProtocolCommand = function(requestOptions, callback) {
var self = this;
var request = new HttpRequest(requestOptions);
request.on('success', function(result, response) {
if (result.status && result.status !== 0) {
result = self.handleTestError(result);
}
request.emit('result', result, response);
})
.on('error', function(result, response, screenshotContent) {
result = self.handleTestError(result);
if (screenshotContent && self.options.screenshots.enabled) {
var d = new Date();
var datestamp = d.toLocaleDateString().toLowerCase().replace(/\//g, '-') + '--' + d.toLocaleTimeString()
var fileName = path.join(self.options.screenshots.path, 'ERROR_' + datestamp + '.png');
self.saveScreenshotToFile(fileName, screenshotContent)
}
request.emit('result', result, response);
})
.on('result', function(result) {
if (callback) {
try {
if (typeof callback != "function") {
var error = new Error('Callback parameter is not a function - ' + typeof(callback) + ' passed: "' + callback + '"');
this.errors.push(error.stack)
this.results.errors++;
throw error;
}
callback.call(self, result);
} catch (ex) {
console.log(ex.stack)
}
}
});
return request
};
Nightwatch.prototype.runCommand = function(commandName, args, callback) {
var self = this;
if (commandName in this) {
args.push(callback);
this[commandName].apply(this, args);
} else {
this.results.errors++;
var error = new Error('No such command: ' + commandName);
this.errors.push(error.stack)
throw error;
}
return this.queue.run();
}
Nightwatch.prototype.executeCommand = function(command) {
util.inherits(command, events.EventEmitter);
var instance = new command();
events.EventEmitter.call(instance)
return instance;
}
Nightwatch.prototype.getElement = function(using, value, callback) {
var self = this;
return this.runCommand("element", [using, value, function(result) {
if (result.status == 0) {
callback.call(self, result.value.ELEMENT, result);
} else {
callback.call(self, false, result);
}
}]);
};
Nightwatch.prototype.assertion = function(passed, receivedValue, expectedValue, message, abortOnFailure) {
var failure = '', stacktrace = '';
if (passed) {
if (this.options.output) {
console.log(Logger.colors.green("✔") + " " + message);
}
this.results.passed++;
} else {
failure = 'Expected "' + expectedValue + '" but got: "' + receivedValue + '"';
try {
var err = new Error();
err.name = 'Assertion failed in: ' + message;
err.message = failure;
Error.captureStackTrace(err, arguments.callee);
throw err;
} catch (ex) {
var logged = Logger.colors.red("✖") + " " + message;
if (typeof expectedValue != "undefined" && typeof receivedValue != "undefined") {
logged += " " + Logger.colors.white(' - expected "' + Logger.colors.green(expectedValue)) + '" but got: ' + Logger.colors.red(receivedValue);
}
if (this.options.output) {
console.log(logged);
}
stacktrace = ex.stack;
}
this.results.failed++;
}
this.results.tests.push({
message : message,
stacktrace : stacktrace,
failure : failure !== '' ? failure : false
});
if (!passed && abortOnFailure) {
this.terminate();
}
return this
};
Nightwatch.prototype.saveScreenshotToFile = function(fileName, content) {
fs.writeFile(fileName, content, "base64", function(err) {
if (err) {
Logger.error(err);
}
});
};
Nightwatch.prototype.handleTestError = function(result) {
var errorMessage = '';
if (result && result.status) {
var errorCodes = require('./selenium/errors.json');
errorMessage = errorCodes[result.status].message || "";
}
var rv = {
status: -1,
value : result && result.value || null,
errorStatus: result && result.status || '',
error : errorMessage
};
return rv;
};
Nightwatch.prototype.startSession = function() {
var self = this;
var request = new HttpRequest({
path : "/session",
data : {
desiredCapabilities : this.desiredCapabilities,
sessionId : null
}
});
request.on('success', function(data, response) {
if (data.sessionId) {
self.sessionId = data.sessionId;
Logger.info("Got sessionId from selenium", self.sessionId);
self.emit('selenium:session_create', self.sessionId, request, response);
} else {
Logger.warn("Couldn't retrieve a new session from selenium server.");
}
})
.on('error', function(data, err) {
console.error(Logger.colors.red("Connection refused!"), "Is selenium server started?", err);
self.emit('error', data, err);
})
.send();
return this;
};
var instance = null;
exports.client = function(options) {
return new Nightwatch(options);
}