PageRenderTime 59ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/node_modules/eyes.protractor/node_modules/eyes.sdk/src/ServerConnector.js

https://gitlab.com/prashanth-sams/protractortesting
JavaScript | 210 lines | 123 code | 14 blank | 73 comment | 11 complexity | d5ff1b18b65931698d4e7ddd88321df7 MD5 | raw file
  1. /*
  2. ---
  3. name: ServerConnector
  4. description: Provides an API for communication with the Applitools server.
  5. provides: [ServerConnector]
  6. requires: [GeneralUtils]
  7. ---
  8. */
  9. (function () {
  10. "use strict";
  11. var GeneralUtils = require('eyes.utils').GeneralUtils,
  12. restler = require('restler'),
  13. fs = require('fs');
  14. // Constants
  15. var CONNECTION_TIMEOUT_MS = 5 * 60 * 1000,
  16. DEFAULT_HEADERS = {'Accept': 'application/json', 'Content-Type': 'application/json'},
  17. SERVER_SUFFIX = '/api/sessions/running';
  18. /**
  19. *
  20. * @param {PromiseFactory} promiseFactory An object which will be used for creating deferreds/promises.
  21. * @param {String} serverUri
  22. * @param {Object} logger
  23. * @constructor
  24. **/
  25. function ServerConnector(promiseFactory, serverUri, logger) {
  26. this._promiseFactory = promiseFactory;
  27. this._logger = logger;
  28. this._serverUri = GeneralUtils.urlConcat(serverUri, SERVER_SUFFIX);
  29. this._httpOptions = {
  30. rejectUnauthorized: false,
  31. headers: DEFAULT_HEADERS,
  32. timeout: CONNECTION_TIMEOUT_MS,
  33. query: {}
  34. };
  35. }
  36. /**
  37. * Sets the API key of your applitools Eyes account.
  38. *
  39. * @param apiKey {String} The api key to be used.
  40. */
  41. ServerConnector.prototype.setApiKey = function (apiKey) {
  42. this._httpOptions.query.apiKey = apiKey;
  43. };
  44. /**
  45. *
  46. * @return {String} The currently set API key.
  47. */
  48. ServerConnector.prototype.getApiKey = function () {
  49. return this._httpOptions.query.apiKey;
  50. };
  51. /**
  52. *
  53. * Starts a new running session in the server. Based on the given parameters,
  54. * this running session will either be linked to an existing session, or to
  55. * a completely new session.
  56. *
  57. * @method startSession
  58. * @param {Object} sessionStartInfo - The start parameters for the session.
  59. * @return {Object} Promise with a resolve result that represents the current running session.
  60. *
  61. **/
  62. ServerConnector.prototype.startSession = function (sessionStartInfo) {
  63. this._logger.verbose('ServerConnector.startSession called with:', sessionStartInfo);
  64. return this._promiseFactory.makePromise(function (resolve, reject) {
  65. this._logger.verbose('ServerConnector.startSession will now post call');
  66. restler.postJson(this._serverUri, {startInfo: sessionStartInfo}, this._httpOptions)
  67. .on('complete', function (data, response) {
  68. if (!response) {
  69. this._logger.verbose('ServerConnector.startSession - got empty response!');
  70. reject(new Error(response));
  71. return;
  72. }
  73. this._logger.verbose('ServerConnector.startSession - start session result', data,
  74. 'status code ', response.statusCode);
  75. if (response.statusCode === 200 || response.statusCode === 201) {
  76. this._logger.verbose('ServerConnector.startSession - post succeeded');
  77. resolve({sessionId: data.id, sessionUrl: data.url,
  78. isNewSession: response.statusCode === 201});
  79. } else {
  80. this._logger.log('ServerConnector.startSession - post failed');
  81. reject(new Error(response));
  82. }
  83. }.bind(this));
  84. }.bind(this));
  85. };
  86. /**
  87. *
  88. * Ends a running session in the server. Session results are received from the server.
  89. *
  90. * @method endSession
  91. * @param {Object} runningSession - The session to end.
  92. * @param {Object} isAborted.
  93. * @param {Object} save - Save the session.
  94. * @return {Object} Promise with a resolve result that represents the test results.
  95. *
  96. **/
  97. ServerConnector.prototype.endSession = function (runningSession, isAborted, save) {
  98. this._logger.verbose('ServerConnector.endSession called with isAborted:', isAborted,
  99. ', save:', save, 'for session:', runningSession);
  100. return this._promiseFactory.makePromise(function (resolve, reject) {
  101. var data = {aborted: isAborted, updateBaseline: save};
  102. var url = GeneralUtils.urlConcat(this._serverUri, runningSession.sessionId.toString());
  103. this._logger.verbose("ServerConnector.endSession will now post:", data, "to:", url);
  104. restler.json(url, data, this._httpOptions, 'DELETE')
  105. .on('complete', function (data, response) {
  106. this._logger.verbose('ServerConnector.endSession result', data, 'status code', response.statusCode);
  107. if (response.statusCode === 200 || response.statusCode === 201) {
  108. resolve({
  109. steps: data.steps,
  110. matches: data.matches,
  111. mismatches: data.mismatches,
  112. missing: data.missing,
  113. exactMatches: data.exactMatches,
  114. strictMatches: data.strictMatches,
  115. contentMatches: data.contentMatches,
  116. layoutMatches: data.layoutMatches,
  117. noneMatches: data.noneMatches
  118. });
  119. } else {
  120. reject(new Error("error on server connector endSession"));
  121. }
  122. }.bind(this));
  123. }.bind(this));
  124. };
  125. /**
  126. * Creates a bytes representation of the given JSON.
  127. * @param {object} jsonData The data from for which to create the bytes representation.
  128. * @return {Buffer} a buffer of bytes which represents the stringified JSON, prefixed with size.
  129. * @private
  130. */
  131. function _createDataBytes(jsonData) {
  132. var dataStr = JSON.stringify(jsonData);
  133. var dataLen = Buffer.byteLength(dataStr, 'utf8');
  134. // The result buffer will contain the length of the data + 4 bytes of size
  135. var result = new Buffer(dataLen + 4);
  136. result.writeUInt32BE(dataLen, 0);
  137. result.write(dataStr, 4, dataLen);
  138. return result;
  139. }
  140. ServerConnector.prototype.matchWindow = function (runningSession, matchWindowData, screenshot) {
  141. return this._promiseFactory.makePromise(function (resolve, reject) {
  142. var url = GeneralUtils.urlConcat(this._serverUri, runningSession.sessionId.toString());
  143. var options = Object.create(this._httpOptions);
  144. options.headers = Object.create(this._httpOptions.headers);
  145. // TODO Daniel - Use binary image instead of base64 (see line below)
  146. //options.headers['Content-Type'] = 'application/octet-stream';
  147. //options.data = Buffer.concat([_createDataBytes(matchWindowData), screenshot]).toString('binary');
  148. this._logger.verbose("ServerConnector.matchWindow will now post to:", url);
  149. restler.postJson(url, matchWindowData, options)
  150. .on('complete', function (data, response) {
  151. this._logger.verbose('ServerConnector.matchWindow result', data,
  152. 'status code', response.statusCode);
  153. if (response.statusCode === 200) {
  154. resolve({asExpected: data.asExpected});
  155. } else {
  156. reject(new Error(response));
  157. }
  158. }.bind(this));
  159. }.bind(this));
  160. };
  161. //noinspection JSValidateJSDoc
  162. /**
  163. * Replaces an actual image in the current running session.
  164. * @param {object} runningSession The currently running session.
  165. * @param {number} stepIndex The zero based index of the step in which to replace the actual image.
  166. * @param {object} replaceWindowData The updated window data (similar to matchWindowData only without ignoreMismatch).
  167. * @param {Buffer} screenshot The PNG bytes of the updated image.
  168. * @return {Promise} A promise which resolves when replacing is done, or rejects on error.
  169. */
  170. ServerConnector.prototype.replaceWindow = function (runningSession, stepIndex, replaceWindowData, screenshot) {
  171. return this._promiseFactory.makePromise(function (resolve, reject) {
  172. var url = GeneralUtils.urlConcat(this._serverUri, runningSession.sessionId.toString() + '/' + stepIndex);
  173. var options = Object.create(this._httpOptions);
  174. options.headers = Object.create(this._httpOptions.headers);
  175. // TODO Daniel - Use binary image instead of base64 (see line below)
  176. //options.headers['Content-Type'] = 'application/octet-stream';
  177. //options.data = Buffer.concat([_createDataBytes(matchWindowData), screenshot]).toString('binary');
  178. this._logger.verbose("ServerConnector.replaceWindow will now post to:", url);
  179. restler.putJson(url, replaceWindowData, options)
  180. .on('complete', function (data, response) {
  181. this._logger.verbose('ServerConnector.replaceWindow result', data,
  182. 'status code', response.statusCode);
  183. if (response.statusCode === 200) {
  184. resolve();
  185. } else {
  186. reject(new Error(response));
  187. }
  188. }.bind(this));
  189. }.bind(this));
  190. };
  191. module.exports = ServerConnector;
  192. }());