assertion.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. var util = require('util');
  2. var events = require('events');
  3. var Logger = require('./../util/logger.js');
  4. var Utils = require('./../util/utils.js');
  5. module.exports = new (function() {
  6. var doneSymbol = Utils.symbols.ok;
  7. var failSymbol = Utils.symbols.fail;
  8. var initialized = false;
  9. var client;
  10. /**
  11. * Abstract assertion class that will subclass all defined assertions
  12. *
  13. * All assertions must implement the following api:
  14. *
  15. * - @type {boolean|function}
  16. * expected
  17. * - @type {string}
  18. * message
  19. * - @type {function}
  20. * pass
  21. * - @type {function}
  22. * value
  23. * - @type {function}
  24. * command
  25. * - @type {function} - Optional
  26. * failure
  27. *
  28. * @param {boolean} abortOnFailure
  29. * @param {Nightwatch} client
  30. * @constructor
  31. */
  32. function BaseAssertion(abortOnFailure, client) {
  33. events.EventEmitter.call(this);
  34. this.abortOnFailure = abortOnFailure;
  35. this.client = client;
  36. this.api = client.api;
  37. this.startTime = new Date().getTime();
  38. this.globals = this.api.globals || {};
  39. this.timeout = this.globals.retryAssertionTimeout || 0; //ms
  40. this.rescheduleInterval = this.globals.waitForConditionPollInterval || 500; //ms
  41. this.shouldRetry = this.timeout > 0;
  42. }
  43. util.inherits(BaseAssertion, events.EventEmitter);
  44. BaseAssertion.prototype.complete = function() {
  45. var self = this, args = Array.prototype.slice.call(arguments, 0);
  46. args.unshift('complete');
  47. setImmediate(function() {
  48. self.emit.apply(self, args);
  49. });
  50. };
  51. /**
  52. * Performs the command method
  53. * @returns {*}
  54. * @private
  55. */
  56. BaseAssertion.prototype._executeCommand = function() {
  57. var self = this;
  58. var methods = [
  59. 'expected',
  60. 'message',
  61. ['pass'],
  62. ['value'],
  63. ['command']
  64. ];
  65. methods.forEach(function(method) {
  66. if (Array.isArray(method)) {
  67. var name = method[0];
  68. if (typeof self[name] !== 'function') {
  69. throw new Error('Assertion must implement method ' + name);
  70. }
  71. } else if (typeof self[method] == 'undefined') {
  72. throw new Error('Assertion must implement method/property ' + method);
  73. }
  74. });
  75. return this._scheduleAssertion();
  76. };
  77. BaseAssertion.prototype._scheduleAssertion = function() {
  78. var self = this;
  79. return this.command(function(result) {
  80. var passed, value;
  81. if (typeof self.failure == 'function' && self.failure(result)) {
  82. passed = false;
  83. value = null;
  84. } else {
  85. value = self.value(result);
  86. passed = self.pass(value);
  87. }
  88. var timeSpent = new Date().getTime() - self.startTime;
  89. if (!passed && timeSpent < self.timeout) {
  90. return self._reschedule();
  91. }
  92. var expected = typeof self.expected == 'function' ? self.expected() : self.expected;
  93. var message = self._getFullMessage(passed, timeSpent);
  94. self.client.assertion(passed, value, expected, message, self.abortOnFailure, self._stackTrace);
  95. self.emit('complete');
  96. });
  97. };
  98. BaseAssertion.prototype._getFullMessage = function(passed, timeSpent) {
  99. if ( !this.shouldRetry) {
  100. return this.message;
  101. }
  102. var timeLogged = passed ? timeSpent : this.timeout;
  103. return this.message + ' after ' + timeLogged + ' milliseconds.';
  104. };
  105. BaseAssertion.prototype._reschedule = function() {
  106. setTimeout(function(){}, this.rescheduleInterval);
  107. return this._scheduleAssertion();
  108. };
  109. /**
  110. *
  111. * @param {string} stackTrace
  112. * @param {string|null} message
  113. */
  114. function buildStackTrace(stackTrace, message) {
  115. var stackParts = stackTrace.split('\n');
  116. stackParts.shift();
  117. if (message) {
  118. stackParts.unshift(message);
  119. }
  120. return Utils.stackTraceFilter(stackParts);
  121. }
  122. /**
  123. * Assertion factory that creates the assertion instances with the supplied assertion definition
  124. * and options
  125. *
  126. * @param {function} assertionFn
  127. * @param {boolean} abortOnFailure
  128. * @param {Nightwatch} client
  129. * @constructor
  130. */
  131. function AssertionInstance(assertionFn, abortOnFailure, client) {
  132. this.abortOnFailure = abortOnFailure;
  133. this.client = client;
  134. this.assertionFn = assertionFn;
  135. }
  136. /**
  137. * This will call the supplied constructor of the assertion, after calling the Base constructor
  138. * first with other arguments and then inherits the rest of the methods from BaseAssertion
  139. *
  140. * @param {function} constructor
  141. * @param {Array} args
  142. * @returns {*}
  143. * @private
  144. */
  145. AssertionInstance.prototype._constructFromSuper = function(constructor, args) {
  146. var self = this;
  147. function F() {
  148. BaseAssertion.apply(this, [self.abortOnFailure, self.client]);
  149. return constructor.apply(this, args);
  150. }
  151. util.inherits(constructor, BaseAssertion);
  152. F.prototype = constructor.prototype;
  153. return new F();
  154. };
  155. AssertionInstance.prototype._commandFn = function commandFn() {
  156. var args = Array.prototype.slice.call(arguments, 0);
  157. var instance = this._constructFromSuper(this.assertionFn, args);
  158. instance._stackTrace = commandFn.stackTrace;
  159. return instance._executeCommand();
  160. };
  161. /**
  162. * @public
  163. * @param {function} assertionFn
  164. * @param {boolean} abortOnFailure
  165. * @param {Nightwatch} client
  166. * @returns {AssertionInstance}
  167. */
  168. this.factory = function(assertionFn, abortOnFailure, client) {
  169. return new AssertionInstance(assertionFn, abortOnFailure, client);
  170. };
  171. /**
  172. * Performs an assertion
  173. *
  174. * @param {Boolean} passed
  175. * @param {Object} receivedValue
  176. * @param {Object} expectedValue
  177. * @param {String} message
  178. * @param {Boolean} abortOnFailure
  179. * @param {String} originalStackTrace
  180. */
  181. this.assert = function assert(passed, receivedValue, expectedValue, message, abortOnFailure, originalStackTrace) {
  182. if (!initialized) {
  183. throw new Error('init must be called first.');
  184. }
  185. var failure = '';
  186. var stacktrace = '';
  187. var fullMsg = '';
  188. if (passed) {
  189. if (client.options.output && client.options.detailed_output) {
  190. console.log(' ' + Logger.colors.green(doneSymbol) + ' ' + message);
  191. }
  192. client.results.passed++;
  193. } else {
  194. failure = 'Expected "' + expectedValue + '" but got: "' + receivedValue + '"';
  195. var err = new Error();
  196. err.name = message;
  197. err.message = message + ' - ' + failure;
  198. if (!originalStackTrace) {
  199. Error.captureStackTrace(err, arguments.callee);
  200. originalStackTrace = err.stack;
  201. }
  202. err.stack = buildStackTrace(originalStackTrace, client.options.start_session ? null : 'AssertionError: ' + message);
  203. fullMsg = message;
  204. if (client.options.output && client.options.detailed_output) {
  205. var logged = ' ' + Logger.colors.red(failSymbol);
  206. if (typeof expectedValue != 'undefined' && typeof receivedValue != 'undefined') {
  207. fullMsg += ' ' + Logger.colors.white(' - expected ' + Logger.colors.green('"' +
  208. expectedValue + '"')) + ' but got: ' + Logger.colors.red('"' + receivedValue + '"');
  209. }
  210. logged += ' ' + fullMsg;
  211. console.log(logged);
  212. }
  213. stacktrace = err.stack;
  214. if (client.options.output && client.options.detailed_output) {
  215. var parts = stacktrace.split('\n');
  216. console.log(Logger.colors.stack_trace(parts.join('\n')) + '\n');
  217. }
  218. client.results.lastError = err;
  219. client.results.failed++;
  220. }
  221. client.results.tests.push({
  222. message : message,
  223. stackTrace : stacktrace,
  224. fullMsg : fullMsg,
  225. failure : failure !== '' ? failure : false
  226. });
  227. if (!passed && abortOnFailure) {
  228. client.terminate(true);
  229. }
  230. };
  231. /**
  232. * Initializer
  233. *
  234. * @param {Object} c Nightwatch client instance
  235. */
  236. this.init = function(c) {
  237. client = c;
  238. initialized = true;
  239. };
  240. })();