api.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. /*!
  2. * Module dependencies.
  3. */
  4. var fs = require('fs');
  5. var path = require('path');
  6. var util = require('util');
  7. var events = require('events');
  8. var assertModule = require('assert');
  9. var CommandQueue = require('./queue.js');
  10. var Assertion = require('./assertion.js');
  11. var Page = require('../page-object/page.js');
  12. module.exports = new (function() {
  13. var client;
  14. var custom_commands_path;
  15. var custom_assertions_path;
  16. var page_objects_path;
  17. var assertOperators = {
  18. ok : ['ok', 'ko'],
  19. equal : ['==', '!='],
  20. notEqual : ['!=', '=='],
  21. deepEqual : ['deepEqual', 'not deepEqual'],
  22. notDeepEqual : ['not deepEqual', 'deepEqual'],
  23. strictEqual : ['===', '!=='],
  24. notStrictEqual : ['!==', '==='],
  25. throws : ['throws', 'doesNotThrow'],
  26. doesNotThrow : ['doesNotThrow', 'throws'],
  27. fail : 'fail',
  28. ifError : 'ifError'
  29. };
  30. /////////////////////////////////////////////////////////////////////
  31. // Assertions
  32. /////////////////////////////////////////////////////////////////////
  33. /**
  34. * Extends the node.js assert module
  35. *
  36. * @param prop
  37. * @param abortOnFailure
  38. * @returns {Function}
  39. */
  40. function makeAssertion(prop, abortOnFailure) {
  41. return function() {
  42. var passed;
  43. var expected = null;
  44. var actual = null;
  45. var lastArgument = arguments[arguments.length-1];
  46. var isLastArgString = typeof lastArgument === 'string';
  47. var message = isLastArgString &&
  48. (arguments.length > 2 || typeof arguments[0] === 'boolean') &&
  49. lastArgument || (typeof arguments[0] === 'function' && '[Function]');
  50. var args = Array.prototype.slice.call(arguments, 0);
  51. try {
  52. assertModule[prop].apply(null, arguments);
  53. passed = true;
  54. message = 'Passed [' + prop + ']: ' + (message || getAssertMessage(prop, args, passed));
  55. } catch (ex) {
  56. passed = false;
  57. message = 'Failed [' + prop + ']: ' + ('(' + ex.message + ')' || message || getAssertMessage(prop, args, passed));
  58. actual = ex.actual;
  59. expected = ex.expected;
  60. }
  61. return Assertion.assert(passed, actual, expected, message, abortOnFailure);
  62. };
  63. }
  64. function getAssertMessage(prop, args, passed) {
  65. if (!Array.isArray(assertOperators[prop])) {
  66. return assertOperators[prop] || '';
  67. }
  68. var operator = passed ? assertOperators[prop][0] : assertOperators[prop][1];
  69. if (args.length === 2) {
  70. args.splice(1, 0, operator);
  71. } else {
  72. args.push(operator);
  73. }
  74. args = args.map(function(argument) {
  75. if (argument && typeof argument == 'object') {
  76. argument = util.inspect(argument);
  77. }
  78. return argument;
  79. });
  80. return args.join(' ');
  81. }
  82. /**
  83. * Loads the available assertions
  84. */
  85. function loadAssertions(parent) {
  86. parent = parent || client.api;
  87. parent.assert = {};
  88. if (client.options.start_session) {
  89. parent.verify = {};
  90. }
  91. for (var prop in assertModule) {
  92. if (assertModule.hasOwnProperty(prop)) {
  93. parent.assert[prop] = (function(prop) {
  94. return makeAssertion(prop, true);
  95. })(prop);
  96. if (client.options.start_session) {
  97. parent.verify[prop] = (function (prop) {
  98. return makeAssertion(prop, false);
  99. })(prop);
  100. }
  101. }
  102. }
  103. if (client.options.start_session) {
  104. var dirPath = path.join(__dirname, './../api/assertions/');
  105. loadAssertionFiles(dirPath, parent.assert, true);
  106. loadAssertionFiles(dirPath, parent.verify, false);
  107. }
  108. }
  109. /**
  110. * Create an instance of an assertion
  111. *
  112. * @param {string} commandName
  113. * @param {function} assertionFn
  114. * @param {boolean} abortOnFailure
  115. * @param {object} parent
  116. * @returns {AssertionInstance}
  117. */
  118. function createAssertion(commandName, assertionFn, abortOnFailure, parent) {
  119. var assertion;
  120. if (typeof assertionFn === 'object' && assertionFn.assertion) {
  121. assertion = Assertion.factory(assertionFn.assertion, abortOnFailure, client);
  122. addCommand(commandName, assertion._commandFn, assertion, parent);
  123. return assertion;
  124. }
  125. // backwards compatibility
  126. var module = loadCommandModule(assertionFn, client.api, {
  127. abortOnFailure : abortOnFailure
  128. });
  129. addCommand(commandName, module.command, module.context, parent);
  130. return assertion;
  131. }
  132. /**
  133. * Loads the actual assertion files.
  134. *
  135. * @param {String} dirPath
  136. * @param {Object} parent
  137. * @param {Boolean} abortOnFailure
  138. */
  139. function loadAssertionFiles(dirPath, parent, abortOnFailure) {
  140. var commandFiles = fs.readdirSync(dirPath);
  141. for (var i = 0, len = commandFiles.length; i < len; i++) {
  142. if (path.extname(commandFiles[i]) === '.js') {
  143. var commandName = path.basename(commandFiles[i], '.js');
  144. var assertionFn = require(path.join(dirPath, commandFiles[i]));
  145. createAssertion(commandName, assertionFn, abortOnFailure, parent);
  146. }
  147. }
  148. }
  149. /////////////////////////////////////////////////////////////////////
  150. // Commands
  151. /////////////////////////////////////////////////////////////////////
  152. /**
  153. * Loads selenium protocol actions
  154. */
  155. function loadProtocolActions(parent) {
  156. parent = parent || client.api;
  157. var protocol = require('./../api/protocol.js')(client);
  158. var actions = Object.keys(protocol);
  159. actions.forEach(function(command) {
  160. addCommand(command, protocol[command], client.api, parent);
  161. });
  162. }
  163. /**
  164. * Loads all the composite commands defined by nightwatch
  165. */
  166. function loadAllCommands(parent) {
  167. loadElementCommands(parent);
  168. loadClientCommands(parent);
  169. loadCommandFiles(client.api, parent, true);
  170. }
  171. /**
  172. * Loads the element composite commands defined by nightwatch
  173. */
  174. function loadElementCommands(parent) {
  175. parent = parent || client.api;
  176. var elementCommands = require('./../api/element-commands.js')(client);
  177. var entries = Object.keys(elementCommands);
  178. entries.forEach(function(command) {
  179. addCommand(command, elementCommands[command], client.api, parent);
  180. });
  181. }
  182. /**
  183. * Loads all the client commands defined by nightwatch
  184. */
  185. function loadClientCommands(parent) {
  186. parent = parent || client.api;
  187. var clientCommands = require('./../api/client-commands.js')(client);
  188. var entries = Object.keys(clientCommands);
  189. entries.forEach(function(command) {
  190. addCommand(command, clientCommands[command], client.api, parent, true);
  191. });
  192. }
  193. /**
  194. * Loads the external commands
  195. */
  196. function loadCommandFiles(context, parent, shouldLoadClientCommands) {
  197. var relativePaths = ['./../api/element-commands/'];
  198. if (shouldLoadClientCommands) {
  199. relativePaths.push('./../api/client-commands/');
  200. }
  201. relativePaths.forEach(function(relativePath) {
  202. var commandFiles = fs.readdirSync(path.join(__dirname, relativePath));
  203. var commandName;
  204. var commandModule;
  205. for (var i = 0, len = commandFiles.length; i < len; i++) {
  206. var ext = path.extname(commandFiles[i]);
  207. commandName = path.basename(commandFiles[i], ext);
  208. if (ext === '.js' && commandName.substr(0, 1) !== '_') {
  209. commandModule = require(__dirname + relativePath + commandFiles[i]);
  210. var m = loadCommandModule(commandModule, context);
  211. addCommand(commandName, m.command, m.context, parent);
  212. }
  213. }
  214. });
  215. }
  216. /**
  217. * Loads a command module either specified as an object with a `command` method
  218. * or specified as a function which will be instantiated (new function() {..})
  219. *
  220. * @param {object|function} module
  221. * @param {object} context
  222. * @param {object} [addt_props]
  223. * @returns {{command: function, context: *}}
  224. */
  225. function loadCommandModule(module, context, addt_props, return_val) {
  226. var m = {command: null, context: context};
  227. function F() {
  228. if (typeof module === 'object') {
  229. events.EventEmitter.call(this);
  230. }
  231. if (addt_props) {
  232. for (var prop in addt_props) {
  233. if (addt_props.hasOwnProperty(prop)) {
  234. this[prop] = addt_props[prop];
  235. }
  236. }
  237. }
  238. this.client = client;
  239. this.api = client.api;
  240. if (typeof module === 'function') {
  241. module.call(this);
  242. }
  243. }
  244. if (typeof module === 'object' && module.command) {
  245. util.inherits(F, events.EventEmitter);
  246. F.prototype.command = function() {
  247. return module.command.apply(this, arguments);
  248. };
  249. } else if (typeof module === 'function') {
  250. F.prototype = Object.create(module.prototype);
  251. F.prototype.constructor = F;
  252. }
  253. m.command = function commandFn() {
  254. var instance = new F();
  255. if (typeof module === 'function') {
  256. context = m.context = instance;
  257. }
  258. instance.command.prototype.constructor.stackTrace = commandFn.stackTrace;
  259. instance.command.apply(context, arguments);
  260. return context;
  261. };
  262. return m;
  263. }
  264. /**
  265. * Loads custom commands defined by the user
  266. * @param {string} [dirPath]
  267. * @param {object} [parent]
  268. */
  269. function loadCustomCommands(dirPath, parent) {
  270. if (!custom_commands_path && !dirPath) {
  271. return;
  272. }
  273. dirPath = dirPath || custom_commands_path;
  274. parent = parent || client.api;
  275. if (Array.isArray(dirPath)) {
  276. dirPath.forEach(function(folder) {
  277. loadCustomCommands(folder, parent);
  278. });
  279. return;
  280. }
  281. var absPath = path.resolve(dirPath);
  282. var commandFiles = fs.readdirSync(absPath);
  283. commandFiles.forEach(function(file) {
  284. var fullPath = path.join(absPath, file);
  285. if (fs.lstatSync(fullPath).isDirectory()) {
  286. parent[file] = parent[file] || {};
  287. var pathFolder = path.join(dirPath, file);
  288. loadCustomCommands(pathFolder, parent[file]);
  289. } else if (path.extname(file) === '.js') {
  290. var commandModule = require(fullPath);
  291. var name = path.basename(file, '.js');
  292. if (!commandModule) {
  293. throw new Error('Module ' + file + 'should have a public method or function.');
  294. }
  295. var m = loadCommandModule(commandModule, client.api);
  296. addCommand(name, m.command, m.context, parent, true);
  297. }
  298. });
  299. }
  300. /**
  301. * Loads custom assertions, similarly to custom commands
  302. * @param [folder]
  303. */
  304. function loadCustomAssertions(folder, parent) {
  305. folder = folder || custom_assertions_path;
  306. parent = parent || client.api;
  307. if (!custom_assertions_path) {
  308. return;
  309. }
  310. if (Array.isArray(folder)) {
  311. folder.forEach(function(folderName) {
  312. loadCustomAssertions(folderName, parent);
  313. });
  314. return;
  315. }
  316. loadCustomAssertionFolder(folder, parent);
  317. }
  318. function loadCustomAssertionFolder(folderName, parent) {
  319. var absPath = path.resolve(folderName);
  320. loadAssertionFiles(absPath, parent.assert, true);
  321. loadAssertionFiles(absPath, parent.verify, false);
  322. }
  323. function loadExpectAssertions(parent) {
  324. parent = parent || client.api;
  325. var Expect = require('../api/expect.js')(client);
  326. var assertions = Object.keys(Expect);
  327. try {
  328. var chaiExpect = module.require('chai').expect;
  329. parent.expect = function() {
  330. return chaiExpect.apply(chaiExpect, arguments);
  331. };
  332. } catch (err) {
  333. parent.expect = {};
  334. }
  335. assertions.forEach(function(assertion) {
  336. parent.expect[assertion] = function() {
  337. var args = Array.prototype.slice.call(arguments);
  338. var command = Expect[assertion].apply(parent, args);
  339. function F(element) {
  340. events.EventEmitter.call(this);
  341. this.client = client;
  342. this.element = element;
  343. }
  344. util.inherits(F, events.EventEmitter);
  345. F.prototype.command = function commandFn() {
  346. this.element._stackTrace = commandFn.stackTrace;
  347. this.element.locate(this);
  348. return this;
  349. };
  350. var instance = new F(command.element);
  351. var err = new Error;
  352. Error.captureStackTrace(err, arguments.callee);
  353. CommandQueue.add(assertion, instance.command, instance, [], err.stack);
  354. return command.expect;
  355. };
  356. });
  357. }
  358. /**
  359. * Loads page object files
  360. * @param {string} [dirPath]
  361. */
  362. function loadPageObjects(dirPath, parent) {
  363. if (!page_objects_path && !dirPath) {
  364. return;
  365. }
  366. dirPath = dirPath || page_objects_path;
  367. client.api.page = client.api.page || {};
  368. parent = parent || client.api.page;
  369. if (Array.isArray(dirPath)) {
  370. dirPath.forEach(function(folder) {
  371. loadPageObjects(folder);
  372. });
  373. return;
  374. }
  375. var absPath = path.resolve(dirPath);
  376. var pageFiles = fs.readdirSync(absPath);
  377. pageFiles.forEach(function(file) {
  378. var fullPath = path.join(absPath, file);
  379. if (fs.lstatSync(fullPath).isDirectory()) {
  380. parent[file] = parent[file] || {};
  381. var pathFolder = path.join(dirPath, file);
  382. loadPageObjects(pathFolder, parent[file]);
  383. } else if (path.extname(file) === '.js') {
  384. var pageName = path.basename(file, '.js');
  385. var pageFnOrObject = require(path.join(absPath, file));
  386. addPageObject(pageName, pageFnOrObject, client.api, parent);
  387. }
  388. });
  389. }
  390. /**
  391. * Instantiates the page object class
  392. * @param {String} name
  393. * @param {Object} pageFnOrObject
  394. * @param {Object} context
  395. * @param {Object} parent
  396. */
  397. function addPageObject(name, pageFnOrObject, context, parent) {
  398. parent[name] = function() {
  399. var args = Array.prototype.slice.call(arguments);
  400. args.unshift(context);
  401. if (useEnhancedModel(pageFnOrObject)) {
  402. var loadOntoPageObject = function(parent) {
  403. if (client.options.start_session) {
  404. loadElementCommands(parent);
  405. loadCommandFiles(client.api, parent, false);
  406. loadExpectAssertions(parent);
  407. // Alias
  408. parent.expect.section = parent.expect.element;
  409. }
  410. loadAssertions(parent);
  411. loadCustomCommands(null, parent);
  412. loadCustomAssertions(null, parent);
  413. return parent;
  414. };
  415. pageFnOrObject.name = name;
  416. return new Page(pageFnOrObject, loadOntoPageObject, context, client);
  417. }
  418. return new (function() {
  419. if (typeof pageFnOrObject == 'function') {
  420. return createPageObject(pageFnOrObject, args);
  421. }
  422. return pageFnOrObject;
  423. })();
  424. };
  425. }
  426. function useEnhancedModel(pageFnOrObject) {
  427. return typeof pageFnOrObject == 'object' && (pageFnOrObject.elements || pageFnOrObject.sections);
  428. }
  429. /**
  430. *
  431. * @param pageFnOrObject
  432. * @param args
  433. * @returns {Object}
  434. */
  435. function createPageObject(pageFnOrObject, args) {
  436. function PageObject() {
  437. return pageFnOrObject.apply(this, args);
  438. }
  439. PageObject.prototype = pageFnOrObject.prototype;
  440. return new PageObject();
  441. }
  442. /**
  443. * Adds a command/assertion to the queue.
  444. *
  445. * @param {String} name
  446. * @param {Object} command
  447. * @param {Object} context
  448. * @param {Object} [parent]
  449. */
  450. function addCommand(name, command, context, parent) {
  451. parent = parent || client.api;
  452. if (parent[name]) {
  453. client.results.errors++;
  454. var error = new Error('The command "' + name + '" is already defined!');
  455. client.errors.push(error.stack);
  456. throw error;
  457. }
  458. parent[name] = function commandFn() {
  459. var args = Array.prototype.slice.call(arguments);
  460. var originalStackTrace;
  461. if (commandFn.stackTrace) {
  462. originalStackTrace = commandFn.stackTrace;
  463. } else {
  464. var err = new Error;
  465. Error.captureStackTrace(err, arguments.callee);
  466. originalStackTrace = err.stack;
  467. }
  468. CommandQueue.add(name, command, context, args, originalStackTrace);
  469. return client.api; // for chaining
  470. };
  471. }
  472. /**
  473. * Initialize the api
  474. *
  475. * @param {Object} c The nightwatch client instance
  476. * @api public
  477. */
  478. this.init = function(c) {
  479. client = c;
  480. custom_commands_path = c.options.custom_commands_path;
  481. custom_assertions_path = c.options.custom_assertions_path;
  482. page_objects_path = c.options.page_objects_path;
  483. return this;
  484. };
  485. /**
  486. * Loads everything
  487. */
  488. this.load = function() {
  489. if (client.options.start_session) {
  490. loadProtocolActions();
  491. loadAllCommands();
  492. loadPageObjects();
  493. loadExpectAssertions();
  494. }
  495. loadAssertions();
  496. loadCustomCommands();
  497. loadCustomAssertions();
  498. return this;
  499. };
  500. this.addCommand = addCommand;
  501. this.loadCustomCommands = loadCustomCommands;
  502. this.loadCustomAssertions = loadCustomAssertions;
  503. this.loadPageObjects = loadPageObjects;
  504. this.createAssertion = createAssertion;
  505. })();