index.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. /*!
  2. * Module dependencies.
  3. */
  4. var path = require('path');
  5. var util = require('util');
  6. var events = require('events');
  7. var HttpRequest = require('./http/request.js');
  8. var CommandQueue = require('./core/queue.js');
  9. var Assertion = require('./core/assertion.js');
  10. var Logger = require('./util/logger.js');
  11. var Api = require('./core/api.js');
  12. var Utils = require('./util/utils.js');
  13. function Nightwatch(options) {
  14. events.EventEmitter.call(this);
  15. this.api = {
  16. capabilities : {},
  17. globals : options && options.persist_globals && options.globals || {},
  18. sessionId : null
  19. };
  20. this.setMaxListeners(0);
  21. this.sessionId = null;
  22. this.context = null;
  23. this.terminated = false;
  24. this.setOptions(options)
  25. .setCapabilities()
  26. .loadKeyCodes();
  27. this.errors = [];
  28. this.results = {
  29. passed:0,
  30. failed:0,
  31. errors:0,
  32. skipped:0,
  33. tests:[]
  34. };
  35. Assertion.init(this);
  36. Api.init(this).load();
  37. this.queue = CommandQueue;
  38. this.queue.empty();
  39. this.queue.reset();
  40. }
  41. Nightwatch.DEFAULT_CAPABILITIES = {
  42. browserName: 'firefox',
  43. javascriptEnabled: true,
  44. acceptSslCerts: true,
  45. platform: 'ANY'
  46. };
  47. util.inherits(Nightwatch, events.EventEmitter);
  48. Nightwatch.prototype.assertion = Assertion.assert;
  49. Nightwatch.prototype.setOptions = function(options) {
  50. this.options = {};
  51. this.api.options = {};
  52. if (options && typeof options == 'object') {
  53. for (var propName in options) {
  54. this.options[propName] = options[propName];
  55. }
  56. }
  57. this.api.launchUrl = this.options.launchUrl || this.options.launch_url || null;
  58. // backwords compatibility
  59. this.api.launch_url = this.api.launchUrl;
  60. if (this.options.globals && typeof this.options.globals == 'object' && !this.options.persist_globals) {
  61. for (var globalKey in this.options.globals) {
  62. this.api.globals[globalKey] = this.options.globals[globalKey];
  63. }
  64. }
  65. var screenshots = this.options.screenshots;
  66. var screenshotsEnabled = screenshots && screenshots.enabled || false;
  67. this.api.options.screenshots = screenshotsEnabled;
  68. if (screenshotsEnabled) {
  69. if (typeof screenshots.path == 'undefined') {
  70. throw new Error('Please specify the screenshots.path in nightwatch.json.');
  71. }
  72. this.options.screenshots.on_error = this.options.screenshots.on_error ||
  73. (typeof this.options.screenshots.on_error == 'undefined');
  74. this.api.screenshotsPath = this.api.options.screenshotsPath = screenshots.path;
  75. } else {
  76. this.options.screenshots = {
  77. enabled : false,
  78. path : ''
  79. };
  80. }
  81. this.setLocateStrategy();
  82. if (this.options.silent) {
  83. Logger.disable();
  84. } else {
  85. Logger.enable();
  86. }
  87. this.options.start_session = this.options.start_session || (typeof this.options.start_session == 'undefined');
  88. this.api.options.skip_testcases_on_fail = this.options.skip_testcases_on_fail ||
  89. (typeof this.options.skip_testcases_on_fail == 'undefined' && this.options.start_session); // off by default for unit tests
  90. this.api.options.log_screenshot_data = this.options.log_screenshot_data ||
  91. (typeof this.options.log_screenshot_data == 'undefined');
  92. var seleniumPort = this.options.seleniumPort || this.options.selenium_port;
  93. var seleniumHost = this.options.seleniumHost || this.options.selenium_host;
  94. var useSSL = this.options.useSsl || this.options.use_ssl;
  95. var proxy = this.options.proxy;
  96. var timeoutOptions = this.options.request_timeout_options || {};
  97. if (seleniumPort) {
  98. HttpRequest.setSeleniumPort(seleniumPort);
  99. }
  100. if (seleniumHost) {
  101. HttpRequest.setSeleniumHost(seleniumHost);
  102. }
  103. if (useSSL) {
  104. HttpRequest.useSSL(true);
  105. }
  106. if (proxy) {
  107. HttpRequest.setProxy(proxy);
  108. }
  109. if (typeof timeoutOptions.timeout != 'undefined') {
  110. HttpRequest.setTimeout(timeoutOptions.timeout);
  111. }
  112. if (typeof timeoutOptions.retry_attempts != 'undefined') {
  113. HttpRequest.setRetryAttempts(timeoutOptions.retry_attempts);
  114. }
  115. if (typeof this.options.default_path_prefix == 'string') {
  116. HttpRequest.setDefaultPathPrefix(this.options.default_path_prefix);
  117. }
  118. var username = this.options.username;
  119. var key = this.options.accesKey || this.options.access_key || this.options.password;
  120. if (username && key) {
  121. this.api.options.username = username;
  122. this.api.options.accessKey = key;
  123. HttpRequest.setCredentials({
  124. username : username,
  125. key : key
  126. });
  127. }
  128. this.endSessionOnFail(typeof this.options.end_session_on_fail == 'undefined' || this.options.end_session_on_fail);
  129. return this;
  130. };
  131. Nightwatch.prototype.endSessionOnFail = function(value) {
  132. if (typeof value == 'undefined') {
  133. return this.options.end_session_on_fail;
  134. }
  135. this.options.end_session_on_fail = value;
  136. return this;
  137. };
  138. Nightwatch.prototype.setCapabilities = function() {
  139. this.desiredCapabilities = {};
  140. for (var capability in Nightwatch.DEFAULT_CAPABILITIES) {
  141. this.desiredCapabilities[capability] = Nightwatch.DEFAULT_CAPABILITIES[capability];
  142. }
  143. if (this.options.desiredCapabilities) {
  144. for (var prop in this.options.desiredCapabilities) {
  145. if (this.options.desiredCapabilities.hasOwnProperty(prop)) {
  146. this.desiredCapabilities[prop] = this.options.desiredCapabilities[prop];
  147. }
  148. }
  149. }
  150. this.api.options.desiredCapabilities = this.desiredCapabilities;
  151. return this;
  152. };
  153. Nightwatch.prototype.setLocateStrategy = function () {
  154. this.locateStrategy = this.options.use_xpath ? 'xpath' : 'css selector';
  155. return this;
  156. };
  157. Nightwatch.prototype.loadKeyCodes = function() {
  158. this.api.Keys = require('./util/keys.json');
  159. return this;
  160. };
  161. Nightwatch.prototype.start = function() {
  162. if (!this.sessionId && this.options.start_session) {
  163. this
  164. .once('selenium:session_create', this.start)
  165. .startSession();
  166. return this;
  167. }
  168. var self = this;
  169. this.queue.reset();
  170. this.queue.run(function(error) {
  171. if (error) {
  172. var stackTrace = '';
  173. if (error.stack) {
  174. stackTrace = error.stack.split('\n').slice(1).join('\n');
  175. }
  176. self.results.errors++;
  177. self.errors.push(error.name + ': ' + error.message + '\n' + stackTrace);
  178. if (self.options.output) {
  179. Utils.showStackTraceWithHeadline(error.name + ': ' + error.message, stackTrace, true);
  180. }
  181. if (self.options.start_session) {
  182. self.terminate();
  183. }
  184. return;
  185. }
  186. self.finished();
  187. });
  188. return this;
  189. };
  190. Nightwatch.prototype.terminate = function(deferred) {
  191. // in case this was a synchronous command (e.g. assert.ok()) we need to wait for other possible
  192. // commands which might have been added afterwards while client is terminated
  193. if (deferred) {
  194. this.queue.instance().once('queue:started', this.terminateSession.bind(this));
  195. } else {
  196. this.terminateSession();
  197. }
  198. this.terminated = true;
  199. return this;
  200. };
  201. Nightwatch.prototype.resetTerminated = function() {
  202. this.terminated = false;
  203. return this;
  204. };
  205. Nightwatch.prototype.terminateSession = function() {
  206. this.queue.reset();
  207. this.queue.empty();
  208. if (this.options.end_session_on_fail && this.options.start_session) {
  209. this.api.end(function() {
  210. this.finished();
  211. }.bind(this));
  212. // FIXME: sometimes the queue is incorrectly restarted when another .end() is
  213. // scheduled from globalBeforeEach and results into a session command being sent with
  214. // null as the sessionId
  215. this.queue.run();
  216. } else {
  217. this.finished();
  218. }
  219. return this;
  220. };
  221. Nightwatch.prototype.complete = function() {
  222. return this.emit('complete');
  223. };
  224. Nightwatch.prototype.finished = function() {
  225. Logger.info('FINISHED');
  226. this.emit('nightwatch:finished', this.results, this.errors);
  227. return this;
  228. };
  229. Nightwatch.prototype.getFailureMessage = function() {
  230. var errors = '';
  231. var failure_msg = [];
  232. if (this.results.failed > 0) {
  233. failure_msg.push(Logger.colors.red(this.results.failed) +
  234. ' assertions failed');
  235. }
  236. if (this.results.errors > 0) {
  237. failure_msg.push(Logger.colors.red(this.results.errors) + ' errors');
  238. }
  239. if (this.results.passed > 0) {
  240. failure_msg.push(Logger.colors.green(this.results.passed) + ' passed');
  241. }
  242. if (this.results.skipped > 0) {
  243. failure_msg.push(Logger.colors.blue(this.results.skipped) + ' skipped');
  244. }
  245. return failure_msg.join(', ').replace(/,([^,]*)$/g, function($0, $1) {
  246. return ' and' + $1;
  247. });
  248. };
  249. Nightwatch.prototype.printResult = function(elapsedTime) {
  250. if (this.options.output && this.options.start_session) {
  251. var ok = false;
  252. if (this.results.failed === 0 && this.results.errors === 0) {
  253. ok = true;
  254. }
  255. if (ok && this.results.passed > 0) {
  256. console.log('\n' + Logger.colors.green('OK.'),
  257. Logger.colors.green(this.results.passed) + ' assertions passed. (' + Utils.formatElapsedTime(elapsedTime, true) + ')');
  258. } else if (ok && this.results.passed === 0) {
  259. if (this.options.start_session) {
  260. console.log(Logger.colors.green('No assertions ran.'));
  261. }
  262. } else {
  263. var failure_msg = this.getFailureMessage();
  264. console.log('\n' + Logger.colors.red('FAILED: '), failure_msg, '(' + Utils.formatElapsedTime(elapsedTime, true) + ')');
  265. }
  266. }
  267. };
  268. Nightwatch.prototype.clearResult = function() {
  269. this.errors.length = 0;
  270. this.results.passed = 0;
  271. this.results.failed = 0;
  272. this.results.errors = 0;
  273. this.results.skipped = 0;
  274. this.results.tests.length = 0;
  275. };
  276. Nightwatch.prototype.handleException = function(err) {
  277. var stack = err.stack.split('\n');
  278. var failMessage = stack.shift();
  279. var firstLine = ' ' + String.fromCharCode(10006) + ' ' + failMessage;
  280. if (typeof err.actual != 'undefined' && typeof err.expected != 'undefined') {
  281. firstLine += '\033[0;90m - expected ' + Logger.colors.green('"' + err.expected + '"') + ' \033[0;90mbut got: ' + Logger.colors.red('"' + err.actual + '"');
  282. }
  283. if (this.options.output) {
  284. Utils.showStackTraceWithHeadline(firstLine, stack);
  285. }
  286. if (err.name == 'AssertionError') {
  287. this.results.failed++;
  288. stack.unshift(failMessage + ' - expected "' + err.expected + '" but got: "' + err.actual + '"');
  289. this.results.stackTrace = stack.join('\n');
  290. } else {
  291. this.addError('\n ' + err.stack, firstLine);
  292. this.terminate();
  293. }
  294. };
  295. Nightwatch.prototype.runProtocolAction = function(requestOptions, callback) {
  296. var self = this;
  297. var request = new HttpRequest(requestOptions)
  298. .on('result', function(result) {
  299. if (typeof callback != 'function') {
  300. var error = new Error('Callback parameter is not a function - ' + typeof(callback) + ' passed: "' + callback + '"');
  301. self.errors.push(error.stack);
  302. self.results.errors++;
  303. } else {
  304. callback.call(self.api, result);
  305. }
  306. if (result.lastScreenshotFile && self.results.tests.length > 0) {
  307. var lastTest = self.results.tests[self.results.tests.length-1];
  308. lastTest.screenshots = lastTest.screenshots || [];
  309. lastTest.screenshots.push(result.lastScreenshotFile);
  310. delete result.lastScreenshotFile;
  311. }
  312. request.emit('complete');
  313. })
  314. .on('success', function(result, response) {
  315. if (result.status && result.status !== 0) {
  316. result = self.handleTestError(result);
  317. }
  318. request.emit('result', result, response);
  319. })
  320. .on('error', function(result, response, screenshotContent) {
  321. result = self.handleTestError(result);
  322. if (screenshotContent && self.options.screenshots.on_error) {
  323. var fileNamePath = Utils.getScreenshotFileName(self.api.currentTest, true, self.options.screenshots.path);
  324. self.saveScreenshotToFile(fileNamePath, screenshotContent);
  325. result.lastScreenshotFile = fileNamePath;
  326. }
  327. request.emit('result', result, response);
  328. });
  329. return request;
  330. };
  331. Nightwatch.prototype.addError = function(message, logMessage) {
  332. var currentTest;
  333. if (this.api.currentTest) {
  334. currentTest = '[' + Utils.getTestSuiteName(this.api.currentTest.module) + ' / ' + this.api.currentTest.name + ']';
  335. } else {
  336. currentTest = 'tests';
  337. }
  338. this.errors.push(' Error while running '+ currentTest + ':\n' + message);
  339. this.results.errors++;
  340. if (this.options.output) {
  341. Logger.warn(' ' + (logMessage || message));
  342. }
  343. };
  344. Nightwatch.prototype.saveScreenshotToFile = function(fileName, content, cb) {
  345. var mkpath = require('mkpath');
  346. var fs = require('fs');
  347. var self = this;
  348. cb = cb || function() {};
  349. var dir = path.resolve(fileName, '..');
  350. var fail = function(err) {
  351. if (self.options.output) {
  352. console.log(Logger.colors.yellow('Couldn\'t save screenshot to '), fileName);
  353. }
  354. Logger.warn(err);
  355. cb(err);
  356. };
  357. mkpath(dir, function(err) {
  358. if (err) {
  359. fail(err);
  360. } else {
  361. fs.writeFile(fileName, content, 'base64', function(err) {
  362. if (err) {
  363. fail(err);
  364. } else {
  365. cb(null, fileName);
  366. }
  367. });
  368. }
  369. });
  370. };
  371. Nightwatch.prototype.handleTestError = function(result) {
  372. var errorMessage = '';
  373. if (result && result.status) {
  374. var errorCodes = require('./api/errors.json');
  375. errorMessage = errorCodes[result.status] && errorCodes[result.status].message || '';
  376. }
  377. return {
  378. status: -1,
  379. value : result && result.value || null,
  380. errorStatus: result && result.status || '',
  381. error : errorMessage
  382. };
  383. };
  384. Nightwatch.prototype.startSession = function () {
  385. if (this.terminated) {
  386. return this;
  387. }
  388. var self = this;
  389. var options = {
  390. path : '/session',
  391. data : {
  392. desiredCapabilities : this.desiredCapabilities
  393. }
  394. };
  395. var request = new HttpRequest(options);
  396. request.on('success', function(data, response, isRedirect) {
  397. if (data && data.sessionId) {
  398. self.sessionId = self.api.sessionId = data.sessionId;
  399. if (data.value) {
  400. self.api.capabilities = data.value;
  401. }
  402. Logger.info('Got sessionId from selenium', self.sessionId);
  403. self.emit('selenium:session_create', self.sessionId, request, response);
  404. } else if (isRedirect) {
  405. self.followRedirect(request, response);
  406. } else {
  407. request.emit('error', data, null);
  408. }
  409. })
  410. .on('error', function(data, err) {
  411. if (self.options.output) {
  412. console.error('\n' + Logger.colors.light_red('Error retrieving a new session from the selenium server'));
  413. }
  414. if (typeof data == 'object' && Object.keys(data).length === 0) {
  415. data = '';
  416. }
  417. if (!data && err) {
  418. data = err;
  419. }
  420. self.emit('error', data);
  421. })
  422. .send();
  423. return this;
  424. };
  425. Nightwatch.prototype.followRedirect = function (request, response) {
  426. if (!response.headers || !response.headers.location) {
  427. this.emit('error', null, null);
  428. return this;
  429. }
  430. var url = require('url');
  431. var urlParts = url.parse(response.headers.location);
  432. request.setOptions({
  433. path : urlParts.pathname,
  434. host : urlParts.hostname,
  435. port : urlParts.port,
  436. method : 'GET'
  437. }).send();
  438. return this;
  439. };
  440. exports = module.exports = {};
  441. exports.client = function(options) {
  442. return new Nightwatch(options);
  443. };
  444. exports.cli = function(runTests) {
  445. var cli = require('./runner/cli/cli.js');
  446. cli.setup();
  447. var argv = cli.init();
  448. if (argv.help) {
  449. cli.showHelp();
  450. } else if (argv.version) {
  451. var packageConfig = require(__dirname + '/../package.json');
  452. console.log(packageConfig.name + ' v' + packageConfig.version);
  453. } else {
  454. if (typeof runTests != 'function') {
  455. throw new Error('Supplied argument needs to be a function!');
  456. }
  457. runTests(argv);
  458. }
  459. };
  460. exports.runner = function(argv, done, settings) {
  461. var runner = exports.CliRunner(argv);
  462. return runner.setup(settings, done).runTests(done);
  463. };
  464. exports.initGrunt = function(grunt) {
  465. grunt.registerMultiTask('nightwatch', 'run nightwatch.', function() {
  466. var done = this.async();
  467. var options = this.options();
  468. var settings = this.data && this.data.settings;
  469. var argv = this.data && this.data.argv;
  470. exports.cli(function(a) {
  471. Object.keys(argv).forEach(function(key) {
  472. if (key === 'env' && a['parallel-mode'] === true) {
  473. return;
  474. }
  475. a[key] = argv[key];
  476. });
  477. if (a.test) {
  478. a.test = path.resolve(a.test);
  479. }
  480. if (options.cwd) {
  481. process.chdir(options.cwd);
  482. }
  483. exports.runner(a, done, settings);
  484. });
  485. });
  486. };
  487. exports.CliRunner = function(argv) {
  488. var CliRunner = require('./runner/cli/clirunner.js');
  489. return new CliRunner(argv);
  490. };
  491. exports.initClient = function(opts) {
  492. var Manager = require('./runner/clientmanager.js');
  493. var instance = new Manager();
  494. return instance.init(opts);
  495. };