Best JavaScript code snippet using mocha
connection.js
Source:connection.js
...99 conn.registerHandshakeCmd(resolve, reject);100 });101 case Status.CLOSING:102 case Status.CLOSED:103 const err = Errors.createFatalError('Connection closed', Errors.ER_CONNECTION_ALREADY_CLOSED, this.info);104 if (this.opts.logger.error) this.opts.logger.error(err);105 return Promise.reject(err);106 case Status.CONNECTING:107 case Status.AUTHENTICATING:108 const errAuth = Errors.createFatalError(109 'Connection is already connecting',110 Errors.ER_ALREADY_CONNECTING,111 this.info112 );113 if (this.opts.logger.error) this.opts.logger.error(errAuth);114 return Promise.reject(errAuth);115 }116 //status Connected117 return Promise.resolve(this);118 }119 executePromise(values, cmdOpts, prepare, resolve, reject) {120 const cmd = new Execute(121 resolve,122 function (err) {123 if (this.opts.logger.error) this.opts.logger.error(err);124 reject(err);125 }.bind(this),126 cmdOpts,127 this.opts,128 prepare,129 values130 );131 if (this.opts.trace) Error.captureStackTrace(cmd);132 this.addCommand(cmd);133 }134 batch(_sql, _options, _values) {135 if (!_sql) {136 const err = Errors.createError('sql parameter is mandatory', Errors.ER_UNDEFINED_SQL, this.info, 'HY000');137 if (this.opts.logger.error) this.opts.logger.error(err);138 return Promise.reject(err);139 }140 if (!_values) {141 const err = Errors.createError(142 'Batch must have values set',143 Errors.ER_BATCH_WITH_NO_VALUES,144 this.info,145 'HY000',146 _sql147 );148 if (this.opts.logger.error) this.opts.logger.error(err);149 return Promise.reject(err);150 }151 return new Promise(this.prepare.bind(this, _options, _sql, this.executePromise.bind(this))).then((prepare) => {152 const usePlaceHolder = (_options && _options.namedPlaceholders) || this.opts.namedPlaceholders;153 let vals;154 if (Array.isArray(_values)) {155 if (usePlaceHolder) {156 vals = _values;157 } else if (Array.isArray(_values[0])) {158 vals = _values;159 } else if (prepare.parameters.length === 1) {160 vals = [];161 for (let i = 0; i < _values.length; i++) {162 vals.push([_values[i]]);163 }164 } else {165 vals = [_values];166 }167 } else {168 vals = [[_values]];169 }170 let useBulk = this._canUseBulk(vals, _options);171 if (useBulk) {172 return new Promise(this.executeBulkPromise.bind(this, vals, _options, prepare));173 } else {174 const executes = [];175 for (let i = 0; i < vals.length; i++) {176 executes.push(prepare.execute(vals[i], _options));177 }178 return Promise.all(executes).then(179 function (res) {180 prepare.close();181 if (_options && _options.fullResult) {182 return Promise.resolve(res);183 } else {184 // aggregate results185 const firstResult = res[0];186 if (firstResult instanceof OkPacket) {187 let affectedRows = 0;188 const insertId = firstResult.insertId;189 const warningStatus = firstResult.warningStatus;190 for (let i = 0; i < res.length; i++) {191 affectedRows += res[i].affectedRows;192 }193 return Promise.resolve(new OkPacket(affectedRows, insertId, warningStatus));194 } else {195 // results have result-set. example :'INSERT ... RETURNING'196 // aggregate results197 const rs = [];198 rs.meta = res.meta;199 res.forEach((row) => {200 Array.prototype.push.apply(rs, row);201 });202 rs.meta = res.meta;203 return Promise.resolve(rs);204 }205 return;206 }207 }.bind(this)208 );209 }210 });211 }212 executeBulkPromise(values, cmdOpts, prepare, resolve, reject) {213 const cmd = new BatchBulk(214 (res) => {215 prepare.close();216 return resolve(res);217 },218 function (err) {219 if (this.opts.logger.error) this.opts.logger.error(err);220 reject(err);221 }.bind(this),222 cmdOpts,223 this.opts,224 prepare,225 values226 );227 if (this.opts.trace) Error.captureStackTrace(cmd);228 this.addCommand(cmd);229 }230 /**231 * Send an empty MySQL packet to ensure connection is active, and reset @@wait_timeout232 * @param timeout (optional) timeout value in ms. If reached, throw error and close connection233 */234 ping(timeout, resolve, reject) {235 if (timeout) {236 if (timeout < 0) {237 const err = Errors.createError(238 'Ping cannot have negative timeout value',239 Errors.ER_BAD_PARAMETER_VALUE,240 this.info,241 '0A000'242 );243 if (this.opts.logger.error) this.opts.logger.error(err);244 reject(err);245 return;246 }247 let tOut = setTimeout(248 function () {249 tOut = undefined;250 const err = Errors.createFatalError('Ping timeout', Errors.ER_PING_TIMEOUT, this.info, '0A000');251 if (this.opts.logger.error) this.opts.logger.error(err);252 // close connection253 this.addCommand = this.addCommandDisabled;254 clearTimeout(this.timeout);255 if (this.status !== Status.CLOSING && this.status !== Status.CLOSED) {256 this.sendQueue.clear();257 this.status = Status.CLOSED;258 this.socket.destroy();259 }260 this.clear();261 reject(err);262 }.bind(this),263 timeout264 );265 this.addCommand(266 new Ping(267 () => {268 if (tOut) {269 clearTimeout(tOut);270 resolve();271 }272 },273 (err) => {274 if (this.opts.logger.error) this.opts.logger.error(err);275 clearTimeout(tOut);276 reject(err);277 }278 )279 );280 return;281 }282 this.addCommand(new Ping(resolve, reject));283 }284 /**285 * Send a reset command that will286 * - rollback any open transaction287 * - reset transaction isolation level288 * - reset session variables289 * - delete user variables290 * - remove temporary tables291 * - remove all PREPARE statement292 *293 * @returns {Promise} promise294 */295 reset(resolve, reject) {296 if (297 (this.info.isMariaDB() && this.info.hasMinVersion(10, 2, 4)) ||298 (!this.info.isMariaDB() && this.info.hasMinVersion(5, 7, 3))299 ) {300 const resetCmd = new Reset(resolve, reject);301 this.addCommand(resetCmd);302 return;303 }304 const err = new Error(305 `Reset command not permitted for server ${this.info.serverVersion.raw} (requires server MariaDB version 10.2.4+ or MySQL 5.7.3+)`306 );307 if (this.opts.logger.error) this.opts.logger.error(err);308 reject(err);309 }310 /**311 * Indicates the state of the connection as the driver knows it312 * @returns {boolean}313 */314 isValid() {315 return this.status === Status.CONNECTED;316 }317 /**318 * Terminate connection gracefully.319 */320 end(resolve, reject) {321 this.addCommand = this.addCommandDisabled;322 clearTimeout(this.timeout);323 if (this.status < Status.CLOSING && this.status !== Status.NOT_CONNECTED) {324 this.status = Status.CLOSING;325 const ended = () => {326 this.status = Status.CLOSED;327 this.socket.destroy();328 this.socket.unref();329 this.clear();330 this.receiveQueue.clear();331 resolve();332 };333 const quitCmd = new Quit(ended, ended);334 this.sendQueue.push(quitCmd);335 this.receiveQueue.push(quitCmd);336 if (this.sendQueue.length === 1) {337 process.nextTick(this.nextSendCmd.bind(this));338 }339 } else resolve();340 }341 /**342 * Force connection termination by closing the underlying socket and killing server process if any.343 */344 destroy() {345 this.addCommand = this.addCommandDisabled;346 clearTimeout(this.timeout);347 if (this.status < Status.CLOSING) {348 this.status = Status.CLOSING;349 this.sendQueue.clear();350 if (this.receiveQueue.length > 0) {351 //socket is closed, but server may still be processing a huge select352 //only possibility is to kill process by another thread353 //TODO reuse a pool connection to avoid connection creation354 const self = this;355 const killCon = new Connection(this.opts);356 killCon357 .connect()358 .then(function () {359 //*************************************************360 //kill connection361 //*************************************************362 const killResHandler = function (err) {363 const destroyError = Errors.createFatalError(364 'Connection destroyed, command was killed',365 Errors.ER_CMD_NOT_EXECUTED_DESTROYED,366 self.info367 );368 if (self.opts.logger.error) self.opts.logger.error(destroyError);369 self.socketErrorDispatchToQueries(destroyError);370 if (self.socket) process.nextTick(self.socket.destroy());371 self.status = Status.CLOSED;372 new Promise(killCon.end.bind(killCon)).catch(() => {});373 };374 new Promise(killCon.query.bind(killCon, null, `KILL ${self.info.threadId}`, undefined)).finally(375 killResHandler376 );377 })378 .catch((err) => {379 //*************************************************380 //failing to create a kill connection, end normally381 //*************************************************382 const ended = () => {383 let sock = self.socket;384 self.clear();385 self.status = Status.CLOSED;386 setImmediate(resolve);387 sock.destroy();388 self.receiveQueue.clear();389 };390 const quitCmd = new Quit(ended, ended);391 self.sendQueue.push(quitCmd);392 self.receiveQueue.push(quitCmd);393 if (self.sendQueue.length === 1) {394 process.nextTick(self.nextSendCmd.bind(self));395 }396 });397 } else {398 this.status = Status.CLOSED;399 this.socket.destroy();400 }401 }402 this.clear();403 }404 pause() {405 this.socket.pause();406 }407 resume() {408 this.socket.resume();409 }410 format(sql, values) {411 const err = Errors.createError(412 '"Connection.format intentionally not implemented. please use Connection.query(sql, values), it will be more secure and faster',413 Errors.ER_NOT_IMPLEMENTED_FORMAT,414 this.info,415 '0A000'416 );417 if (this.opts.logger.error) this.opts.logger.error(err);418 throw err;419 }420 //*****************************************************************421 // additional public methods422 //*****************************************************************423 /**424 * return current connected server version information.425 *426 * @returns {*}427 */428 serverVersion() {429 if (!this.info.serverVersion) {430 const err = new Error('cannot know if server information until connection is established');431 if (this.opts.logger.error) this.opts.logger.error(err);432 throw err;433 }434 return this.info.serverVersion.raw;435 }436 /**437 * Change option "debug" during connection.438 * @param val debug value439 */440 debug(val) {441 if (typeof val === 'boolean') {442 if (val && !this.opts.logger.network) this.opts.logger.network = console.log;443 } else if (typeof val === 'function') {444 this.opts.logger.network = val;445 }446 this.opts.emit('debug', val);447 }448 debugCompress(val) {449 if (val) {450 if (typeof val === 'boolean') {451 this.opts.debugCompress = val;452 if (val && !this.opts.logger.network) this.opts.logger.network = console.log;453 } else if (typeof val === 'function') {454 this.opts.debugCompress = true;455 this.opts.logger.network = val;456 }457 } else this.opts.debugCompress = false;458 }459 //*****************************************************************460 // internal public testing methods461 //*****************************************************************462 get __tests() {463 return new TestMethods(this.info.collation, this.socket);464 }465 //*****************************************************************466 // internal methods467 //*****************************************************************468 /**469 * Use multiple COM_STMT_EXECUTE or COM_STMT_BULK_EXECUTE470 *471 * @param values current batch values472 * @param _options batch option473 * @return {boolean} indicating if can use bulk command474 */475 _canUseBulk(values, _options) {476 // not using info.isMariaDB() directly in case of callback use,477 // without connection being completely finished.478 let useBulk =479 this.info.serverVersion &&480 this.info.serverVersion.mariaDb &&481 this.info.hasMinVersion(10, 2, 7) &&482 this.opts.bulk &&483 (this.info.serverCapabilities & Capabilities.MARIADB_CLIENT_STMT_BULK_OPERATIONS) > BigInt(0);484 if (_options && _options.fullResult) return false;485 if (useBulk) {486 //ensure that there is no stream object487 if (values !== undefined) {488 if (!this.opts.namedPlaceholders) {489 //ensure that all parameters have same length490 //single array is considered as an array of single element.491 const paramLen = Array.isArray(values[0]) ? values[0].length : values[0] ? 1 : 0;492 if (paramLen === 0) return false;493 for (let r = 0; r < values.length; r++) {494 let row = values[r];495 if (!Array.isArray(row)) row = [row];496 if (paramLen !== row.length) {497 return false;498 }499 for (let j = 0; j < paramLen; j++) {500 const val = row[j];501 if (502 val !== null &&503 typeof val === 'object' &&504 typeof val.pipe === 'function' &&505 typeof val.read === 'function'506 ) {507 return false;508 }509 }510 }511 } else {512 for (let r = 0; r < values.length; r++) {513 let row = values[r];514 const keys = Object.keys(row);515 for (let j = 0; j < keys.length; j++) {516 const val = row[keys[j]];517 if (518 val !== null &&519 typeof val === 'object' &&520 typeof val.pipe === 'function' &&521 typeof val.read === 'function'522 ) {523 return false;524 }525 }526 }527 }528 }529 }530 return useBulk;531 }532 /**533 * Add handshake command to queue.534 *535 * @private536 */537 registerHandshakeCmd(resolve, rejected) {538 const _authFail = this.authFailHandler.bind(539 this,540 function (err) {541 if (this.opts.logger.error) this.opts.logger.error(err);542 rejected(err);543 }.bind(this)544 );545 const _authSucceed = this.authSucceedHandler.bind(this, resolve, _authFail);546 const handshake = new Handshake(547 _authSucceed,548 _authFail,549 this.createSecureContext.bind(this, _authFail),550 this.addCommandEnable.bind(this),551 this.getSocket.bind(this)552 );553 Error.captureStackTrace(handshake);554 handshake.once(555 'end',556 function () {557 if (!this.opts.collation) {558 this.opts.emit('collation', this.info.collation);559 }560 process.nextTick(this.nextSendCmd.bind(this));561 }.bind(this)562 );563 this.receiveQueue.push(handshake);564 this.streamInitSocket(_authFail);565 }566 executeSessionVariableQuery() {567 if (this.opts.sessionVariables) {568 const values = [];569 let sessionQuery = 'set ';570 let keys = Object.keys(this.opts.sessionVariables);571 if (keys.length > 0) {572 return new Promise(573 function (resolve, reject) {574 for (let k = 0; k < keys.length; ++k) {575 sessionQuery += (k !== 0 ? ',' : '') + '@@' + keys[k].replace(/[^a-z0-9_]/gi, '') + '=?';576 values.push(this.opts.sessionVariables[keys[k]]);577 }578 const errorHandling = (initialErr) => {579 const err = Errors.createFatalError(580 `Error setting session variable (value ${JSON.stringify(this.opts.sessionVariables)}). Error: ${581 initialErr.message582 }`,583 Errors.ER_SETTING_SESSION_ERROR,584 this.info,585 '08S01',586 sessionQuery587 );588 if (this.opts.logger.error) this.opts.logger.error(err);589 reject(err);590 };591 const cmd = new Query(resolve, errorHandling, null, this.opts, sessionQuery, values);592 if (this.opts.trace) Error.captureStackTrace(cmd);593 this.addCommand(cmd);594 }.bind(this)595 );596 }597 }598 return Promise.resolve();599 }600 /**601 * Asking server timezone if not set in case of 'auto'602 * @returns {Promise<void>}603 * @private604 */605 checkServerTimezone() {606 if (this.opts.timezone === 'auto') {607 return new Promise(this.query.bind(this, null, 'SELECT @@system_time_zone stz, @@time_zone tz', undefined)).then(608 (res) => {609 const serverTimezone = res[0].tz === 'SYSTEM' ? res[0].stz : res[0].tz;610 const serverZone = moment.tz.zone(serverTimezone);611 if (serverZone) {612 const localTz = moment.tz.guess();613 if (serverTimezone === localTz) {614 //db server and client use same timezone, avoid any conversion615 this.opts.tz = null;616 } else {617 this.opts._localTz = localTz;618 this.opts.tz = serverTimezone;619 }620 } else {621 const err = Errors.createFatalError(622 `Automatic timezone setting fails. Server timezone '${serverTimezone}' does't have a corresponding IANA timezone. Option timezone must be set according to server timezone`,623 Errors.ER_WRONG_AUTO_TIMEZONE,624 this.info625 );626 if (this.opts.logger.error) this.opts.logger.error(err);627 return Promise.reject(err);628 }629 return Promise.resolve();630 }631 );632 }633 if (this.opts.tz && !this.opts.skipSetTimezone) {634 let tz = this.opts.tz;635 if (this.opts.tz === 'Etc/UTC') {636 tz = '+00:00';637 } else if (this.opts.tz.startsWith('Etc/GMT')) {638 let zone = moment.tz.zone(this.opts.tz);639 tz = zone.abbrs[0] + ':00';640 }641 return new Promise(this.query.bind(this, null, 'SET time_zone=?', [tz]))642 .then(() => {643 return Promise.resolve();644 })645 .catch((err) => {646 if (this.opts.logger.error) this.opts.logger.error(err);647 console.log(648 `warning: setting timezone '${this.opts.tz}' fails on server.\n look at https://mariadb.com/kb/en/mysql_tzinfo_to_sql/ to load IANA timezone.\nSetting timezone can be disabled with option \`skipSetTimezone\``649 );650 return Promise.resolve();651 });652 }653 return Promise.resolve();654 }655 checkServerVersion() {656 if (!this.opts.forceVersionCheck) {657 return Promise.resolve();658 }659 return new Promise(this.query.bind(this, null, 'SELECT @@VERSION AS v', undefined)).then(660 function (res) {661 this.info.serverVersion.raw = res[0].v;662 this.info.serverVersion.mariaDb = this.info.serverVersion.raw.includes('MariaDB');663 ConnectionInformation.parseVersionString(this.info);664 return Promise.resolve();665 }.bind(this)666 );667 }668 executeInitQuery() {669 if (this.opts.initSql) {670 const initialArr = Array.isArray(this.opts.initSql) ? this.opts.initSql : [this.opts.initSql];671 const initialPromises = [];672 initialArr.forEach((sql) => {673 initialPromises.push(new Promise(this.query.bind(this, null, sql, undefined)));674 });675 return Promise.all(initialPromises).catch((initialErr) => {676 const err = Errors.createFatalError(677 `Error executing initial sql command: ${initialErr.message}`,678 Errors.ER_INITIAL_SQL_ERROR,679 this.info680 );681 if (this.opts.logger.error) this.opts.logger.error(err);682 return Promise.reject(err);683 });684 }685 return Promise.resolve();686 }687 executeSessionTimeout() {688 if (this.opts.queryTimeout) {689 if (this.info.isMariaDB() && this.info.hasMinVersion(10, 1, 2)) {690 const query = `SET max_statement_time=${this.opts.queryTimeout / 1000}`;691 new Promise(this.query.bind(this, null, query, undefined)).catch(692 function (initialErr) {693 const err = Errors.createFatalError(694 `Error setting session queryTimeout: ${initialErr.message}`,695 Errors.ER_INITIAL_TIMEOUT_ERROR,696 this.info,697 '08S01',698 query699 );700 if (this.opts.logger.error) this.opts.logger.error(err);701 return Promise.reject(err);702 }.bind(this)703 );704 } else {705 const err = Errors.createError(706 `Can only use queryTimeout for MariaDB server after 10.1.1. queryTimeout value: ${this.opts.queryTimeout}`,707 Errors.ER_TIMEOUT_NOT_SUPPORTED,708 this.info,709 'HY000',710 this.opts.queryTimeout711 );712 if (this.opts.logger.error) this.opts.logger.error(err);713 return Promise.reject(err);714 }715 }716 return Promise.resolve();717 }718 getSocket() {719 return this.socket;720 }721 /**722 * Initialize socket and associate events.723 * @private724 */725 streamInitSocket(authFailHandler) {726 if (this.opts.socketPath) {727 this.socket = Net.connect(this.opts.socketPath);728 } else if (this.opts.stream) {729 if (typeof this.opts.stream === 'function') {730 const tmpSocket = this.opts.stream(731 function (err, stream) {732 if (err) {733 authFailHandler(err);734 return;735 } else if (stream) {736 this.socket = stream;737 this.socketInit(authFailHandler);738 } else {739 this.socket = Net.connect(this.opts.port, this.opts.host);740 this.socketInit(authFailHandler);741 }742 }.bind(this)743 );744 if (tmpSocket) {745 this.socket = tmpSocket;746 this.socketInit(authFailHandler);747 }748 } else {749 const err = Errors.createError(750 'stream option is not a function. stream must be a function with (error, callback) parameter',751 Errors.ER_BAD_PARAMETER_VALUE,752 this.info753 );754 authFailHandler(err);755 }756 return;757 } else {758 this.socket = Net.connect(this.opts.port, this.opts.host);759 }760 this.socketInit(authFailHandler);761 }762 socketInit(authFailHandler) {763 if (this.opts.connectTimeout) {764 this.timeout = setTimeout(765 this.connectTimeoutReached.bind(this),766 this.opts.connectTimeout,767 authFailHandler,768 Date.now()769 );770 }771 const socketError = this.socketErrorHandler.bind(this, authFailHandler);772 this.socket.on('data', this.streamIn.onData.bind(this.streamIn));773 this.socket.on('error', socketError);774 this.socket.on('end', socketError);775 this.socket.on(776 'connect',777 function () {778 clearTimeout(this.timeout);779 if (this.status === Status.CONNECTING) {780 this.status = Status.AUTHENTICATING;781 this.socketConnected = true;782 this.socket.setTimeout(this.opts.socketTimeout, this.socketTimeoutReached.bind(this, authFailHandler));783 this.socket.setNoDelay(true);784 // keep alive for socket. This won't reset server wait_timeout use pool option idleTimeout for that785 if (this.opts.keepAliveDelay) {786 this.socket.setKeepAlive(true, this.opts.keepAliveDelay);787 }788 }789 }.bind(this)790 );791 this.socket.writeBuf = (buf) => this.socket.write(buf);792 this.socket.flush = () => {};793 this.streamOut.setStream(this.socket);794 }795 /**796 * Authentication success result handler.797 *798 * @private799 */800 authSucceedHandler(resolve, rejected) {801 //enable packet compression according to option802 if (this.opts.compress) {803 if (this.info.serverCapabilities & Capabilities.COMPRESS) {804 this.streamOut.setStream(new CompressionOutputStream(this.socket, this.opts, this.info));805 this.streamIn = new CompressionInputStream(this.streamIn, this.receiveQueue, this.opts, this.info);806 this.socket.removeAllListeners('data');807 this.socket.on('data', this.streamIn.onData.bind(this.streamIn));808 } else {809 const err = Errors.createError(810 "connection is configured to use packet compression, but the server doesn't have this capability",811 Errors.ER_COMPRESSION_NOT_SUPPORTED,812 this.info813 );814 if (this.opts.logger.error) this.opts.logger.error(err);815 }816 }817 this.addCommand = this.opts.pipelining ? this.addCommandEnablePipeline : this.addCommandEnable;818 const commands = this.waitingAuthenticationQueue.toArray();819 commands.forEach((cmd) => {820 this.addCommand(cmd);821 });822 const errorInitialQueries = (err) => {823 if (!err.fatal)824 this.end(825 () => {},826 () => {}827 );828 process.nextTick(rejected, err);829 };830 this.status = Status.INIT_CMD;831 this.executeSessionVariableQuery()832 .then(this.checkServerTimezone.bind(this))833 .then(this.checkServerVersion.bind(this))834 .then(this.executeInitQuery.bind(this))835 .then(this.executeSessionTimeout.bind(this))836 .then(837 function () {838 this.status = Status.CONNECTED;839 process.nextTick(resolve, this);840 }.bind(this)841 )842 .catch(errorInitialQueries);843 }844 /**845 * Authentication failed result handler.846 *847 * @private848 */849 authFailHandler(reject, err) {850 process.nextTick(reject, err);851 //remove handshake command852 this.receiveQueue.shift();853 this.fatalError(err, true);854 }855 /**856 * Create TLS socket and associate events.857 *858 * @param rejected rejected function when error859 * @param callback callback function when done860 * @private861 */862 createSecureContext(rejected, callback) {863 const socketError = this.socketErrorHandler.bind(864 this,865 function (err) {866 if (this.opts.logger.error) this.opts.logger.error(err);867 rejected(err);868 }.bind(this)869 );870 const sslOption = Object.assign({}, this.opts.ssl, {871 servername: this.opts.host,872 socket: this.socket873 });874 try {875 const secureSocket = tls.connect(sslOption, callback);876 secureSocket.on('data', this.streamIn.onData.bind(this.streamIn));877 secureSocket.on('error', socketError);878 secureSocket.on('end', socketError);879 secureSocket.writeBuf = (buf) => secureSocket.write(buf);880 secureSocket.flush = () => {};881 this.socket.removeAllListeners('data');882 this.socket = secureSocket;883 this.streamOut.setStream(secureSocket);884 } catch (err) {885 socketError(err);886 }887 }888 /**889 * Handle packet when no packet is expected.890 * (there can be an ERROR packet send by server/proxy to inform that connection is ending).891 *892 * @param packet packet893 * @private894 */895 unexpectedPacket(packet) {896 if (packet && packet.peek() === 0xff) {897 //can receive unexpected error packet from server/proxy898 //to inform that connection is closed (usually by timeout)899 let err = packet.readError(this.info);900 if (err.fatal && this.status < Status.CLOSING) {901 this.emit('error', err);902 if (this.opts.logger.error) this.opts.logger.error(err);903 this.end(904 () => {},905 () => {}906 );907 }908 } else if (this.status < Status.CLOSING) {909 const err = Errors.createFatalError(910 `receiving packet from server without active commands\nconn:${this.info.threadId ? this.info.threadId : -1}(${911 packet.pos912 },${packet.end})\n${Utils.log(this.opts, packet.buf, packet.pos, packet.end)}`,913 Errors.ER_UNEXPECTED_PACKET,914 this.info915 );916 if (this.opts.logger.error) this.opts.logger.error(err);917 this.emit('error', err);918 this.destroy();919 }920 }921 /**922 * Handle connection timeout.923 *924 * @private925 */926 connectTimeoutReached(authFailHandler, initialConnectionTime) {927 this.timeout = null;928 const handshake = this.receiveQueue.peekFront();929 const err = Errors.createFatalError(930 `Connection timeout: failed to create socket after ${Date.now() - initialConnectionTime}ms`,931 Errors.ER_CONNECTION_TIMEOUT,932 this.info,933 '08S01',934 null,935 handshake ? handshake.stack : null936 );937 if (this.opts.logger.error) this.opts.logger.error(err);938 authFailHandler(err);939 }940 /**941 * Handle socket timeout.942 *943 * @private944 */945 socketTimeoutReached() {946 const err = Errors.createFatalError('socket timeout', Errors.ER_SOCKET_TIMEOUT, this.info);947 if (this.opts.logger.error) this.opts.logger.error(err);948 this.fatalError(err, true);949 }950 /**951 * Add command to waiting queue until authentication.952 *953 * @param cmd command954 * @returns {*} current command955 * @private956 */957 addCommandQueue(cmd) {958 this.waitingAuthenticationQueue.push(cmd);959 return cmd;960 }961 /**962 * Add command to command sending and receiving queue.963 *964 * @param cmd command965 * @returns {*} current command966 * @private967 */968 addCommandEnable(cmd) {969 cmd.once(970 'end',971 function () {972 if (!this.sendQueue.isEmpty()) {973 setImmediate(this.nextSendCmd.bind(this));974 }975 }.bind(this)976 );977 //send immediately only if no current active receiver978 if (this.sendQueue.isEmpty() || !this.receiveQueue.peekFront()) {979 this.receiveQueue.push(cmd);980 cmd.start(this.streamOut, this.opts, this.info);981 } else {982 this.receiveQueue.push(cmd);983 this.sendQueue.push(cmd);984 }985 return cmd;986 }987 /**988 * Add command to command sending and receiving queue using pipelining989 *990 * @param cmd command991 * @returns {*} current command992 * @private993 */994 addCommandEnablePipeline(cmd) {995 cmd.once(996 'send_end',997 function () {998 if (!this.sendQueue.isEmpty()) {999 setImmediate(this.nextSendCmd.bind(this));1000 }1001 }.bind(this)1002 );1003 this.receiveQueue.push(cmd);1004 if (this.sendQueue.isEmpty()) {1005 cmd.start(this.streamOut, this.opts, this.info);1006 if (cmd.sending) {1007 this.sendQueue.push(cmd);1008 cmd.prependOnceListener('send_end', this.sendQueue.shift.bind(this.sendQueue));1009 }1010 } else {1011 this.sendQueue.push(cmd);1012 }1013 return cmd;1014 }1015 /**1016 * Replacing command when connection is closing or closed to send a proper error message.1017 *1018 * @param cmd command1019 * @private1020 */1021 addCommandDisabled(cmd) {1022 const err = cmd.throwNewError(1023 'Cannot execute new commands: connection closed',1024 true,1025 this.info,1026 '08S01',1027 Errors.ER_CMD_CONNECTION_CLOSED1028 );1029 if (this.opts.logger.error) this.opts.logger.error(err);1030 }1031 /**1032 * Handle socket error.1033 *1034 * @param authFailHandler authentication handler1035 * @param err socket error1036 * @private1037 */1038 socketErrorHandler(authFailHandler, err) {1039 if (this.status >= Status.CLOSING) return;1040 if (this.socket) {1041 this.socket.writeBuf = () => {};1042 this.socket.flush = () => {};1043 }1044 //socket has been ended without error1045 if (!err) {1046 err = Errors.createFatalError(1047 'socket has unexpectedly been closed',1048 Errors.ER_SOCKET_UNEXPECTED_CLOSE,1049 this.info1050 );1051 } else {1052 err.fatal = true;1053 this.sqlState = 'HY000';1054 }1055 switch (this.status) {1056 case Status.CONNECTING:1057 case Status.AUTHENTICATING:1058 const currentCmd = this.receiveQueue.peekFront();1059 if (currentCmd && currentCmd.stack && err) {1060 err.stack += '\n From event:\n' + currentCmd.stack.substring(currentCmd.stack.indexOf('\n') + 1);1061 }1062 authFailHandler(err);1063 break;1064 default:1065 this.fatalError(err, false);1066 }1067 }1068 /**1069 * Fatal unexpected error : closing connection, and throw exception.1070 */1071 fatalError(err, avoidThrowError) {1072 if (this.status >= Status.CLOSING) {1073 this.socketErrorDispatchToQueries(err);1074 return;1075 }1076 const mustThrowError = this.status !== Status.CONNECTING;1077 this.status = Status.CLOSING;1078 //prevent executing new commands1079 this.addCommand = this.addCommandDisabled;1080 if (this.socket) {1081 this.socket.removeAllListeners('error');1082 this.socket.removeAllListeners('timeout');1083 this.socket.removeAllListeners('close');1084 this.socket.removeAllListeners('data');1085 if (!this.socket.destroyed) this.socket.destroy();1086 this.socket = undefined;1087 }1088 this.status = Status.CLOSED;1089 const errorThrownByCmd = this.socketErrorDispatchToQueries(err);1090 if (mustThrowError) {1091 if (this.opts.logger.error) this.opts.logger.error(err);1092 if (this.listenerCount('error') > 0) {1093 this.emit('error', err);1094 this.emit('end');1095 this.clear();1096 } else {1097 this.emit('end');1098 this.clear();1099 //error will be thrown if no error listener and no command did throw the exception1100 if (!avoidThrowError && !errorThrownByCmd) throw err;1101 }1102 } else {1103 this.clear();1104 }1105 }1106 /**1107 * Dispatch fatal error to current running queries.1108 *1109 * @param err the fatal error1110 * @return {boolean} return if error has been relayed to queries1111 */1112 socketErrorDispatchToQueries(err) {1113 let receiveCmd;1114 let errorThrownByCmd = false;1115 while ((receiveCmd = this.receiveQueue.shift())) {1116 if (receiveCmd && receiveCmd.onPacketReceive) {1117 errorThrownByCmd = true;1118 setImmediate(receiveCmd.throwError.bind(receiveCmd), err, this.info);1119 }1120 }1121 return errorThrownByCmd;1122 }1123 /**1124 * Will send next command in queue if any.1125 *1126 * @private1127 */1128 nextSendCmd() {1129 let sendCmd;1130 if ((sendCmd = this.sendQueue.shift())) {1131 if (sendCmd.sending) {1132 this.sendQueue.unshift(sendCmd);1133 } else {1134 sendCmd.start(this.streamOut, this.opts, this.info);1135 if (sendCmd.sending) {1136 this.sendQueue.unshift(sendCmd);1137 sendCmd.prependOnceListener('send_end', this.sendQueue.shift.bind(this.sendQueue));1138 }1139 }1140 }1141 }1142 /**1143 * Change transaction state.1144 *1145 * @param sql sql1146 * @returns {Promise} promise1147 * @private1148 */1149 changeTransaction(sql, resolve, reject) {1150 //if command in progress, driver cannot rely on status and must execute query1151 if (this.status >= Status.CLOSING) {1152 const err = Errors.createFatalError(1153 'Cannot execute new commands: connection closed',1154 Errors.ER_CMD_CONNECTION_CLOSED,1155 this.info,1156 '08S01',1157 sql1158 );1159 if (this.opts.logger.error) this.opts.logger.error(err);1160 return reject(err);1161 }1162 //Command in progress => must execute query1163 //or if no command in progress, can rely on status to know if query is needed1164 if (this.receiveQueue.peekFront() || this.info.status & ServerStatus.STATUS_IN_TRANS) {1165 const cmd = new Query(1166 resolve,...
runner.js
Source:runner.js
...360 if (this.state === constants.STATE_STOPPED) {361 if (err.code === errors.constants.MULTIPLE_DONE) {362 throw err;363 }364 throw createFatalError(365 'Test failed after root suite execution completed!',366 err367 );368 }369 ++this.failures;370 debug('total number of failures: %d', this.failures);371 test.state = STATE_FAILED;372 if (!isError(err)) {373 err = thrown2Error(err);374 }375 try {376 err.stack =377 this.fullStackTrace || !err.stack ? err.stack : stackFilter(err.stack);378 } catch (ignore) {379 // some environments do not take kindly to monkeying with the stack380 }381 this.emit(constants.EVENT_TEST_FAIL, test, err);382};383/**384 * Run hook `name` callbacks and then invoke `fn()`.385 *386 * @private387 * @param {string} name388 * @param {Function} fn389 */390Runner.prototype.hook = function(name, fn) {391 var suite = this.suite;392 var hooks = suite.getHooks(name);393 var self = this;394 function next(i) {395 var hook = hooks[i];396 if (!hook) {397 return fn();398 }399 self.currentRunnable = hook;400 if (name === HOOK_TYPE_BEFORE_ALL) {401 hook.ctx.currentTest = hook.parent.tests[0];402 } else if (name === HOOK_TYPE_AFTER_ALL) {403 hook.ctx.currentTest = hook.parent.tests[hook.parent.tests.length - 1];404 } else {405 hook.ctx.currentTest = self.test;406 }407 setHookTitle(hook);408 hook.allowUncaught = self.allowUncaught;409 self.emit(constants.EVENT_HOOK_BEGIN, hook);410 if (!hook.listeners('error').length) {411 self._addEventListener(hook, 'error', function(err) {412 self.fail(hook, err);413 });414 }415 hook.run(function cbHookRun(err) {416 var testError = hook.error();417 if (testError) {418 self.fail(self.test, testError);419 }420 // conditional skip421 if (hook.pending) {422 if (name === HOOK_TYPE_AFTER_EACH) {423 // TODO define and implement use case424 if (self.test) {425 self.test.pending = true;426 }427 } else if (name === HOOK_TYPE_BEFORE_EACH) {428 if (self.test) {429 self.test.pending = true;430 }431 self.emit(constants.EVENT_HOOK_END, hook);432 hook.pending = false; // activates hook for next test433 return fn(new Error('abort hookDown'));434 } else if (name === HOOK_TYPE_BEFORE_ALL) {435 suite.tests.forEach(function(test) {436 test.pending = true;437 });438 suite.suites.forEach(function(suite) {439 suite.pending = true;440 });441 hooks = [];442 } else {443 hook.pending = false;444 var errForbid = createUnsupportedError('`this.skip` forbidden');445 self.fail(hook, errForbid);446 return fn(errForbid);447 }448 } else if (err) {449 self.fail(hook, err);450 // stop executing hooks, notify callee of hook err451 return fn(err);452 }453 self.emit(constants.EVENT_HOOK_END, hook);454 delete hook.ctx.currentTest;455 setHookTitle(hook);456 next(++i);457 });458 function setHookTitle(hook) {459 hook.originalTitle = hook.originalTitle || hook.title;460 if (hook.ctx && hook.ctx.currentTest) {461 hook.title =462 hook.originalTitle + ' for ' + dQuote(hook.ctx.currentTest.title);463 } else {464 var parentTitle;465 if (hook.parent.title) {466 parentTitle = hook.parent.title;467 } else {468 parentTitle = hook.parent.root ? '{root}' : '';469 }470 hook.title = hook.originalTitle + ' in ' + dQuote(parentTitle);471 }472 }473 }474 Runner.immediately(function() {475 next(0);476 });477};478/**479 * Run hook `name` for the given array of `suites`480 * in order, and callback `fn(err, errSuite)`.481 *482 * @private483 * @param {string} name484 * @param {Array} suites485 * @param {Function} fn486 */487Runner.prototype.hooks = function(name, suites, fn) {488 var self = this;489 var orig = this.suite;490 function next(suite) {491 self.suite = suite;492 if (!suite) {493 self.suite = orig;494 return fn();495 }496 self.hook(name, function(err) {497 if (err) {498 var errSuite = self.suite;499 self.suite = orig;500 return fn(err, errSuite);501 }502 next(suites.pop());503 });504 }505 next(suites.pop());506};507/**508 * Run hooks from the top level down.509 *510 * @param {String} name511 * @param {Function} fn512 * @private513 */514Runner.prototype.hookUp = function(name, fn) {515 var suites = [this.suite].concat(this.parents()).reverse();516 this.hooks(name, suites, fn);517};518/**519 * Run hooks from the bottom up.520 *521 * @param {String} name522 * @param {Function} fn523 * @private524 */525Runner.prototype.hookDown = function(name, fn) {526 var suites = [this.suite].concat(this.parents());527 this.hooks(name, suites, fn);528};529/**530 * Return an array of parent Suites from531 * closest to furthest.532 *533 * @return {Array}534 * @private535 */536Runner.prototype.parents = function() {537 var suite = this.suite;538 var suites = [];539 while (suite.parent) {540 suite = suite.parent;541 suites.push(suite);542 }543 return suites;544};545/**546 * Run the current test and callback `fn(err)`.547 *548 * @param {Function} fn549 * @private550 */551Runner.prototype.runTest = function(fn) {552 var self = this;553 var test = this.test;554 if (!test) {555 return;556 }557 if (this.asyncOnly) {558 test.asyncOnly = true;559 }560 this._addEventListener(test, 'error', function(err) {561 self.fail(test, err);562 });563 if (this.allowUncaught) {564 test.allowUncaught = true;565 return test.run(fn);566 }567 try {568 test.run(fn);569 } catch (err) {570 fn(err);571 }572};573/**574 * Run tests in the given `suite` and invoke the callback `fn()` when complete.575 *576 * @private577 * @param {Suite} suite578 * @param {Function} fn579 */580Runner.prototype.runTests = function(suite, fn) {581 var self = this;582 var tests = suite.tests.slice();583 var test;584 function hookErr(_, errSuite, after) {585 // before/after Each hook for errSuite failed:586 var orig = self.suite;587 // for failed 'after each' hook start from errSuite parent,588 // otherwise start from errSuite itself589 self.suite = after ? errSuite.parent : errSuite;590 if (self.suite) {591 // call hookUp afterEach592 self.hookUp(HOOK_TYPE_AFTER_EACH, function(err2, errSuite2) {593 self.suite = orig;594 // some hooks may fail even now595 if (err2) {596 return hookErr(err2, errSuite2, true);597 }598 // report error suite599 fn(errSuite);600 });601 } else {602 // there is no need calling other 'after each' hooks603 self.suite = orig;604 fn(errSuite);605 }606 }607 function next(err, errSuite) {608 // if we bail after first err609 if (self.failures && suite._bail) {610 tests = [];611 }612 if (self._abort) {613 return fn();614 }615 if (err) {616 return hookErr(err, errSuite, true);617 }618 // next test619 test = tests.shift();620 // all done621 if (!test) {622 return fn();623 }624 // grep625 var match = self._grep.test(test.fullTitle());626 if (self._invert) {627 match = !match;628 }629 if (!match) {630 // Run immediately only if we have defined a grep. When we631 // define a grep â It can cause maximum callstack error if632 // the grep is doing a large recursive loop by neglecting633 // all tests. The run immediately function also comes with634 // a performance cost. So we don't want to run immediately635 // if we run the whole test suite, because running the whole636 // test suite don't do any immediate recursive loops. Thus,637 // allowing a JS runtime to breathe.638 if (self._grep !== self._defaultGrep) {639 Runner.immediately(next);640 } else {641 next();642 }643 return;644 }645 // static skip, no hooks are executed646 if (test.isPending()) {647 if (self.forbidPending) {648 self.fail(test, new Error('Pending test forbidden'), true);649 } else {650 test.state = STATE_PENDING;651 self.emit(constants.EVENT_TEST_PENDING, test);652 }653 self.emit(constants.EVENT_TEST_END, test);654 return next();655 }656 // execute test and hook(s)657 self.emit(constants.EVENT_TEST_BEGIN, (self.test = test));658 self.hookDown(HOOK_TYPE_BEFORE_EACH, function(err, errSuite) {659 // conditional skip within beforeEach660 if (test.isPending()) {661 if (self.forbidPending) {662 self.fail(test, new Error('Pending test forbidden'), true);663 } else {664 test.state = STATE_PENDING;665 self.emit(constants.EVENT_TEST_PENDING, test);666 }667 self.emit(constants.EVENT_TEST_END, test);668 // skip inner afterEach hooks below errSuite level669 var origSuite = self.suite;670 self.suite = errSuite || self.suite;671 return self.hookUp(HOOK_TYPE_AFTER_EACH, function(e, eSuite) {672 self.suite = origSuite;673 next(e, eSuite);674 });675 }676 if (err) {677 return hookErr(err, errSuite, false);678 }679 self.currentRunnable = self.test;680 self.runTest(function(err) {681 test = self.test;682 // conditional skip within it683 if (test.pending) {684 if (self.forbidPending) {685 self.fail(test, new Error('Pending test forbidden'), true);686 } else {687 test.state = STATE_PENDING;688 self.emit(constants.EVENT_TEST_PENDING, test);689 }690 self.emit(constants.EVENT_TEST_END, test);691 return self.hookUp(HOOK_TYPE_AFTER_EACH, next);692 } else if (err) {693 var retry = test.currentRetry();694 if (retry < test.retries()) {695 var clonedTest = test.clone();696 clonedTest.currentRetry(retry + 1);697 tests.unshift(clonedTest);698 self.emit(constants.EVENT_TEST_RETRY, test, err);699 // Early return + hook trigger so that it doesn't700 // increment the count wrong701 return self.hookUp(HOOK_TYPE_AFTER_EACH, next);702 } else {703 self.fail(test, err);704 }705 self.emit(constants.EVENT_TEST_END, test);706 return self.hookUp(HOOK_TYPE_AFTER_EACH, next);707 }708 test.state = STATE_PASSED;709 self.emit(constants.EVENT_TEST_PASS, test);710 self.emit(constants.EVENT_TEST_END, test);711 self.hookUp(HOOK_TYPE_AFTER_EACH, next);712 });713 });714 }715 this.next = next;716 this.hookErr = hookErr;717 next();718};719/**720 * Run the given `suite` and invoke the callback `fn()` when complete.721 *722 * @private723 * @param {Suite} suite724 * @param {Function} fn725 */726Runner.prototype.runSuite = function(suite, fn) {727 var i = 0;728 var self = this;729 var total = this.grepTotal(suite);730 debug('runSuite(): running %s', suite.fullTitle());731 if (!total || (self.failures && suite._bail)) {732 debug('runSuite(): bailing');733 return fn();734 }735 this.emit(constants.EVENT_SUITE_BEGIN, (this.suite = suite));736 function next(errSuite) {737 if (errSuite) {738 // current suite failed on a hook from errSuite739 if (errSuite === suite) {740 // if errSuite is current suite741 // continue to the next sibling suite742 return done();743 }744 // errSuite is among the parents of current suite745 // stop execution of errSuite and all sub-suites746 return done(errSuite);747 }748 if (self._abort) {749 return done();750 }751 var curr = suite.suites[i++];752 if (!curr) {753 return done();754 }755 // Avoid grep neglecting large number of tests causing a756 // huge recursive loop and thus a maximum call stack error.757 // See comment in `this.runTests()` for more information.758 if (self._grep !== self._defaultGrep) {759 Runner.immediately(function() {760 self.runSuite(curr, next);761 });762 } else {763 self.runSuite(curr, next);764 }765 }766 function done(errSuite) {767 self.suite = suite;768 self.nextSuite = next;769 // remove reference to test770 delete self.test;771 self.hook(HOOK_TYPE_AFTER_ALL, function() {772 self.emit(constants.EVENT_SUITE_END, suite);773 fn(errSuite);774 });775 }776 this.nextSuite = next;777 this.hook(HOOK_TYPE_BEFORE_ALL, function(err) {778 if (err) {779 return done();780 }781 self.runTests(suite, next);782 });783};784/**785 * Handle uncaught exceptions within runner.786 *787 * This function is bound to the instance as `Runner#uncaught` at instantiation788 * time. It's intended to be listening on the `Process.uncaughtException` event.789 * In order to not leak EE listeners, we need to ensure no more than a single790 * `uncaughtException` listener exists per `Runner`. The only way to do791 * this--because this function needs the context (and we don't have lambdas)--is792 * to use `Function.prototype.bind`. We need strict equality to unregister and793 * _only_ unregister the _one_ listener we set from the794 * `Process.uncaughtException` event; would be poor form to just remove795 * everything. See {@link Runner#run} for where the event listener is registered796 * and unregistered.797 * @param {Error} err - Some uncaught error798 * @private799 */800Runner.prototype._uncaught = function(err) {801 // this is defensive to prevent future developers from mis-calling this function.802 // it's more likely that it'd be called with the incorrect context--say, the global803 // `process` object--than it would to be called with a context that is not a "subclass"804 // of `Runner`.805 if (!(this instanceof Runner)) {806 throw createFatalError(807 'Runner#uncaught() called with invalid context',808 this809 );810 }811 if (err instanceof Pending) {812 debug('uncaught(): caught a Pending');813 return;814 }815 // browser does not exit script when throwing in global.onerror()816 if (this.allowUncaught && !utils.isBrowser()) {817 debug('uncaught(): bubbling exception due to --allow-uncaught');818 throw err;819 }820 if (this.state === constants.STATE_STOPPED) {...
ApiHealthCheckService.js
Source:ApiHealthCheckService.js
...29 let apiConfigKey = apiUrl.replace(/\//g, '-');30 let healthcheckConfigs = await this.getHealthcheckConfig(baseUrl, apiConfigKey);31 //console.log('healthcheck configs ', JSON.stringify(healthcheckConfigs));32 if (!(healthcheckConfigs && healthcheckConfigs.response && healthcheckConfigs.response.configObjects)) {33 return this.createFatalError(apiUrl);34 }35 let response = undefined;36 let apiConfig = this.getApiConfig(healthcheckConfigs, apiConfigKey);37 if (apiConfig) {38 if(apiConfig.rdfInternal){39 let serviceName = apiUrl.replace("internal/","");40 dfUrl = this._internalRdfUrl+ '/' + tenantId + '/api/' + serviceName + '?timeStamp=' + timeStamp;41 }42 let operation = apiConfig.operation;43 switch (operation) {44 case "get": {45 return this.executeGetRequest(dfUrl, apiUrl, apiConfig, isCOPService);46 }47 case "update": {48 return this.executeUpdateRequest(dfUrl, apiUrl, apiConfig);49 }50 case "create": {51 return this.executeCreateRequest(dfUrl, apiUrl, apiConfig);52 }53 default: {54 return this.createFatalError(apiUrl);55 }56 }57 }58 return {};59 },60 executeGetRequest: async function (dfUrl, apiUrl, apiConfig, isCOPService) {61 let response = {};62 let request = apiConfig.request;63 let collectionName = apiConfig.responseInfo.collectionName;64 if (!request) {65 response = this.createFatalError(apiUrl);66 }67 else {68 if(isCOPService){69 dfUrl = dfUrl.replace("copservice/", "rsConnectService/");70 }71 request.url = dfUrl;72 let getStartTick = process.hrtime();73 let apiResponse = await this.callRdfApi(request);74 let getEndTick = process.hrtime(getStartTick);75 let getTimeTaken = getEndTick[1] / 1000000;76 if ((apiResponse && apiResponse.response) || isCOPService) {77 if ((isCOPService && apiResponse[collectionName]) || (apiResponse.response && apiResponse.response[collectionName] && apiResponse.response[collectionName].length > 0)) {78 response = {79 "status": "success",80 "msg": "All is well...! " + apiUrl + " call returned with data.",81 "detail": {82 "request": request.body,83 "response": apiResponse,84 "stats": {85 "timeTaken": getTimeTaken,86 "verificationTimeTaken": -1,87 "noOfVerificationProbs": -1,88 "verificationProbTotalWait": -189 }90 }91 };92 }93 else {94 response = {95 "status": "warning",96 "msg": apiUrl + " call returned without any data. Check the system.",97 "detail": {98 "request": request.body,99 "response": apiResponse,100 "stats": {101 "timeTaken": getTimeTaken,102 "verificationTimeTaken": -1,103 "noOfVerificationProbs": -1,104 "verificationProbTotalWait": -1105 }106 }107 };108 }109 }110 else {111 response = {112 "status": "error",113 "msg": apiUrl + " call failed to return expected data.",114 "detail": {115 "request": request.body,116 "response": apiResponse,117 "stats": {118 "timeTaken": getTimeTaken,119 "verificationTimeTaken": -1,120 "noOfVerificationProbs": -1,121 "verificationProbTotalWait": -1122 }123 }124 };125 }126 }127 return response;128 },129 executeUpdateRequest: async function (dfUrl, apiUrl, apiConfig) {130 let response = undefined;131 let getRequest = apiConfig.getRequest;132 let getApiUrl = apiConfig.getApiUrl;133 let updateRequest = apiConfig.updateRequest;134 let attributesToUpdate = apiConfig.attributesToUpdate;135 let attrName = attributesToUpdate[0];136 let verificationDelayIntervals = apiConfig.verificationDelayIntervals;137 let collectionName = apiConfig.objectInfo.collectionName;138 let objectName = apiConfig.objectInfo.objectName;139 if (!getRequest) {140 response = this.createFatalError(apiUrl);141 }142 else {143 let newVal = moment().format("YYYY-MM-DDTHH:mm:ss.SSS-0500"); // just set new value as current timestamp..144 //console.log('new val', newVal);145 getRequest.url = dfUrl.replace(apiUrl, getApiUrl);146 let getApiResponse = await this.callRdfApi(getRequest);147 if (!(getApiResponse && getApiResponse.response && getApiResponse.response[collectionName] && getApiResponse.response[collectionName].length > 0)) {148 response = {149 "status": "error",150 "msg": getRequest.url + " call returned without any data. Check the healthcheck config.",151 "detail": {152 "request": getRequest.body,153 "response": getApiResponse154 }155 };156 return response;157 }158 let defaultValContext = await this.tenantSystemConfigService.getDefaultValContext();159 let dataObject = updateRequest.body[objectName];160 this.setAttrVal(dataObject.data.attributes, attrName, newVal, defaultValContext);161 updateRequest.url = dfUrl;162 let updateStartTick = process.hrtime();163 let updateApiResponse = await this.callRdfApi(updateRequest);164 let updateEndTick = process.hrtime(updateStartTick);165 let updateTime = updateEndTick[1] / 1000000;166 if (updateApiResponse && updateApiResponse.response) {167 let status = updateApiResponse.response.status;168 let verificationStartTick = process.hrtime();169 if (status == "success") {170 let i = 0;171 let totalDelay = 0;172 do {173 let val = await this.getDataObjectAttrVal(getRequest, collectionName, attrName);174 //console.log('val ', val);175 if (val == newVal) {176 let verificationEndTick = process.hrtime(verificationStartTick);177 let verificationTime = verificationEndTick[1] / 1000000;178 response = {179 "status": "success",180 "msg": apiUrl + " call returned with success status",181 "detail": {182 "request": updateRequest.body,183 "response": updateApiResponse,184 "stats": {185 "timeTaken": updateTime,186 "verificationTimeTaken": verificationTime,187 "noOfVerificationProbs": i + 1,188 "verificationProbTotalWait": totalDelay189 }190 }191 };192 break;193 }194 let interval = verificationDelayIntervals[i];195 totalDelay += interval;196 sleep(interval);197 i++;198 } while (i < verificationDelayIntervals.length);199 if (!response) {200 let verificationEndTick = process.hrtime(verificationStartTick);201 let verificationTime = verificationEndTick[1] / 1000000;202 response = {203 "status": "warning",204 "msg": apiUrl + " call succeeded but unable to verify updated value",205 "detail": {206 "request": updateRequest.body,207 "response": updateApiResponse,208 "stats": {209 "timeTaken": updateTime,210 "verificationTimeTaken": verificationTime,211 "noOfVerificationProbs": i + 1,212 "verificationProbTotalWait": totalDelay213 }214 }215 };216 }217 } else {218 let verificationEndTick = process.hrtime(verificationStartTick);219 let verificationTime = verificationEndTick[1] / 1000000;220 response = {221 "status": "error",222 "msg": apiUrl + " call failed.",223 "detail": {224 "request": updateRequest.body,225 "response": updateApiResponse,226 "stats": {227 "timeTaken": updateTime,228 "verificationTimeTaken": verificationTime,229 "noOfVerificationProbs": -1,230 "verificationProbTotalWait": -1231 }232 }233 };234 }235 }236 else {237 return this.createFatalError(apiUrl);238 }239 }240 return response;241 },242 executeCreateRequest: async function (dfUrl, apiUrl, apiConfig) {243 let response = undefined;244 let newEntityGuid = uuidV1();245 let apiConfigAsString = JSON.stringify(apiConfig);246 apiConfigAsString = apiConfigAsString.replace(/<GUID>/g, newEntityGuid);247 apiConfig = JSON.parse(apiConfigAsString);248 let getRequest = apiConfig.getRequest;249 let getApiUrl = apiConfig.getApiUrl;250 let deleteApiUrl = apiConfig.deleteApiUrl;251 let createRequest = apiConfig.createRequest;252 let deleteRequest = apiConfig.deleteRequest;253 let attributesToUpdate = apiConfig.attributesToUpdate;254 let attrName = attributesToUpdate[0];255 let verificationDelayIntervals = apiConfig.verificationDelayIntervals;256 let collectionName = apiConfig.objectInfo.collectionName;257 let objectName = apiConfig.objectInfo.objectName;258 if (!getRequest) {259 response = this.createFatalError(apiUrl);260 }261 else {262 let newVal = moment().format("YYYY-MM-DDTHH:mm:ss.SSS-0500"); // just set new value as current timestamp..263 //console.log('new val', newVal);264 let serverUrl = apiUrl;265 if(apiConfig.rdfInternal){266 serverUrl = apiUrl.replace('internal/','');267 }268 getRequest.url = dfUrl.replace(serverUrl, getApiUrl);269 deleteRequest.url = dfUrl.replace(serverUrl, deleteApiUrl);270 let defaultValContext = await this.tenantSystemConfigService.getDefaultValContext();271 let dataObject = createRequest.body[objectName];272 this.setAttrVal(dataObject.data.attributes, attrName, newVal, defaultValContext);273 createRequest.url = dfUrl;274 let createStartTick = process.hrtime();275 let createApiResponse = await this.callRdfApi(createRequest);276 let createEndTick = process.hrtime(createStartTick);277 let createTime = createEndTick[1] / 1000000;278 if (createApiResponse && createApiResponse.response) {279 let status = createApiResponse.response.status;280 let verificationStartTick = process.hrtime();281 if (status == "success") {282 let i = 0;283 let totalDelay = 0;284 do {285 let val = await this.getDataObjectAttrVal(getRequest, collectionName, attrName);286 //console.log('val ', val);287 if (val == newVal) {288 let verificationEndTick = process.hrtime(verificationStartTick);289 let verificationTime = verificationEndTick[1] / 1000000;290 response = {291 "status": "success",292 "msg": apiUrl + " call returned with success status.",293 "detail": {294 "request": createRequest.body,295 "response": createApiResponse,296 "stats": {297 "timeTaken": createTime,298 "verificationTimeTaken": verificationTime,299 "noOfVerificationProbs": i + 1,300 "verificationProbTotalWait": totalDelay301 }302 }303 };304 let deleteApiResponse = await this.callRdfApi(deleteRequest);305 response.detail.cleanupResponse = deleteApiResponse;306 break;307 }308 let interval = verificationDelayIntervals[i];309 totalDelay += interval;310 sleep(interval);311 i++;312 } while (i < verificationDelayIntervals.length);313 if (!response) {314 let verificationEndTick = process.hrtime(verificationStartTick);315 let verificationTime = verificationEndTick[1] / 1000000;316 response = {317 "status": "warning",318 "msg": apiUrl + " call succeeded but unable to verify created object",319 "detail": {320 "request": createRequest.body,321 "response": createApiResponse,322 "stats": {323 "timeTaken": createTime,324 "verificationTimeTaken": verificationTime,325 "noOfVerificationProbs": i + 1,326 "verificationProbTotalWait": totalDelay327 }328 }329 };330 let deleteApiResponse = await this.callRdfApi(deleteRequest);331 response.detail.cleanupResponse = deleteApiResponse;332 }333 } else {334 let verificationEndTick = process.hrtime(verificationStartTick);335 let verificationTime = verificationEndTick[1] / 1000000;336 response = {337 "status": "error",338 "msg": apiUrl + " call failed.",339 "detail": {340 "request": createRequest.body,341 "response": createApiResponse,342 "stats": {343 "timeTaken": createTime,344 "verificationTimeTaken": verificationTime,345 "noOfVerificationProbs": -1,346 "verificationProbTotalWait": -1347 }348 }349 };350 }351 }352 else {353 return this.createFatalError(apiUrl);354 }355 }356 return response;357 },358 getDataObjectAttrVal: async function (getRequest, collectionName, attrName) {359 let attrVal = undefined;360 let getApiResponse = await this.callRdfApi(getRequest);361 if (getApiResponse && getApiResponse.response && getApiResponse.response[collectionName] && getApiResponse.response[collectionName].length > 0) {362 let dataObject = getApiResponse.response[collectionName][0];363 if (dataObject && dataObject.data && dataObject.data.attributes && dataObject.data.attributes[attrName]) {364 let attr = dataObject.data.attributes[attrName];365 if (attr && attr.values && attr.values.length > 0) {366 attrVal = attr.values[0].value;367 }...
parallel-buffered-runner.js
Source:parallel-buffered-runner.js
...135 : obj;136 this._linkedObjectMap.set(id, newObj);137 parent[prop] = newObj;138 } else {139 throw createFatalError(140 'Object missing ID received in event data',141 obj142 );143 }144 }145 Object.keys(newObj).forEach(key => {146 const value = obj[key];147 if (value && typeof value === 'object' && value[MOCHA_ID_PROP_NAME]) {148 stack.push({obj: value, parent: newObj, prop: key});149 }150 });151 }152 };153 return async file => {...
handshake.js
Source:handshake.js
...196 return;197 }198 if (!this.plugin) {199 this.reject(200 Errors.createFatalError(201 "Client does not support authentication protocol '" + pluginName + "' requested by server. ",202 Errors.ER_AUTHENTICATION_PLUGIN_NOT_SUPPORTED,203 info,204 '08004'205 )206 );207 } else {208 this._addCommand(this.plugin);209 }210 }211 static pluginHandler(212 pluginName,213 packSeq,214 compressPackSeq,215 pluginData,216 info,217 opts,218 out,219 authResolve,220 authReject,221 multiAuthResolver222 ) {223 let pluginAuth;224 switch (pluginName) {225 case 'mysql_native_password':226 pluginAuth = require('./auth/native-password-auth.js');227 break;228 case 'mysql_clear_password':229 pluginAuth = require('./auth/clear-password-auth.js');230 break;231 case 'client_ed25519':232 pluginAuth = require('./auth/ed25519-password-auth.js');233 break;234 case 'dialog':235 pluginAuth = require('./auth/pam-password-auth.js');236 break;237 case 'sha256_password':238 if (!Handshake.ensureNodeVersion(11, 6, 0)) {239 throw Errors.createFatalError(240 'sha256_password authentication plugin require node 11.6+',241 Errors.ER_MINIMUM_NODE_VERSION_REQUIRED,242 info,243 '08004'244 );245 }246 pluginAuth = require('./auth/sha256-password-auth.js');247 break;248 case 'caching_sha2_password':249 if (!Handshake.ensureNodeVersion(11, 6, 0)) {250 throw Errors.createFatalError(251 'caching_sha2_password authentication plugin require node 11.6+',252 Errors.ER_MINIMUM_NODE_VERSION_REQUIRED,253 info,254 '08004'255 );256 }257 pluginAuth = require('./auth/caching-sha2-password-auth.js');258 break;259 //TODO "auth_gssapi_client"260 default:261 return null;262 }263 return new pluginAuth(packSeq, compressPackSeq, pluginData, authResolve, authReject, multiAuthResolver);264 }...
errors.js
Source:errors.js
...175 * @public176 * @param {string} message - Error message to be displayed.177 * @returns {Error} instance detailing the error condition178 */179function createFatalError(message, value) {180 var err = new Error(message)181 err.code = constants.FATAL182 err.valueType = typeof value183 err.value = value184 return err185}186/**187 * Dynamically creates a plugin-type-specific error based on plugin type188 * @param {string} message - Error message189 * @param {"reporter"|"interface"} pluginType - Plugin type. Future: expand as needed190 * @param {string} [pluginId] - Name/path of plugin, if any191 * @throws When `pluginType` is not known192 * @public193 * @returns {Error}...
caching-sha2-password-auth.js
Source:caching-sha2-password-auth.js
...72 Sha256PasswordAuth.sendSha256PwdPacket(this, this.pluginData, this.publicKey, opts.password, out);73 } else {74 if (!opts.allowPublicKeyRetrieval) {75 return this.throwError(76 Errors.createFatalError(77 'RSA public key is not available client side. Either set option `cachingRsaPublicKey` to indicate' +78 ' public key path, or allow public key retrieval with option `allowPublicKeyRetrieval`',79 Errors.ER_CANNOT_RETRIEVE_RSA_KEY,80 info81 ),82 info83 );84 }85 this.state = State.REQUEST_SERVER_KEY;86 // ask caching public Key Retrieval87 out.startPacket(this);88 out.writeInt8(0x02);89 out.flushPacket();90 }...
sha256-password-auth.js
Source:sha256-password-auth.js
...47 }48 } else {49 if (!opts.allowPublicKeyRetrieval) {50 return this.throwError(51 Errors.createFatalError(52 'RSA public key is not available client side. Either set option `rsaPublicKey` to indicate' +53 ' public key path, or allow public key retrieval with option `allowPublicKeyRetrieval`',54 Errors.ER_CANNOT_RETRIEVE_RSA_KEY,55 info56 ),57 info58 );59 }60 this.initialState = false;61 // ask public Key Retrieval62 out.startPacket(this);63 out.writeInt8(0x01);64 out.flushPacket();65 return;...
Using AI Code Generation
1var Mocha = require('mocha');2var mocha = new Mocha();3var suite = Mocha.Suite.create(mocha.suite, 'My Suite');4var test = new Mocha.Test('My Test', function() {5 throw new Error('My Error');6});7suite.addTest(test);8mocha.run(function(failures) {9 process.on('exit', function() {10 });11});12 mocha.setup('bdd');13 mocha.run();
Using AI Code Generation
1var mocha = require('mocha');2var createFatalError = mocha.utils.createFatalError;3var mocha = require('mocha');4var createFatalError = mocha.utils.createFatalError;5var mocha = require('mocha');6var createFatalError = mocha.utils.createFatalError;7var mocha = require('mocha');8var createFatalError = mocha.utils.createFatalError;9var mocha = require('mocha');10var createFatalError = mocha.utils.createFatalError;11var mocha = require('mocha');12var createFatalError = mocha.utils.createFatalError;13var mocha = require('mocha');14var createFatalError = mocha.utils.createFatalError;15var mocha = require('mocha');16var createFatalError = mocha.utils.createFatalError;17var mocha = require('mocha');18var createFatalError = mocha.utils.createFatalError;19var mocha = require('mocha');20var createFatalError = mocha.utils.createFatalError;
Using AI Code Generation
1const { createFatalError } = require('mocha/lib/errors');2throw createFatalError('This is a fatal error');3const { createInvalidExceptionError } = require('mocha/lib/errors');4throw createInvalidExceptionError('This is an invalid exception error');5const { createInvalidTestError } = require('mocha/lib/errors');6throw createInvalidTestError('This is an invalid test error');7const { createInvalidSuiteError } = require('mocha/lib/errors');8throw createInvalidSuiteError('This is an invalid suite error');9const { createInvalidHookError } = require('mocha/lib/errors');10throw createInvalidHookError('This is an invalid hook error');11const { createInvalidRunnableError } = require('mocha/lib/errors');12throw createInvalidRunnableError('This is an invalid runnable error');13const { createInvalidArgumentError } = require('mocha/lib/errors');14throw createInvalidArgumentError('This is an invalid argument error');15const { createInvalidReturnValueError } = require('mocha/lib/errors');16throw createInvalidReturnValueError('This is an invalid return value error');17const { createInvalidExceptionTypeError } = require('mocha/lib/errors');18throw createInvalidExceptionTypeError('This is an invalid exception type error');19const { createInvalidExceptionMessageError } = require('mocha/lib/errors');20throw createInvalidExceptionMessageError('This is an invalid exception message error');21const { createInvalidTestTitleError } = require('mocha/lib/errors');22throw createInvalidTestTitleError('This
Using AI Code Generation
1var Mocha = require("mocha");2var mocha = new Mocha();3mocha.createFatalError("fatal error");4mocha.createFatalError("fatal error", new Error("error"));5mocha.createFatalError(new Error("error"));6var Mocha = require("mocha");7var mocha = new Mocha();8var runner = mocha.run(function() {9});10runner.createFatalError("fatal error");11runner.createFatalError("fatal error", new Error("error"));12runner.createFatalError(new Error("error"));13var Mocha = require("mocha");14var mocha = new Mocha();15var suite = mocha.suite;16suite.createFatalError("fatal error");17suite.createFatalError("fatal error", new Error("error"));18suite.createFatalError(new Error("error"));19var Mocha = require("mocha");20var mocha = new Mocha();21var suite = mocha.suite;22var test = new Mocha.Test("test", function() {23});24suite.addTest(test);25test.createFatalError("fatal error");26test.createFatalError("fatal error", new Error("error"));27test.createFatalError(new Error("error"));28var Mocha = require("mocha");29var mocha = new Mocha();30var suite = mocha.suite;31var hook = new Mocha.Hook("hook", function() {32});33suite.addTest(hook);34hook.createFatalError("fatal error");35hook.createFatalError("fatal error", new Error("error"));36hook.createFatalError(new Error("error"));37var Mocha = require("mocha");38var mocha = new Mocha();39var runner = mocha.run(function() {40});41var reporter = new Mocha.reporters.Base(runner);42reporter.createFatalError("fatal error");43reporter.createFatalError("fatal error", new Error("error"));44reporter.createFatalError(new Error("error"));45var Mocha = require("mocha");46var mocha = new Mocha();47var suite = mocha.suite;48var runnable = new Mocha.Runnable("runnable");49suite.addTest(r
Using AI Code Generation
1var createFatalError = require('mocha').utils.createFatalError;2throw createFatalError('some error');3var createFatalError = require('mocha').utils.createFatalError;4throw createFatalError('some error');5var createFatalError = require('mocha').utils.createFatalError;6throw createFatalError('some error');7var createFatalError = require('mocha').utils.createFatalError;8throw createFatalError('some error');9var createFatalError = require('mocha').utils.createFatalError;10throw createFatalError('some error');11var createFatalError = require('mocha').utils.createFatalError;12throw createFatalError('some error');13var createFatalError = require('mocha').utils.createFatalError;14throw createFatalError('some error');15var createFatalError = require('mocha').utils.createFatalError;16throw createFatalError('some error');17var createFatalError = require('mocha').utils.createFatalError;18throw createFatalError('some error');
Using AI Code Generation
1it('should fail', function() {2 throw createFatalError(new Error('fatal error'));3});4it('should fail', function() {5 throw createFatalError(new Error('fatal error'), 'some message');6});7it('should fail', function() {8 throw createFatalError(new Error('fatal error'), 'some message', 'some title');9});10it('should fail', function() {11 throw createFatalError(new Error('fatal error'), 'some message', 'some title', 'some stack');12});13it('should fail', function() {14 throw createFatalError(new Error('fatal error'), 'some message', 'some title', 'some stack', 'some full title');15});16it('should fail', function() {17 throw createFatalError(new Error('fatal error'), 'some message', 'some title', 'some stack', 'some full title', 'some file');18});19it('should fail', function() {20 throw createFatalError(new Error('fatal error'), 'some message', 'some title', 'some stack', 'some full title', 'some file', 'some duration');21});22it('should fail', function() {23 throw createFatalError(new Error('fatal error'), 'some message', 'some title', 'some stack', 'some full title', 'some file', 'some duration', 'some current retry');24});25it('should fail', function() {26 throw createFatalError(new Error('fatal error'), 'some message', 'some title', 'some stack', 'some full title', 'some file', 'some duration', 'some current retry', 'some err');27});28it('should fail', function() {29 throw createFatalError(new Error('fatal error'), 'some message', 'some title', 'some stack', 'some full title', 'some file', 'some duration', 'some current retry', 'some err', 'some test');30});
Using AI Code Generation
1var assert = require('assert');2var Mocha = require('mocha');3var mocha = new Mocha();4var test = new Mocha.Test('test', function(){5 assert.ok(false, 'This will fail');6});7mocha.suite.addTest(test);8mocha.run(function(failures){9 process.on('exit', function () {10 });11});12 0 passing (7ms)13 at Context.<anonymous> (test.js:7:12)14 at callFn (node_modules\mocha\lib\runnable.js:351:21)15 at Test.Runnable.run (node_modules\mocha\lib\runnable.js:343:7)16 at Runner.runTest (node_modules\mocha\lib\runner.js:455:10)17 at next (node_modules\mocha\lib\runner.js:369:14)18 at next (node_modules\mocha\lib\runner.js:303:14)19 at Immediate._onImmediate (node_modules\mocha\lib\runner.js:347:5)20 at runCallback (timers.js:794:20)21 at tryOnImmediate (timers.js:752:5)22 at processImmediate [as _immediateCallback] (timers.js:729:5)
Using AI Code Generation
1var err = new Error('some error');2err.showDiff = true;3err.actual = 'foo';4err.expected = 'bar';5err.stack = 'some stack';6mocha.createFatalError(err);7var err = new Error('some error');8err.showDiff = true;9err.actual = 'foo';10err.expected = 'bar';11err.stack = 'some stack';12mocha.createFatalError(err);13var err = new Error('some error');14err.showDiff = true;15err.actual = 'foo';16err.expected = 'bar';17err.stack = 'some stack';18mocha.createFatalError(err);19var err = new Error('some error');20err.showDiff = true;21err.actual = 'foo';22err.expected = 'bar';23err.stack = 'some stack';24mocha.createFatalError(err);25var err = new Error('some error');26err.showDiff = true;27err.actual = 'foo';28err.expected = 'bar';29err.stack = 'some stack';30mocha.createFatalError(err);31var err = new Error('some error');32err.showDiff = true;33err.actual = 'foo';34err.expected = 'bar';35err.stack = 'some stack';36mocha.createFatalError(err);37var err = new Error('some error');38err.showDiff = true;39err.actual = 'foo';40err.expected = 'bar';41err.stack = 'some stack';42mocha.createFatalError(err);43var err = new Error('some error');44err.showDiff = true;45err.actual = 'foo';46err.expected = 'bar';47err.stack = 'some stack';48mocha.createFatalError(err);
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!