index.js 16.2 KB
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 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
/*!
 * Module dependencies.
 */
var path = require('path');
var util = require('util');
var events = require('events');
var HttpRequest = require('./http/request.js');
var CommandQueue = require('./core/queue.js');
var Assertion = require('./core/assertion.js');
var Logger = require('./util/logger.js');
var Api = require('./core/api.js');
var Utils = require('./util/utils.js');

function Nightwatch(options) {
  events.EventEmitter.call(this);

  this.locateStrategy = 'css selector';

  this.api = {
    capabilities : {},
    globals : options && options.persist_globals && options.globals || {},
    sessionId : null
  };

  this.setMaxListeners(0);
  this.sessionId = null;
  this.context = null;
  this.terminated = false;

  this.setOptions(options)
      .setCapabilities()
      .loadKeyCodes();

  this.errors = [];
  this.results = {
    passed:0,
    failed:0,
    errors:0,
    skipped:0,
    tests:[]
  };

  Assertion.init(this);
  Api.init(this).load();

  this.queue = CommandQueue;
  this.queue.empty();
  this.queue.reset();
}

Nightwatch.DEFAULT_CAPABILITIES = {
  browserName: 'firefox',
  javascriptEnabled: true,
  acceptSslCerts: true,
  platform: 'ANY'
};

util.inherits(Nightwatch, events.EventEmitter);

Nightwatch.prototype.assertion = Assertion.assert;

Nightwatch.prototype.setOptions = function(options) {
  this.options = {};
  this.api.options = {};
  if (options && typeof options == 'object') {
    for (var propName in options) {
      this.options[propName] = options[propName];
    }
  }

  this.api.launchUrl = this.options.launchUrl || this.options.launch_url || null;
  // backwords compatibility
  this.api.launch_url = this.api.launchUrl;

  if (this.options.globals && typeof this.options.globals == 'object' && !this.options.persist_globals) {
    for (var globalKey in this.options.globals) {
      this.api.globals[globalKey] = this.options.globals[globalKey];
    }
  }

  var screenshots = this.options.screenshots;
  var screenshotsEnabled = screenshots && screenshots.enabled || false;

  this.api.options.screenshots = screenshotsEnabled;
  if (screenshotsEnabled) {
    if (typeof screenshots.path == 'undefined') {
      throw new Error('Please specify the screenshots.path in nightwatch.json.');
    }
    this.options.screenshots.on_error = this.options.screenshots.on_error ||
      (typeof this.options.screenshots.on_error == 'undefined');
    this.api.screenshotsPath = this.api.options.screenshotsPath = screenshots.path;
  } else {
    this.options.screenshots = {
      enabled : false,
      path : ''
    };
  }

  if (this.options.use_xpath) {
    this.locateStrategy = 'xpath';
  }

  if (this.options.silent) {
    Logger.disable();
  } else {
    Logger.enable();
  }

  this.options.start_session = this.options.start_session || (typeof this.options.start_session == 'undefined');

  this.api.options.skip_testcases_on_fail = this.options.skip_testcases_on_fail ||
    (typeof this.options.skip_testcases_on_fail == 'undefined' && this.options.start_session); // off by default for unit tests

  this.api.options.log_screenshot_data = this.options.log_screenshot_data ||
    (typeof this.options.log_screenshot_data == 'undefined');
  var seleniumPort     = this.options.seleniumPort || this.options.selenium_port;
  var seleniumHost     = this.options.seleniumHost || this.options.selenium_host;
  var useSSL           = this.options.useSsl || this.options.use_ssl;
  var proxy            = this.options.proxy;
  var timeoutOptions   = this.options.request_timeout_options || {};

  if (seleniumPort) {
    HttpRequest.setSeleniumPort(seleniumPort);
  }
  if (seleniumHost) {
    HttpRequest.setSeleniumHost(seleniumHost);
  }
  if (useSSL) {
    HttpRequest.useSSL(true);
  }
  if (proxy) {
    HttpRequest.setProxy(proxy);
  }
  if (typeof timeoutOptions.timeout != 'undefined') {
    HttpRequest.setTimeout(timeoutOptions.timeout);
  }
  if (typeof timeoutOptions.retry_attempts != 'undefined') {
    HttpRequest.setRetryAttempts(timeoutOptions.retry_attempts);
  }

  if (typeof this.options.default_path_prefix == 'string') {
    HttpRequest.setDefaultPathPrefix(this.options.default_path_prefix);
  }

  var username = this.options.username;
  var key = this.options.accesKey || this.options.access_key || this.options.password;

  if (username && key) {
    this.api.options.username = username;
    this.api.options.accessKey = key;

    HttpRequest.setCredentials({
      username : username,
      key : key
    });
  }

  this.endSessionOnFail(typeof this.options.end_session_on_fail == 'undefined' || this.options.end_session_on_fail);

  return this;
};

Nightwatch.prototype.endSessionOnFail = function(value) {
  if (typeof value == 'undefined') {
    return this.options.end_session_on_fail;
  }

  this.options.end_session_on_fail = value;
  return this;
};

Nightwatch.prototype.setCapabilities = function() {
  this.desiredCapabilities = {};
  for (var capability in Nightwatch.DEFAULT_CAPABILITIES) {
    this.desiredCapabilities[capability] = Nightwatch.DEFAULT_CAPABILITIES[capability];
  }

  if (this.options.desiredCapabilities) {
    for (var prop in this.options.desiredCapabilities) {
      if (this.options.desiredCapabilities.hasOwnProperty(prop)) {
        this.desiredCapabilities[prop] = this.options.desiredCapabilities[prop];
      }
    }
  }
  this.api.options.desiredCapabilities = this.desiredCapabilities;
  return this;
};

Nightwatch.prototype.loadKeyCodes = function() {
  this.api.Keys = require('./util/keys.json');
  return this;
};

Nightwatch.prototype.start = function() {
  if (!this.sessionId && this.options.start_session) {
    this
      .once('selenium:session_create', this.start)
      .startSession();
    return this;
  }

  var self = this;

  this.queue.reset();
  this.queue.run(function(error) {
    if (error) {
      var stackTrace = '';
      if (error.stack) {
        stackTrace = error.stack.split('\n').slice(1).join('\n');
      }

      self.results.errors++;
      self.errors.push(error.name + ': ' + error.message + '\n' + stackTrace);
      if (self.options.output) {
        Utils.showStackTraceWithHeadline(error.name + ': ' + error.message, stackTrace, true);
      }

      if (self.options.start_session) {
        self.terminate();
      }
      return;
    }

    self.finished();
  });

  return this;
};

Nightwatch.prototype.terminate = function(deferred) {
  // in case this was a synchronous command (e.g. assert.ok()) we need to wait for other possible
  // commands which might have been added afterwards while client is terminated
  if (deferred) {
    this.queue.instance().once('queue:started', this.terminateSession.bind(this));
  } else {
    this.terminateSession();
  }

  this.terminated = true;
  return this;
};

Nightwatch.prototype.resetTerminated = function() {
  this.terminated = false;
  return this;
};

Nightwatch.prototype.terminateSession = function() {
  this.queue.reset();
  this.queue.empty();

  if (this.options.end_session_on_fail && this.options.start_session) {
    this.api.end(function() {
      this.finished();
    }.bind(this));

    // FIXME: sometimes the queue is incorrectly restarted when another .end() is
    // scheduled from globalBeforeEach and results into a session command being sent with
    // null as the sessionId
    this.queue.run();
  } else {
    this.finished();
  }
  return this;
};

Nightwatch.prototype.complete = function() {
  return this.emit('complete');
};

Nightwatch.prototype.finished = function() {
  Logger.info('FINISHED');

  this.emit('nightwatch:finished', this.results, this.errors);

  return this;
};

Nightwatch.prototype.getFailureMessage = function() {
  var errors = '';

  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');
  }

  return failure_msg.join(', ').replace(/,([^,]*)$/g, function($0, $1) {
    return  ' and' + $1;
  });
};

Nightwatch.prototype.printResult = function(elapsedTime) {
  if (this.options.output && this.options.start_session) {
    var ok = false;
    if (this.results.failed === 0 && this.results.errors === 0) {
      ok = true;
    }

    if (ok && this.results.passed > 0) {
      console.log('\n' + Logger.colors.green('OK.'),
        Logger.colors.green(this.results.passed) + ' assertions passed. (' + Utils.formatElapsedTime(elapsedTime, true) + ')');
    } else if (ok && this.results.passed === 0) {
      if (this.options.start_session) {
        console.log(Logger.colors.green('No assertions ran.'));
      }
    } else {
      var failure_msg = this.getFailureMessage();
      console.log('\n' +  Logger.colors.red('FAILED: '), failure_msg, '(' + Utils.formatElapsedTime(elapsedTime, true) + ')');
    }
  }
};

Nightwatch.prototype.clearResult = function() {
  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.handleException = function(err) {
  var stack = err.stack.split('\n');
  var failMessage = stack.shift();
  var firstLine = ' ' + String.fromCharCode(10006) + ' ' + failMessage;
  if (typeof err.actual != 'undefined' && typeof err.expected != 'undefined') {
    firstLine += '\033[0;90m - expected ' + Logger.colors.green('"' + err.expected + '"') + ' \033[0;90mbut got: ' + Logger.colors.red('"' + err.actual + '"');
  }

  if (this.options.output) {
    Utils.showStackTraceWithHeadline(firstLine, stack);
  }

  if (err.name == 'AssertionError') {
    this.results.failed++;
    stack.unshift(failMessage + ' - expected "' + err.expected + '" but got: "' + err.actual + '"');
    this.results.stackTrace = stack.join('\n');
  } else {
    this.addError('\n  ' + err.stack, firstLine);
    this.terminate();
  }
};

Nightwatch.prototype.runProtocolAction = function(requestOptions, callback) {
  var self = this;

  var request = new HttpRequest(requestOptions)
    .on('result', function(result) {
      if (typeof callback != 'function') {
        var error = new Error('Callback parameter is not a function - ' + typeof(callback) + ' passed: "' + callback + '"');
        self.errors.push(error.stack);
        self.results.errors++;
      } else {
        callback.call(self.api, result);
      }

      if (result.lastScreenshotFile && self.results.tests.length > 0) {
        var lastTest = self.results.tests[self.results.tests.length-1];
        lastTest.screenshots = lastTest.screenshots || [];
        lastTest.screenshots.push(result.lastScreenshotFile);
        delete result.lastScreenshotFile;
      }

      request.emit('complete');
    })
    .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.on_error) {
        var fileNamePath = Utils.getScreenshotFileName(self.api.currentTest, true, self.options.screenshots.path);
        self.saveScreenshotToFile(fileNamePath, screenshotContent);
        result.lastScreenshotFile = fileNamePath;
      }

      request.emit('result', result, response);
    });

  return request;
};

Nightwatch.prototype.addError = function(message, logMessage) {
  var currentTest;
  if (this.api.currentTest) {
    currentTest = '[' + Utils.getTestSuiteName(this.api.currentTest.module) + ' / ' + this.api.currentTest.name + ']';
  } else {
    currentTest = 'tests';
  }

  this.errors.push('  Error while running '+ currentTest  + ':\n' + message);
  this.results.errors++;
  if (this.options.output) {
    Logger.warn('    ' + (logMessage || message));
  }

};

Nightwatch.prototype.saveScreenshotToFile = function(fileName, content, cb) {
  var mkpath = require('mkpath');
  var fs = require('fs');
  var self = this;
  cb = cb || function() {};

  var dir = path.resolve(fileName, '..');
  var fail = function(err) {
    if (self.options.output) {
      console.log(Logger.colors.yellow('Couldn\'t save screenshot to '), fileName);
    }

    Logger.warn(err);
    cb(err);
  };

  mkpath(dir, function(err) {
    if (err) {
      fail(err);
    } else {
      fs.writeFile(fileName, content, 'base64', function(err) {
        if (err) {
          fail(err);
        } else {
          cb(null, fileName);
        }
      });
    }
  });
};

Nightwatch.prototype.handleTestError = function(result) {
  var errorMessage = '';
  if (result && result.status) {
    var errorCodes = require('./api/errors.json');
    errorMessage = errorCodes[result.status] && errorCodes[result.status].message || '';
  }

  return {
    status: -1,
    value : result && result.value || null,
    errorStatus: result && result.status || '',
    error : errorMessage
  };
};

Nightwatch.prototype.startSession = function () {
  if (this.terminated) {
    return this;
  }
  var self = this;
  var options = {
    path : '/session',
    data : {
      desiredCapabilities : this.desiredCapabilities
    }
  };

  var request = new HttpRequest(options);
  request.on('success', function(data, response, isRedirect) {
    if (data && data.sessionId) {
      self.sessionId = self.api.sessionId = data.sessionId;
      if (data.value) {
        self.api.capabilities = data.value;
      }
      Logger.info('Got sessionId from selenium', self.sessionId);
      self.emit('selenium:session_create', self.sessionId, request, response);
    } else if (isRedirect) {
      self.followRedirect(request, response);
    } else {
      request.emit('error', data, null);
    }
  })
  .on('error', function(data, err) {
    if (self.options.output) {
      console.error('\n' + Logger.colors.light_red('Error retrieving a new session from the selenium server'));
    }

    if (typeof data == 'object' && Object.keys(data).length === 0) {
      data = '';
    }

    if (!data && err) {
      data = err;
    }

    self.emit('error', data);
  })
  .send();

  return this;
};

Nightwatch.prototype.followRedirect = function (request, response) {
  if (!response.headers || !response.headers.location) {
    this.emit('error', null, null);
    return this;
  }
  var url = require('url');
  var urlParts = url.parse(response.headers.location);
  request.setOptions({
    path   : urlParts.pathname,
    host   : urlParts.hostname,
    port   : urlParts.port,
    method : 'GET'
  }).send();

  return this;
};

exports = module.exports = {};

exports.client = function(options) {
  return new Nightwatch(options);
};

exports.cli = function(runTests) {
  var cli = require('./runner/cli/cli.js');
  cli.setup();

  var argv = cli.init();
  if (argv.help) {
    cli.showHelp();
  } else if (argv.version) {
    var packageConfig = require(__dirname + '/../package.json');
    console.log(packageConfig.name + ' v' + packageConfig.version);
  } else {
    if (typeof runTests != 'function') {
      throw new Error('Supplied argument needs to be a function!');
    }
    runTests(argv);
  }
};

exports.runner = function(argv, done, settings) {
  var runner = exports.CliRunner(argv);
  return runner.setup(settings, done).runTests(done);
};

exports.initGrunt = function(grunt) {
  grunt.registerMultiTask('nightwatch', 'run nightwatch.', function() {
    var done = this.async();
    var options = this.options();
    var settings = this.data && this.data.settings;
    var argv = this.data && this.data.argv;

    exports.cli(function(a) {
      Object.keys(argv).forEach(function(key) {
        if (key === 'env' && a['parallel-mode'] === true) {
          return;
        }
        a[key] = argv[key];
      });

      if (a.test) {
        a.test = path.resolve(a.test);
      }

      if (options.cwd) {
        process.chdir(options.cwd);
      }

      exports.runner(a, done, settings);
    });
  });
};

exports.CliRunner = function(argv) {
  var CliRunner = require('./runner/cli/clirunner.js');
  return new CliRunner(argv);
};

exports.initClient = function(opts) {
  var Manager = require('./runner/clientmanager.js');
  var instance = new Manager();
  return instance.init(opts);
};