How to use fakeConnection method in wpt

Best JavaScript code snippet using wpt

_amqp_test.js

Source:_amqp_test.js Github

copy

Full Screen

1// Copyright (c) Microsoft. All rights reserved.2// Licensed under the MIT license. See LICENSE file in the project root for full license information.3'use strict';4var assert = require('chai').assert;5var sinon = require('sinon');6var sinonTestFactory = require('sinon-test');7var sinonTest = sinonTestFactory(sinon);8var AmqpMessage = require('../dist/amqp_message.js').AmqpMessage;9var Amqp = require('../dist/amqp.js').Amqp;10var MockCBSSecurityAgent = require('../dist/amqp_cbs.js');11var MockReceiverLink = require('../dist/receiver_link.js');12var MockSenderLink = require('../dist/sender_link.js');13var ReceiverLink = require('../dist/receiver_link.js').ReceiverLink;14var SenderLink = require('../dist/sender_link.js').SenderLink;15var results = require('azure-iot-common').results;16var errors = require('azure-iot-common').errors;17var Message = require('azure-iot-common').Message;18var EventEmitter = require('events').EventEmitter;19var uuid = require('uuid');20describe('Amqp', function () {21 sinon.test = sinonTest;22 /*Tests_SRS_NODE_COMMON_AMQP_16_042: [The Amqp constructor shall create a new `amqp10.Client` instance and configure it to:23 - not reconnect on failure24 - not reattach sender and receiver links on failure]*/25 describe('#policies', function () {26 it('sets the connection to not reconnect on failure', function () {27 var amqp = new Amqp();28 var fakeConnection = new EventEmitter();29 fakeConnection.name = 'connection';30 var fakeConnectionContext = {connection: fakeConnection};31 sinon.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});32 var fakeSession = new EventEmitter();33 var fakeSessionContext = {session: fakeSession};34 fakeConnection.create_session = sinon.stub().returns(fakeSession);35 fakeSession.open = () => {};36 sinon.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});37 amqp.connect({uri: 'uri'}, function(err) {38 assert.isNotOk(err,'client connected');39 assert(amqp._rheaContainer.connect.args[0][0].hasOwnProperty('reconnect'), 'connection parameter has reconnect property');40 assert.isFalse(amqp._rheaContainer.connect.args[0][0].reconnect, 'connection parameter reconnect is false');41 });42 });43 it('sets the links to not reattach on failure', function () {44 var amqp = new Amqp();45 var fakeConnection = new EventEmitter();46 fakeConnection.name = 'connection';47 var fakeConnectionContext = {connection: fakeConnection};48 sinon.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});49 var fakeSession = new EventEmitter();50 var fakeSessionContext = {session: fakeSession};51 fakeConnection.create_session = sinon.stub().returns(fakeSession);52 fakeSession.open = () => {};53 sinon.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});54 amqp.connect({uri: 'uri'}, function(err, res) {55 assert.isNotOk(err,'client connected');56 assert.isFalse(amqp._rheaContainer.options.sender_options.reconnect, 'rhea sender does not reconnect');57 assert.isFalse(amqp._rheaContainer.options.receiver_options.reconnect, 'rhea sender does not reconnect');58 });59 });60 });61 describe('#connect', function () {62 /*Tests_SRS_NODE_COMMON_AMQP_16_002: [The connect method shall establish a connection with the IoT hub instance and if given as argument call the `done` callback with a null error object in the case of success and a `results.Connected` object.]*/63 /*Tests_SRS_NODE_COMMON_AMQP_06_011: [The `connect` method shall set up a listener for responses to put tokens.]*/64 it('Calls the done callback when successfully connected', function(testCallback) {65 var amqp = new Amqp();66 var fakeConnection = new EventEmitter();67 fakeConnection.name = 'connection';68 var fakeConnectionContext = {connection: fakeConnection};69 sinon.stub(amqp._rheaContainer, 'connect').callsFake(() => {70 process.nextTick(() => {71 amqp._rheaConnection.emit('connection_open', fakeConnectionContext);72 });73 return fakeConnection;74 });75 var fakeSession = new EventEmitter();76 var fakeSessionContext = {session: fakeSession};77 fakeConnection.create_session = sinon.stub().returns(fakeSession);78 fakeSession.open = () => {};79 sinon.stub(fakeSession, 'open').callsFake(() => {80 process.nextTick(() => {81 fakeSession.emit('session_open', fakeSessionContext);82 });83 });84 amqp.connect({uri: 'uri'}, function(err, res) {85 if (err) testCallback(err);86 else {87 assert.instanceOf(res, results.Connected);88 testCallback();89 }90 });91 });92 it('Calls the done callback immediately when already connected', function(testCallback) {93 var amqp = new Amqp();94 var fakeConnection = new EventEmitter();95 fakeConnection.name = 'connection';96 var fakeConnectionContext = {connection: fakeConnection};97 sinon.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});98 var fakeSession = new EventEmitter();99 var fakeSessionContext = {session: fakeSession};100 fakeConnection.create_session = sinon.stub().returns(fakeSession);101 fakeSession.open = () => {};102 sinon.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});103 amqp.connect({uri: 'uri'}, function(err, res) {104 if (err) testCallback(err);105 else {106 assert.instanceOf(res, results.Connected);107 assert(amqp._rheaContainer.connect.calledOnce);108 amqp.connect({uri: 'uri'}, function(err, res) {109 if (err) testCallback(err);110 else {111 assert.instanceOf(res, results.Connected);112 assert(amqp._rheaContainer.connect.calledOnce);113 }114 });115 testCallback();116 }117 });118 });119 /*Tests_SRS_NODE_COMMON_AMQP_16_003: [If given as an argument, the connect method shall call the `done` callback with a standard `Error` object if the connection fails.]*/120 it('Calls the done callback with an error if connecting fails (disconnected)', function(testCallback) {121 var amqp = new Amqp();122 var fakeConnection = new EventEmitter();123 var fakeConnectionContext = {connection: fakeConnection};124 fakeConnection.name = 'connection';125 fakeConnection.error = new Error();126 sinon.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('disconnected', fakeConnectionContext)}); return fakeConnection});127 amqp.connect({uri: 'uri'}, function(err) {128 assert.instanceOf(err, Error);129 testCallback();130 });131 });132 it('Calls the done callback with an error if connecting fails (auth error)', function(testCallback) {133 var amqp = new Amqp();134 var fakeConnection = new EventEmitter();135 var fakeConnectionContext = {container: amqp._rheaContainer, connection: fakeConnection};136 fakeConnection.error = new Error();137 sinon.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_error', fakeConnectionContext);amqp._rheaConnection.emit('connection_close', fakeConnectionContext)}); return fakeConnection});138 amqp.connect({uri: 'uri'}, function(err) {139 assert.strictEqual(err, fakeConnection.error);140 testCallback();141 });142 });143 it('Calls the done callback with an error if an error is emitted to the connection object', function(testCallback) {144 var amqp = new Amqp();145 var fakeConnection = new EventEmitter();146 var fakeConnectionContext = {container: amqp._rheaContainer, connection: fakeConnection};147 fakeConnection.error = new Error();148 sinon.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('error', fakeConnectionContext);}); return fakeConnection});149 amqp.connect({uri: 'uri'}, function(err) {150 assert.strictEqual(err, fakeConnection.error);151 testCallback();152 });153 });154 describe('#session begin', function() {155 it('invokes the connect callback with an error if the session begin fails', (testCallback) => {156 var amqp = new Amqp();157 var fakeSessionError = new Error('fake session error');158 var fakeConnection = new EventEmitter();159 fakeConnection.close = () => {};160 sinon.stub(fakeConnection, 'close').callsFake(() => {161 process.nextTick(() => {162 amqp._rheaConnection.emit('connection_close', fakeConnectionContext);163 });164 });165 fakeConnection.name = 'connection';166 var fakeConnectionContext = {connection: fakeConnection};167 sinon.stub(amqp._rheaContainer, 'connect').callsFake(() => {168 process.nextTick(() => {169 fakeConnection.emit('connection_open', fakeConnectionContext);170 });171 return fakeConnection;172 });173 var fakeSession = new EventEmitter();174 fakeSession.close = sinon.stub();175 var fakeSessionContext = {session: fakeSession};176 fakeConnection.create_session = sinon.stub().returns(fakeSession);177 fakeSession.open = () => {};178 sinon.stub(fakeSession, 'open').callsFake(() => {179 process.nextTick(() => {180 fakeSession.error = fakeSessionError;181 fakeSession.emit('session_error', fakeSessionContext);182 fakeSession.error = undefined;183 fakeSession.emit('session_close', fakeSessionContext);184 });185 });186 amqp.connect({uri: 'uri'}, function(err) {187 assert.strictEqual(err, fakeSessionError);188 testCallback();189 });190 })191 it('invokes the connect callback with an error if a connect error occurs while connecting the session', (testCallback) => {192 var amqp = new Amqp();193 var fakeConnectionError = new Error('fake connection error');194 var fakeConnection = new EventEmitter();195 fakeConnection.close = () => {};196 sinon.stub(fakeConnection, 'close').callsFake(() => {197 process.nextTick(() => {198 amqp._rheaConnection.emit('connection_close', fakeConnectionContext);199 });200 });201 fakeConnection.name = 'connection';202 var fakeConnectionContext = {connection: fakeConnection};203 sinon.stub(amqp._rheaContainer, 'connect').callsFake(() => {204 process.nextTick(() => {205 fakeConnection.emit('connection_open', fakeConnectionContext);206 });207 return fakeConnection;208 });209 var fakeSession = new EventEmitter();210 fakeSession.close = sinon.stub();211 fakeConnection.create_session = sinon.stub().returns(fakeSession);212 fakeSession.open = () => {};213 sinon.stub(fakeSession, 'open').callsFake(() => {214 process.nextTick(() => {215 fakeConnection.error = fakeConnectionError;216 fakeConnection.emit('connection_error', fakeConnectionContext);217 fakeConnection.error = undefined;218 fakeConnection.emit('connection_close', fakeConnectionContext);219 });220 });221 amqp.connect({uri: 'uri'}, function(err) {222 assert.strictEqual(err, fakeConnectionError);223 testCallback();224 });225 });226 it('invokes the connect callback with an error if a disconnect error occurs while connecting the session', (testCallback) => {227 var amqp = new Amqp();228 var fakeConnection = new EventEmitter();229 fakeConnection.close = () => {};230 sinon.stub(fakeConnection, 'close').callsFake(() => {231 process.nextTick(() => {232 amqp._rheaConnection.emit('connection_close', fakeConnectionContext);233 });234 });235 fakeConnection.name = 'connection';236 var fakeConnectionContext = {connection: fakeConnection};237 sinon.stub(amqp._rheaContainer, 'connect').callsFake(() => {238 process.nextTick(() => {239 fakeConnection.emit('connection_open', fakeConnectionContext);240 });241 return fakeConnection;242 });243 var fakeSession = new EventEmitter();244 fakeSession.close = sinon.stub();245 fakeConnection.create_session = sinon.stub().returns(fakeSession);246 fakeSession.open = () => {};247 sinon.stub(fakeSession, 'open').callsFake(() => {248 process.nextTick(() => {249 fakeConnection.emit('disconnected', fakeConnectionContext)250 });251 });252 amqp.connect({uri: 'uri'}, function(err) {253 assert.instanceOf(err, errors.NotConnectedError);254 testCallback();255 });256 });257 it('invokes the connect callback with an error if an `error` occurs while connecting the session', (testCallback) => {258 var amqp = new Amqp();259 var fakeConnectionError = new Error('fake connection error');260 var fakeConnection = new EventEmitter();261 fakeConnection.close = () => {};262 sinon.stub(fakeConnection, 'close').callsFake(() => {263 process.nextTick(() => {264 amqp._rheaConnection.emit('connection_close', fakeConnectionContext);265 });266 });267 fakeConnection.name = 'connection';268 var fakeConnectionContext = {connection: fakeConnection};269 sinon.stub(amqp._rheaContainer, 'connect').callsFake(() => {270 process.nextTick(() => {271 fakeConnection.emit('connection_open', fakeConnectionContext);272 });273 return fakeConnection;274 });275 var fakeSession = new EventEmitter();276 fakeSession.close = sinon.stub();277 fakeConnection.create_session = sinon.stub().returns(fakeSession);278 fakeSession.open = () => {};279 sinon.stub(fakeSession, 'open').callsFake(() => {280 process.nextTick(() => {281 fakeConnection.error = fakeConnectionError;282 fakeConnection.emit('error', fakeConnectionContext)283 fakeConnection.error = undefined;284 });285 });286 amqp.connect({uri: 'uri'}, function(err) {287 assert.strictEqual(err, fakeConnectionError, 'inappropriate error indicated');288 testCallback();289 });290 });291 });292 describe('#connection failures', function() {293 it('invokes the disconnect handler with an error if the connection fails - returns to the disconnected state.', (testCallback) => {294 var amqp = new Amqp();295 var fakeConnection = new EventEmitter();296 var fakeConnectionError = new Error('fake connection error');297 fakeConnection.name = 'connection';298 var fakeConnectionContext = {connection: fakeConnection};299 sinon.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});300 fakeConnection.close = () => {};301 sinon.stub(fakeConnection, 'close').callsFake(() => {302 process.nextTick(() => {303 amqp._rheaConnection.emit('connection_close', fakeConnectionContext);304 });305 });306 var fakeSession = new EventEmitter();307 var fakeSessionContext = {session: fakeSession};308 fakeConnection.create_session = sinon.stub().returns(fakeSession);309 fakeSession.open = () => {};310 sinon.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});311 fakeSession.close = () => {};312 sinon.stub(fakeSession, 'close').callsFake(() => {313 process.nextTick(() => {314 amqp._rheaSession.emit('session_close', fakeSessionContext);315 });316 });317 amqp.setDisconnectHandler(function(err) {318 assert.strictEqual(err, fakeConnectionError, 'inappropriate error indicated to disconnect handler');319 assert(amqp._fsm.state, 'disconnected', 'did not return to the disconnected state');320 testCallback();321 });322 amqp.connect({uri: 'uri'}, function(err) {323 assert.isNotOk(err);324 assert(amqp._fsm.state, 'connected', 'did not transition to the `connected` state');325 fakeConnection.error = fakeConnectionError;326 fakeConnection.emit('connection_error', fakeConnectionContext);327 fakeConnection.error = undefined;328 fakeConnection.emit('connection_close', fakeConnectionContext);329 });330 });331 it('invokes the disconnect handler with an error if the session fails - returns to the disconnected state.', (testCallback) => {332 var amqp = new Amqp();333 var fakeConnection = new EventEmitter();334 var fakeSessionError = new Error('fake session error');335 fakeConnection.name = 'connection';336 var fakeConnectionContext = {connection: fakeConnection};337 sinon.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});338 fakeConnection.close = () => {};339 sinon.stub(fakeConnection, 'close').callsFake(() => {340 process.nextTick(() => {341 amqp._rheaConnection.emit('connection_close', fakeConnectionContext);342 });343 });344 var fakeSession = new EventEmitter();345 var fakeSessionContext = {session: fakeSession};346 fakeConnection.create_session = sinon.stub().returns(fakeSession);347 fakeSession.open = () => {};348 sinon.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});349 fakeSession.close = () => {};350 sinon.stub(fakeSession, 'close').callsFake(() => {351 process.nextTick(() => {352 amqp._rheaSession.emit('session_close', fakeSessionContext);353 });354 });355 amqp.setDisconnectHandler(function(err) {356 assert.strictEqual(err, fakeSessionError, 'inappropriate error indicated to disconnect handler');357 assert(amqp._fsm.state, 'disconnected', 'did not return to the disconnected state');358 testCallback();359 });360 amqp.connect({uri: 'uri'}, function(err) {361 assert.isNotOk(err);362 assert(amqp._fsm.state, 'connected', 'did not transition to the `connected` state');363 fakeSession.error = fakeSessionError;364 fakeSession.emit('session_error', fakeSessionContext);365 fakeSession.error = undefined;366 fakeSession.emit('session_close', fakeSessionContext);367 });368 });369 it('invokes the disconnect handler with an error if an `error` is emitted - returns to the disconnected state.', (testCallback) => {370 var amqp = new Amqp();371 var fakeConnection = new EventEmitter();372 var fakeConnectionError = new Error('fake connection error');373 fakeConnection.name = 'connection';374 var fakeConnectionContext = {connection: fakeConnection};375 sinon.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});376 fakeConnection.close = () => {};377 sinon.stub(fakeConnection, 'close').callsFake(() => {378 process.nextTick(() => {379 amqp._rheaConnection.emit('connection_close', fakeConnectionContext);380 });381 });382 var fakeSession = new EventEmitter();383 var fakeSessionContext = {session: fakeSession};384 fakeConnection.create_session = sinon.stub().returns(fakeSession);385 fakeSession.open = () => {};386 sinon.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});387 fakeSession.close = () => {};388 sinon.stub(fakeSession, 'close').callsFake(() => {389 process.nextTick(() => {390 amqp._rheaSession.emit('session_close', fakeSessionContext);391 });392 });393 amqp.setDisconnectHandler(function(err) {394 assert.strictEqual(err, fakeConnectionError, 'inappropriate error indicated to disconnect handler');395 assert(amqp._fsm.state, 'disconnected', 'did not return to the disconnected state');396 testCallback();397 });398 amqp.connect({uri: 'uri'}, function(err) {399 assert.isNotOk(err);400 assert(amqp._fsm.state, 'connected', 'did not transition to the `connected` state');401 fakeConnection.error = fakeConnectionError;402 fakeConnection.emit('error', fakeConnectionContext);403 fakeConnection.error = undefined;404 });405 });406 });407 });408 describe('#setDisconnectHandler', function() {409 it('disconnect callback is called when the \'disconnected\' event is emitted while connected', function(testCallback) {410 var amqp = new Amqp();411 var fakeConnection = new EventEmitter();412 fakeConnection.name = 'connection';413 var fakeConnectionContext = {connection: fakeConnection};414 sinon.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});415 var fakeSession = new EventEmitter();416 fakeSession.name = 'session';417 var fakeSessionContext = {connection: fakeConnection, session: fakeSession};418 fakeConnection.create_session = sinon.stub().returns(fakeSession);419 fakeSession.open = () => {};420 sinon.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});421 amqp.setDisconnectHandler(function() {422 testCallback();423 });424 amqp.connect({uri: 'uri'}, function () {425 var fakeError = new Error('Connected closed');426 fakeConnection.error = fakeError;427 fakeConnection.emit('disconnected', fakeConnectionContext);428 });429 });430 it('ignores the disconnected event if already disconnected', function (testCallback) {431 var amqp = new Amqp();432 amqp.setDisconnectHandler(function() {433 assert.fail();434 });435 amqp._rheaContainer.emit('disconnected');436 testCallback();437 });438 it('ignores the disconnected event if fired while connecting', function (testCallback) {439 var amqp = new Amqp();440 var fakeConnection = new EventEmitter();441 fakeConnection.name = 'connection';442 var fakeConnectionContext = {connection: fakeConnection};443 sinon.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});444 var fakeSession = new EventEmitter();445 fakeSession.name = 'session';446 fakeConnection.create_session = sinon.stub().returns(fakeSession);447 fakeSession.open = () => sinon.stub();448 amqp.setDisconnectHandler(function() {449 assert.fail();450 });451 amqp.connect({uri: 'uri'}, function() {});452 fakeConnection.emit('disconnected', fakeConnectionContext);453 testCallback();454 });455 it('ignores the disconnected event if fired while disconnecting', function (testCallback) {456 var amqp = new Amqp();457 var fakeConnection = new EventEmitter();458 fakeConnection.name = 'connection';459 var fakeConnectionContext = {connection: fakeConnection};460 sinon.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});461 var fakeSession = new EventEmitter();462 fakeSession.name = 'session';463 var fakeSessionContext = {connection: fakeConnection, session: fakeSession};464 fakeConnection.create_session = sinon.stub().returns(fakeSession);465 fakeConnection.close = sinon.stub();466 fakeSession.close = sinon.stub();467 fakeSession.open = () => {};468 sinon.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});469 fakeConnection.close = sinon.stub();470 amqp.setDisconnectHandler(function() {471 assert.fail();472 });473 amqp.connect({uri: 'uri'}, () => {474 amqp.disconnect(function () { });475 fakeConnection.error = new Error('connection disconnected');476 fakeConnection.emit('disconnected', fakeConnectionContext);477 testCallback();478 });479 });480 });481 describe('#disconnect', function() {482 /*Tests_SRS_NODE_COMMON_AMQP_16_034: [The `disconnect` method shall detach all open links before disconnecting the underlying AMQP client.]*/483 it('detaches the CBS endpoints before disconnecting the client', function(testCallback) {484 var amqp = new Amqp();485 var fakeConnection = new EventEmitter();486 fakeConnection.name = 'connection';487 var fakeConnectionContext = {connection: fakeConnection};488 sinon.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});489 var fakeSession = new EventEmitter();490 fakeSession.name = 'session';491 var fakeSessionContext = {connection: fakeConnection, session: fakeSession};492 fakeConnection.create_session = sinon.stub().returns(fakeSession);493 fakeConnection.close = () => {};494 sinon.stub(fakeConnection, 'close').callsFake(() => {process.nextTick(() => {fakeConnection.emit('connection_close', fakeConnectionContext)})});495 fakeSession.close = () => {};496 sinon.stub(fakeSession, 'close').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_close', fakeSessionContext)})});497 fakeSession.open = () => {};498 sinon.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});499 amqp._cbs = {500 detach: sinon.stub().callsArg(0)501 };502 amqp.connect({uri: 'uri'}, function() {503 amqp.disconnect(function(err) {504 if (err) {505 testCallback(err);506 } else {507 testCallback();508 }509 });510 });511 });512 /*Tests_SRS_NODE_COMMON_AMQP_16_034: [The `disconnect` method shall detach all open links before disconnecting the underlying AMQP client.]*/513 it('detaches existing links before disconnecting the client', function(testCallback) {514 var amqp = new Amqp();515 var fakeConnection = new EventEmitter();516 fakeConnection.name = 'connection';517 var fakeConnectionContext = {connection: fakeConnection};518 sinon.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});519 var fakeSession = new EventEmitter();520 fakeSession.name = 'session';521 var fakeSessionContext = {connection: fakeConnection, session: fakeSession};522 fakeConnection.create_session = sinon.stub().returns(fakeSession);523 fakeConnection.close = () => {};524 sinon.stub(fakeConnection, 'close').callsFake(() => {process.nextTick(() => {fakeConnection.emit('connection_close', fakeConnectionContext)})});525 fakeSession.close = () => {};526 sinon.stub(fakeSession, 'close').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_close', fakeSessionContext)})});527 fakeSession.open = () => {};528 sinon.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});529 var fakeSender = {530 detach: sinon.stub().callsArg(0)531 };532 var fakeReceiver = {533 detach: sinon.stub().callsArg(0)534 };535 amqp.connect({uri: 'uri'}, function() {536 amqp._senders.fake_sender_endpoint = fakeSender;537 amqp._receivers.fake_receiver_endpoint = fakeReceiver;538 amqp.disconnect(function(err) {539 if (err) {540 testCallback(err);541 } else {542 assert(fakeSender.detach.calledOnce);543 assert(fakeReceiver.detach.calledOnce);544 testCallback();545 }546 });547 });548 });549 /*Tests_SRS_NODE_COMMON_AMQP_16_004: [The disconnect method shall call the `done` callback when the application/service has been successfully disconnected from the service]*/550 it('calls the done callback if disconnected successfully', function(testCallback) {551 var amqp = new Amqp();552 var fakeConnection = new EventEmitter();553 fakeConnection.name = 'connection';554 var fakeConnectionContext = {connection: fakeConnection};555 sinon.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});556 var fakeSession = new EventEmitter();557 fakeSession.name = 'session';558 var fakeSessionContext = {connection: fakeConnection, session: fakeSession};559 fakeConnection.create_session = sinon.stub().returns(fakeSession);560 fakeConnection.close = () => {};561 sinon.stub(fakeConnection, 'close').callsFake(() => {process.nextTick(() => {fakeConnection.emit('connection_close', fakeConnectionContext)})});562 fakeSession.close = () => {};563 sinon.stub(fakeSession, 'close').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_close', fakeSessionContext)})});564 fakeSession.open = () => {};565 sinon.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});566 amqp.connect({uri: 'uri'}, function() {567 amqp.disconnect(function(err) {568 testCallback(err);569 });570 });571 });572 /*Tests_SRS_NODE_COMMON_AMQP_06_007: [While disconnecting, if the run down does not complete within 45 seconds, the code will be re-run with `forceDetach`es.]*/573 it('Re-invokes the rundown if no responses on network within timeout', function(testCallback) {574 this.clock = sinon.useFakeTimers();575 var amqp = new Amqp();576 var fakeConnection = new EventEmitter();577 fakeConnection.name = 'connection';578 var fakeConnectionContext = {connection: fakeConnection};579 sinon.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});580 var fakeSession = new EventEmitter();581 fakeSession.name = 'session';582 var fakeSessionContext = {connection: fakeConnection, session: fakeSession};583 fakeConnection.create_session = sinon.stub().returns(fakeSession);584 fakeConnection.close = () => {};585 sinon.stub(fakeConnection, 'close').callsFake(() => {process.nextTick(() => {fakeConnection.emit('connection_close', fakeConnectionContext)})});586 fakeSession.close = () => {};587 sinon.stub(fakeSession, 'close').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_close', fakeSessionContext)})});588 fakeSession.open = () => {};589 sinon.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});590 var fakeSender = {591 detach: sinon.stub(),592 forceDetach: sinon.stub()593 };594 var fakeReceiver = {595 detach: sinon.stub(),596 forceDetach: sinon.stub()597 };598 amqp.connect({uri: 'uri'}, function() {599 amqp._senders.fake_sender_endpoint = fakeSender;600 amqp._receivers.fake_receiver_endpoint = fakeReceiver;601 amqp.disconnect(function(err) {602 assert(fakeSender.detach.calledOnce);603 assert(fakeSender.forceDetach.calledOnce);604 assert(fakeReceiver.detach.calledOnce);605 assert(fakeReceiver.forceDetach.calledOnce);606 testCallback(err);607 }.bind(this));608 //609 // The detaches should have been called but the removes should not yet have been called.610 //611 assert(fakeSender.detach.calledOnce);612 assert(fakeSender.forceDetach.notCalled);613 assert(fakeReceiver.detach.calledOnce);614 assert(fakeReceiver.forceDetach.notCalled);615 this.clock.tick(46000);616 }.bind(this));617 });618 /*Tests_SRS_NODE_COMMON_AMQP_16_005: [The disconnect method shall call the `done` callback and pass the error as a parameter if the disconnection is unsuccessful]*/619 it('calls the done callback with an error if there\'s an error while disconnecting', function(testCallback) {620 var amqp = new Amqp();621 var fakeConnection = new EventEmitter();622 fakeConnection.name = 'connection';623 var fakeConnectionContext = {connection: fakeConnection};624 sinon.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});625 var fakeSession = new EventEmitter();626 fakeSession.name = 'session';627 var fakeSessionContext = {connection: fakeConnection, session: fakeSession};628 fakeConnection.create_session = sinon.stub().returns(fakeSession);629 fakeConnection.close = () => {};630 sinon.stub(fakeConnection, 'close').callsFake(() => {process.nextTick(() => {fakeConnection.error = new Error('connection error'); fakeConnection.emit('connection_error', fakeConnectionContext); fakeConnection.error = undefined; fakeConnection.emit('connection_close', fakeConnectionContext)})});631 fakeSession.close = () => {};632 sinon.stub(fakeSession, 'close').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_close', fakeSessionContext)})});633 fakeSession.open = () => {};634 sinon.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});635 amqp.connect({uri: 'uri'}, function() {636 amqp.disconnect(function(err) {637 if (err) {638 assert.instanceOf(err, Error);639 testCallback();640 } else {641 testCallback(new Error('disconnect callback was called without an error'));642 }643 });644 });645 });646 it('immediately calls the callback if already disconnected', function(testCallback) {647 var amqp = new Amqp();648 amqp.disconnect(function(err) {649 assert.isNull(err);650 testCallback();651 });652 });653 it('ignores client errors emitted while disconnecting', function (testCallback) {654 var amqp = new Amqp();655 var fakeConnection = new EventEmitter();656 fakeConnection.name = 'connection';657 var fakeConnectionContext = {connection: fakeConnection};658 sinon.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});659 var fakeSession = new EventEmitter();660 fakeSession.name = 'session';661 var fakeSessionContext = {connection: fakeConnection, session: fakeSession};662 fakeConnection.create_session = sinon.stub().returns(fakeSession);663 fakeConnection.close = sinon.stub();664 fakeSession.close = () => {};665 sinon.stub(fakeSession, 'close').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_close', fakeSessionContext)})});666 fakeSession.open = () => {};667 sinon.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});668 amqp.setDisconnectHandler(function() {669 assert.fail();670 });671 amqp.connect({uri: 'uri'}, function() {672 amqp.disconnect(function() {});673 fakeConnection.error = new Error('should be ignored');674 fakeConnection.emit('error', fakeConnectionContext);675 testCallback();676 });677 });678 });679 describe('#connect using custom SASL', function() {680 it.skip('sets the saslMechanism property in the policyOverride object', function (testCallback) {681 var amqp = new Amqp();682 var connectStub = sinon.stub(amqp._amqp, 'connect').resolves();683 var fakeSaslName = 'FAKE';684 var fakeSaslMechanism = { getInitFrame: function () {}, getResponseFrame: function () {}};685 var config = {686 uri: 'uri',687 saslMechanismName: fakeSaslName,688 saslMechanism: fakeSaslMechanism689 };690 amqp.connect(config, function () {691 assert.strictEqual(connectStub.firstCall.args[1].saslMechanism, fakeSaslName);692 testCallback();693 });694 });695 it.skip('calls registerSaslMechanism on the amqp10 client', function (testCallback) {696 var amqp = new Amqp();697 sinon.stub(amqp._amqp, 'connect').resolves();698 var registerSaslMechanismStub = sinon.stub(amqp._amqp, 'registerSaslMechanism');699 var fakeSaslName = 'FAKE';700 var fakeSaslMechanism = { getInitFrame: function () {}, getResponseFrame: function () {}};701 var config= {702 uri: 'uri',703 saslMechanismName: fakeSaslName,704 saslMechanism: fakeSaslMechanism705 };706 amqp.connect(config, function () {707 assert.strictEqual(registerSaslMechanismStub.firstCall.args[0], fakeSaslName);708 assert.strictEqual(registerSaslMechanismStub.firstCall.args[1], fakeSaslMechanism);709 testCallback();710 });711 });712 });713 describe('#send', function() {714 it('calls the done callback with a MessageEnqueued result if it successful', sinon.test(function(testCallback) {715 var amqp = new Amqp();716 var fakeConnection = new EventEmitter();717 fakeConnection.name = 'connection';718 var fakeConnectionContext = {connection: fakeConnection};719 this.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});720 var fakeSession = new EventEmitter();721 var fakeSessionContext = {session: fakeSession};722 fakeConnection.create_session = this.stub().returns(fakeSession);723 fakeSession.open = () => {};724 this.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});725 amqp.connect({uri: 'uri'}, () => {726 var fakeLink = new SenderLink('endpoint', undefined, fakeSession);727 fakeLink.attach = this.stub().callsArg(0);728 fakeLink.send = this.stub().callsArgWith(1, null, new results.MessageEnqueued());729 this.stub(MockSenderLink, 'SenderLink').returns(fakeLink);730 amqp.send(new Message('message'), 'endpoint', 'deviceId', function(err, result) {731 if(!err) {732 assert.instanceOf(result, results.MessageEnqueued);733 }734 testCallback(err);735 });736 });737 }));738 it('encodes the security interface id correctly', sinon.test(function(testCallback) {739 var amqp = new Amqp();740 var fakeConnection = new EventEmitter();741 fakeConnection.name = 'connection';742 var fakeConnectionContext = {connection: fakeConnection};743 this.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});744 var fakeSession = new EventEmitter();745 var fakeSessionContext = {session: fakeSession};746 fakeConnection.create_session = this.stub().returns(fakeSession);747 fakeSession.open = () => {};748 this.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});749 assert.doesNotThrow(() => {750 amqp.connect({uri: 'uri'}, () => {751 var fakeLink = new SenderLink('endpoint', undefined, fakeSession);752 fakeLink.attach = this.stub().callsArg(0);753 fakeLink.send = this.stub().callsArgWith(1, null, new results.MessageEnqueued());754 this.stub(MockSenderLink, 'SenderLink').returns(fakeLink);755 var msg = new Message('message');756 msg.setAsSecurityMessage();757 amqp.send(msg, 'endpoint', undefined, function() {758 assert.equal(fakeLink.send.args[0][0]['message_annotations']['iothub-interface-id'], 'urn:azureiot:Security:SecurityAgent:1');759 testCallback();760 });761 });762 });763 }));764 /*Tests_SRS_NODE_COMMON_AMQP_16_007: [If send encounters an error before it can send the request, it shall invoke the `done` callback function and pass the standard JavaScript Error object with a text description of the error (err.message).]*/765 it('calls the done callback with an Error if creating a sender fails', sinon.test(function(testCallback) {766 var amqp = new Amqp();767 var fakeConnection = new EventEmitter();768 fakeConnection.name = 'connection';769 var fakeConnectionContext = {connection: fakeConnection};770 this.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});771 var fakeSession = new EventEmitter();772 var fakeSessionContext = {session: fakeSession};773 fakeConnection.create_session = this.stub().returns(fakeSession);774 fakeSession.open = () => {};775 this.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});776 amqp.connect({uri: 'uri'}, () => {777 var fakeError = new Error('bad sender attach');778 var fakeLink = new SenderLink('endpoint', undefined, fakeSession);779 fakeLink.attach = this.stub().callsArgWith(0,fakeError);780 this.stub(MockSenderLink, 'SenderLink').returns(fakeLink);781 amqp.send(new Message('message'), 'endpoint', 'deviceId', function(err) {782 assert.strictEqual(err, fakeError, 'incorrect error returned from attach for send');783 testCallback();784 });785 });786 }));787 it('calls the done callback with an Error if the sender fails to send the message', sinon.test(function(testCallback) {788 var amqp = new Amqp();789 var fakeConnection = new EventEmitter();790 fakeConnection.name = 'connection';791 var fakeConnectionContext = {connection: fakeConnection};792 this.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});793 var fakeSession = new EventEmitter();794 var fakeSessionContext = {session: fakeSession};795 fakeConnection.create_session = this.stub().returns(fakeSession);796 fakeSession.open = () => {};797 this.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});798 amqp.connect({uri: 'uri'}, () => {799 var fakeError = new Error('bad sender send');800 var fakeLink = new SenderLink('endpoint', undefined, fakeSession);801 fakeLink.attach = this.stub().callsArg(0);802 fakeLink.send = this.stub().callsArgWith(1, fakeError);803 this.stub(MockSenderLink, 'SenderLink').returns(fakeLink);804 amqp.send(new Message('message'), 'endpoint', 'deviceId', function(err) {805 assert.strictEqual(err, fakeError, 'incorrect error returned from attach for send');806 testCallback();807 });808 });809 }));810 it('Reuses the same sender link if already created', sinon.test(function(testCallback) {811 var amqp = new Amqp();812 var fakeConnection = new EventEmitter();813 fakeConnection.name = 'connection';814 var fakeConnectionContext = {connection: fakeConnection};815 this.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});816 var fakeSession = new EventEmitter();817 var fakeSessionContext = {session: fakeSession};818 fakeConnection.create_session = this.stub().returns(fakeSession);819 fakeSession.open = () => {};820 this.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});821 amqp.connect({uri: 'uri'}, () => {822 var fakeLink = new SenderLink('endpoint', undefined, fakeSession);823 fakeLink.attach = this.stub().callsArg(0);824 fakeLink.send = this.stub().callsArgWith(1, null, new results.MessageEnqueued());825 this.stub(MockSenderLink, 'SenderLink').returns(fakeLink);826 amqp.send(new Message('message'), 'endpoint', 'deviceId', function(err, result) {827 if (err) {828 testCallback(err);829 } else {830 assert.instanceOf(result, results.MessageEnqueued);831 assert(MockSenderLink.SenderLink.calledOnce);832 amqp.send(new Message('message'), 'endpoint', 'deviceId', function(err, result) {833 if (!err) {834 assert.instanceOf(result, results.MessageEnqueued);835 assert(MockSenderLink.SenderLink.calledOnce);836 }837 testCallback(err);838 });839 }840 });841 });842 }));843 it('does not populate the \'to\' property of the amqp message if not passed', sinon.test(function(testCallback) {844 var amqp = new Amqp();845 var fakeConnection = new EventEmitter();846 fakeConnection.name = 'connection';847 var fakeConnectionContext = {connection: fakeConnection};848 this.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});849 var fakeSession = new EventEmitter();850 var fakeSessionContext = {session: fakeSession};851 fakeConnection.create_session = this.stub().returns(fakeSession);852 fakeSession.open = () => {};853 this.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});854 assert.doesNotThrow(() => {855 amqp.connect({uri: 'uri'}, () => {856 var fakeLink = new SenderLink('endpoint', undefined, fakeSession);857 fakeLink.attach = this.stub().callsArg(0);858 fakeLink.send = this.stub().callsArgWith(1, null, new results.MessageEnqueued());859 this.stub(MockSenderLink, 'SenderLink').returns(fakeLink);860 amqp.send(new Message('message'), 'endpoint', undefined, function() {861 assert.isUndefined(fakeLink.send.args[0][0].to);862 testCallback();863 });864 });865 });866 }));867 /*Tests_SRS_NODE_COMMON_AMQP_16_011: [All methods should treat the `done` callback argument as optional and not throw if it is not passed as argument.]*/868 it('does not throw on success if no callback is provided', sinon.test(function(testCallback) {869 var amqp = new Amqp();870 var fakeConnection = new EventEmitter();871 fakeConnection.name = 'connection';872 var fakeConnectionContext = {connection: fakeConnection};873 this.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});874 var fakeSession = new EventEmitter();875 var fakeSessionContext = {session: fakeSession};876 fakeConnection.create_session = this.stub().returns(fakeSession);877 fakeSession.open = () => {};878 this.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});879 assert.doesNotThrow(() => {880 var fakeLink = new SenderLink('endpoint', undefined, fakeSession);881 fakeLink.attach = this.stub().callsArg(0);882 fakeLink.send = this.stub();883 this.stub(MockSenderLink, 'SenderLink').returns(fakeLink);884 amqp.connect({uri: 'uri'}, () => {885 amqp.send(new Message('message'), 'endpoint', 'deviceId');886 assert(fakeLink.send.calledOnce, 'the link send api not invoked');887 testCallback();888 });889 });890 }));891 it('does not throw on error if no callback is provided', sinon.test(function(testCallback) {892 //893 // Effectively this is the same as the previous test.894 //895 // We are NOT testing whether rhea senders can handle not having a callback. We're testing that OUR transport896 // can handle not having a transport.897 //898 var amqp = new Amqp();899 var fakeConnection = new EventEmitter();900 fakeConnection.name = 'connection';901 var fakeConnectionContext = {connection: fakeConnection};902 this.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});903 var fakeSession = new EventEmitter();904 var fakeSessionContext = {session: fakeSession};905 fakeConnection.create_session = this.stub().returns(fakeSession);906 fakeSession.open = () => {};907 this.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});908 assert.doesNotThrow(() => {909 var fakeLink = new SenderLink('endpoint', undefined, fakeSession);910 fakeLink.attach = this.stub().callsArg(0);911 fakeLink.send = this.stub();912 this.stub(MockSenderLink, 'SenderLink').returns(fakeLink);913 amqp.connect({uri: 'uri'}, () => {914 amqp.send(new Message('message'), 'endpoint', 'deviceId');915 assert(fakeLink.send.calledOnce, 'the link send api not invoked');916 testCallback();917 });918 });919 }));920 });921 describe('#getReceiver', function() {922 /*Tests_SRS_NODE_COMMON_AMQP_16_010: [If a receiver for this endpoint doesn't exist, the getReceiver method should create a new AmqpReceiver object and then call the `done` method with the object that was just created as an argument.]*/923 it('calls the done callback with a null Error and a receiver if successful', sinon.test(function(testCallback) {924 var amqp = new Amqp();925 var fakeConnection = new EventEmitter();926 fakeConnection.name = 'connection';927 var fakeConnectionContext = {connection: fakeConnection};928 this.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});929 var fakeSession = new EventEmitter();930 var fakeSessionContext = {session: fakeSession};931 fakeConnection.create_session = this.stub().returns(fakeSession);932 fakeSession.open = () => {};933 this.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});934 amqp.connect({uri: 'uri'}, () => {935 var fakeLink = new ReceiverLink('endpoint', undefined, fakeSession);936 fakeLink.attach = this.stub().callsArg(0);937 this.stub(MockReceiverLink, 'ReceiverLink').returns(fakeLink);938 amqp.getReceiver('endpoint', function(err, receiver) {939 assert.instanceOf(receiver, ReceiverLink);940 testCallback(err);941 });942 });943 }));944 /*Tests_SRS_NODE_COMMON_AMQP_16_009: [If a receiver for this endpoint has already been created, the getReceiver method should call the `done` method with the existing instance as an argument.]*/945 it('gets the existing receiver for an endpoint if it was previously created', sinon.test(function(testCallback) {946 var amqp = new Amqp();947 var fakeConnection = new EventEmitter();948 fakeConnection.name = 'connection';949 var fakeConnectionContext = {connection: fakeConnection};950 this.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});951 var fakeSession = new EventEmitter();952 var fakeSessionContext = {session: fakeSession};953 fakeConnection.create_session = this.stub().returns(fakeSession);954 fakeSession.open = () => {};955 this.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});956 amqp.connect({uri: 'uri'}, () => {957 var fakeLink = new ReceiverLink('endpoint', undefined, fakeSession);958 fakeLink.attach = this.stub().callsArg(0);959 this.stub(MockReceiverLink, 'ReceiverLink').returns(fakeLink);960 amqp.getReceiver('endpoint', function(err, recv1) {961 if (err) {962 testCallback(err);963 } else {964 amqp.getReceiver('endpoint', function(err, recv2) {965 if (err) {966 testCallback(err);967 } else {968 assert.equal(recv1, recv2);969 testCallback();970 }971 });972 }973 });974 });975 }));976 it('calls the done callback with an Error if it fails', sinon.test(function(testCallback) {977 var amqp = new Amqp();978 var fakeConnection = new EventEmitter();979 fakeConnection.name = 'connection';980 var fakeConnectionContext = {connection: fakeConnection};981 this.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});982 var fakeSession = new EventEmitter();983 var fakeSessionContext = {session: fakeSession};984 fakeConnection.create_session = this.stub().returns(fakeSession);985 fakeSession.open = () => {};986 this.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});987 amqp.connect({uri: 'uri'}, () => {988 var fakeError = new Error('fake create error');989 var fakeLink = new ReceiverLink('endpoint', undefined, fakeSession);990 fakeLink.attach = this.stub().callsArgWith(0, fakeError);991 this.stub(MockReceiverLink, 'ReceiverLink').returns(fakeLink);992 amqp.getReceiver('endpoint', function(err) {993 assert.instanceOf(err, Error);994 testCallback();995 });996 });997 }));998 });999 describe('#CBS', function() {1000 it('initializeCBS invokes callback with no error if successful', sinon.test(function(testCallback) {1001 var amqp = new Amqp();1002 var fakeConnection = new EventEmitter();1003 fakeConnection.name = 'connection';1004 var fakeConnectionContext = {connection: fakeConnection};1005 this.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});1006 var fakeSession = new EventEmitter();1007 var fakeSessionContext = {session: fakeSession};1008 fakeConnection.create_session = this.stub().returns(fakeSession);1009 fakeSession.open = () => {};1010 this.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});1011 amqp.connect({uri: 'uri'}, (err) => {1012 var fakeAgent = new EventEmitter();1013 fakeAgent.attach = this.stub().callsArg(0);1014 this.stub(MockCBSSecurityAgent, 'ClaimsBasedSecurityAgent').returns(fakeAgent);1015 assert.isNotOk(err, 'the connection failed to be established');1016 assert(amqp._fsm.state, 'connected', 'Not connected after CBS initialized');1017 amqp.initializeCBS((cbsError) => {1018 assert(MockCBSSecurityAgent.ClaimsBasedSecurityAgent.calledOnce, 'the CBS constructor was not invoked');1019 assert(amqp._fsm.state, 'connected', 'Not connected after CBS initialized');1020 testCallback(cbsError);1021 });1022 })1023 }));1024 it('putToken will invoke initialize CBS if was not already invoked', sinon.test(function(testCallback) {1025 var amqp = new Amqp();1026 var fakeConnection = new EventEmitter();1027 fakeConnection.name = 'connection';1028 var fakeConnectionContext = {connection: fakeConnection};1029 this.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});1030 var fakeSession = new EventEmitter();1031 var fakeSessionContext = {session: fakeSession};1032 fakeConnection.create_session = this.stub().returns(fakeSession);1033 fakeSession.open = () => {};1034 this.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});1035 amqp.connect({uri: 'uri'}, (err) => {1036 var fakeAgent = new EventEmitter();1037 fakeAgent.attach = this.stub().callsArg(0);1038 fakeAgent.putToken = this.stub().callsArg(2);1039 this.stub(MockCBSSecurityAgent, 'ClaimsBasedSecurityAgent').returns(fakeAgent);1040 assert.isNotOk(err, 'the connection failed to be established');1041 assert(amqp._fsm.state, 'connected', 'Not connected after CBS initialized');1042 amqp.putToken('audience', 'token', (tokenError) => {1043 assert(MockCBSSecurityAgent.ClaimsBasedSecurityAgent.calledOnce, 'the CBS constructor was not invoked');1044 assert(amqp._fsm.state, 'connected', 'Not connected after CBS initialized');1045 testCallback(tokenError);1046 });1047 });1048 }));1049 it('putToken will invoke initialize CBS if was not already invoked and invoke callback with error when initialize fails', sinon.test(function(testCallback) {1050 var amqp = new Amqp();1051 var fakeCBSError = new Error('fake CBS error');1052 var fakeConnection = new EventEmitter();1053 fakeConnection.name = 'connection';1054 var fakeConnectionContext = {connection: fakeConnection};1055 this.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});1056 var fakeSession = new EventEmitter();1057 var fakeSessionContext = {session: fakeSession};1058 fakeConnection.create_session = this.stub().returns(fakeSession);1059 fakeSession.open = () => {};1060 this.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});1061 amqp.connect({uri: 'uri'}, (err) => {1062 var fakeAgent = new EventEmitter();1063 fakeAgent.attach = this.stub().callsArgWith(0, fakeCBSError);1064 this.stub(MockCBSSecurityAgent, 'ClaimsBasedSecurityAgent').returns(fakeAgent);1065 assert.isNotOk(err, 'the connection failed to be established');1066 assert(amqp._fsm.state, 'connected', 'Not connected after CBS initialized');1067 amqp.putToken('audience', 'token', (tokenError) => {1068 assert.strictEqual(tokenError, fakeCBSError, 'Improper error returned from initializing the CBS');1069 testCallback();1070 });1071 });1072 }));1073 it('initializeCBS invoked only once', sinon.test(function(testCallback) {1074 var amqp = new Amqp();1075 var fakeConnection = new EventEmitter();1076 fakeConnection.name = 'connection';1077 var fakeConnectionContext = {connection: fakeConnection};1078 this.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});1079 var fakeSession = new EventEmitter();1080 var fakeSessionContext = {session: fakeSession};1081 fakeConnection.create_session = this.stub().returns(fakeSession);1082 fakeSession.open = () => {};1083 this.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});1084 amqp.connect({uri: 'uri'}, (err) => {1085 var fakeAgent = new EventEmitter();1086 fakeAgent.attach = this.stub().callsArg(0);1087 fakeAgent.putToken = this.stub().callsArg(2);1088 this.stub(MockCBSSecurityAgent, 'ClaimsBasedSecurityAgent').returns(fakeAgent);1089 assert.isNotOk(err, 'the connection failed to be established');1090 assert(amqp._fsm.state, 'connected', 'Not connected after CBS initialized');1091 amqp.initializeCBS((cbsError) => {1092 assert.isNotOk(cbsError, 'CBS did not initialize');1093 amqp.putToken('audience', 'token', (tokenError) => {1094 assert(MockCBSSecurityAgent.ClaimsBasedSecurityAgent.calledOnce, 'the CBS constructor was not invoked');1095 testCallback(tokenError);1096 })1097 });1098 })1099 }));1100 });1101 describe('Links', function() {1102 var fakeEndpoint = 'fakeEndpoint';1103 [1104 { amqpFunc: 'attachSenderLink', privateLinkArray: '_senders', mockLink: MockSenderLink, nameOfConstructor: 'SenderLink'},1105 { amqpFunc: 'attachReceiverLink', privateLinkArray: '_receivers', mockLink: MockReceiverLink, nameOfConstructor: 'ReceiverLink'}1106 ].forEach(function(testConfig) {1107 describe('#' + testConfig.amqpFunc, function() {1108 /*Tests_SRS_NODE_COMMON_AMQP_16_012: [The `attachSenderLink` method shall throw a ReferenceError if the `endpoint` argument is falsy.]*/1109 /*Tests_SRS_NODE_COMMON_AMQP_16_017: [The `attachReceiverLink` method shall throw a ReferenceError if the `endpoint` argument is falsy.]*/1110 [null, undefined, ''].forEach(function(badEndpoint) {1111 it('throws if the endpoint is \'' + badEndpoint + '\'', function() {1112 var amqp = new Amqp();1113 assert.throws(function() {1114 amqp[testConfig.amqpFunc](badEndpoint, null, function() {});1115 }, ReferenceError);1116 });1117 });1118 /*Tests_SRS_NODE_COMMON_AMQP_06_006: [The `attachReceiverLink` method shall call `attach` on the `ReceiverLink` object.] */1119 /*Tests_SRS_NODE_COMMON_AMQP_06_005: [The `attachSenderLink` method shall call `attach` on the `SenderLink` object.] */1120 /*Tests_SRS_NODE_COMMON_AMQP_06_003: [The `attachSenderLink` method shall create a policy object that contain link options to be merged if the linkOptions argument is not falsy.]*/1121 /*Tests_SRS_NODE_COMMON_AMQP_06_004: [The `attachReceiverLink` method shall create a policy object that contain link options to be merged if the linkOptions argument is not falsy.]*/1122 it('calls `attach` with success and passes options to the constructor ', sinon.test(function(testCallback) {1123 var amqp = new Amqp();1124 var fakeConnection = new EventEmitter();1125 fakeConnection.name = 'connection';1126 var fakeConnectionContext = {connection: fakeConnection};1127 this.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});1128 var fakeSession = new EventEmitter();1129 fakeSession.name = 'session';1130 var fakeSessionContext = {connection: fakeConnection, session: fakeSession};1131 fakeConnection.create_session = this.stub().returns(fakeSession);1132 fakeConnection.close = this.stub();1133 fakeSession.close = () => {};1134 this.stub(fakeSession, 'close').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_close', fakeSessionContext)})});1135 fakeSession.open = () => {};1136 this.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});1137 var fakeLink = new EventEmitter();1138 fakeLink.attach = sinon.stub().callsArg(0);1139 var fakeOptions = {color: 'red'};1140 amqp.connect({uri: 'uri'}, () => {1141 this.stub(testConfig.mockLink, testConfig.nameOfConstructor).returns(fakeLink);1142 amqp[testConfig.amqpFunc](fakeEndpoint, fakeOptions, function(err) {1143 assert(testConfig.mockLink[testConfig.nameOfConstructor].calledWith(fakeEndpoint,fakeOptions), 'constructor passed address and options');1144 if (err) { return testCallback(err); }1145 assert(fakeLink.attach.calledOnce, 'attach is invoked');1146 testCallback();1147 });1148 });1149 }));1150 /*Tests_SRS_NODE_COMMON_AMQP_16_016: [The `attachSenderLink` method shall call the `done` callback with an `Error` object if the link object wasn't created successfully.]*/1151 /*Tests_SRS_NODE_COMMON_AMQP_16_021: [The `attachReceiverLink` method shall call the `done` callback with an `Error` object if the link object wasn't created successfully.]*/1152 it('calls the done callback with an error if attaching the link failed', sinon.test(function(testCallback) {1153 var amqp = new Amqp();1154 var fakeConnection = new EventEmitter();1155 fakeConnection.name = 'connection';1156 var fakeConnectionContext = {connection: fakeConnection};1157 this.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});1158 var fakeSession = new EventEmitter();1159 fakeSession.name = 'session';1160 var fakeSessionContext = {connection: fakeConnection, session: fakeSession};1161 fakeConnection.create_session = this.stub().returns(fakeSession);1162 fakeConnection.close = this.stub();1163 fakeSession.close = () => {};1164 this.stub(fakeSession, 'close').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_close', fakeSessionContext)})});1165 fakeSession.open = () => {};1166 this.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});1167 var fakeLink = new EventEmitter();1168 var fakeAttachError = new Error('bad attach');1169 fakeLink.attach = sinon.stub().callsArgWith(0, fakeAttachError);1170 amqp.connect({uri: 'uri'}, () => {1171 this.stub(testConfig.mockLink, testConfig.nameOfConstructor).returns(fakeLink);1172 amqp[testConfig.amqpFunc](fakeEndpoint, null, function(err) {1173 assert.strictEqual(err, fakeAttachError);1174 assert(fakeLink.attach.calledOnce, 'attach is invoked');1175 testCallback();1176 });1177 });1178 }));1179 it('calls the done callback with an error if the connection fails while trying to attach the link', sinon.test(function(testCallback) {1180 var amqp = new Amqp();1181 var fakeConnection = new EventEmitter();1182 fakeConnection.name = 'connection';1183 var fakeConnectionContext = {connection: fakeConnection};1184 this.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});1185 var fakeSession = new EventEmitter();1186 fakeSession.name = 'session';1187 var fakeSessionContext = {connection: fakeConnection, session: fakeSession};1188 fakeConnection.create_session = this.stub().returns(fakeSession);1189 fakeConnection.close = this.stub();1190 fakeSession.close = () => {};1191 this.stub(fakeSession, 'close').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_close', fakeSessionContext)})});1192 fakeSession.open = () => {};1193 this.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});1194 var fakeLink = new EventEmitter();1195 var fakeError = new Error('error emitted');1196 fakeLink.attach = sinon.stub();1197 amqp.connect({uri: 'uri'}, () => {1198 this.stub(testConfig.mockLink, testConfig.nameOfConstructor).returns(fakeLink);1199 amqp[testConfig.amqpFunc](fakeEndpoint, null, function(err) {1200 assert.strictEqual(fakeError, err);1201 testCallback();1202 });1203 fakeLink.emit('error', fakeError);1204 });1205 }));1206 it('subscribe to the `error` event and removes the link from ' + testConfig.privateLinkArray + ' if it is emitted', sinon.test(function(testCallback) {1207 var amqp = new Amqp();1208 var fakeConnection = new EventEmitter();1209 fakeConnection.name = 'connection';1210 var fakeConnectionContext = {connection: fakeConnection};1211 this.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});1212 var fakeSession = new EventEmitter();1213 fakeSession.name = 'session';1214 var fakeSessionContext = {connection: fakeConnection, session: fakeSession};1215 fakeConnection.create_session = this.stub().returns(fakeSession);1216 fakeConnection.close = this.stub();1217 fakeSession.close = () => {};1218 this.stub(fakeSession, 'close').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_close', fakeSessionContext)})});1219 fakeSession.open = () => {};1220 this.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});1221 var fakeLink = new EventEmitter();1222 fakeLink.attach = sinon.stub().callsArgWith(0);1223 amqp.connect({uri: 'uri'}, () => {1224 this.stub(testConfig.mockLink, testConfig.nameOfConstructor).returns(fakeLink);1225 amqp[testConfig.amqpFunc](fakeEndpoint, null, function() {1226 assert.isDefined(amqp[testConfig.privateLinkArray][fakeEndpoint]);1227 fakeLink.emit('error', new Error('error emitted'));1228 assert.isUndefined(amqp[testConfig.privateLinkArray][fakeEndpoint]);1229 testCallback();1230 });1231 });1232 }));1233 });1234 });1235 [1236 { amqpFunc: 'detachSenderLink', privateLinkArray: '_senders', mockLink: MockSenderLink, nameOfConstructor: 'SenderLink'},1237 { amqpFunc: 'detachReceiverLink', privateLinkArray: '_receivers', mockLink: MockReceiverLink, nameOfConstructor: 'ReceiverLink'}1238 ].forEach(function(testConfig) {1239 describe('#' + testConfig.amqpFunc, function() {1240 /*Tests_SRS_NODE_COMMON_AMQP_16_022: [The `detachSenderLink` method shall throw a ReferenceError if the `endpoint` argument is falsy.]*/1241 [null, undefined, ''].forEach(function(badEndpoint) {1242 it('throws if the endpoint is \'' + badEndpoint + '\'', function() {1243 var amqp = new Amqp();1244 assert.throws(function() {1245 amqp[testConfig.amqpFunc](badEndpoint, null, function() {});1246 }, ReferenceError);1247 });1248 });1249 /*Tests_SRS_NODE_COMMON_AMQP_16_023: [The `detachSenderLink` method shall call detach on the link object corresponding to the endpoint passed as argument.]*/1250 it('calls the \'detach\' method on the link object', function(testCallback) {1251 var amqp = new Amqp();1252 var fakeConnection = new EventEmitter();1253 fakeConnection.name = 'connection';1254 var fakeConnectionContext = {connection: fakeConnection};1255 sinon.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});1256 var fakeSession = new EventEmitter();1257 fakeSession.name = 'session';1258 var fakeSessionContext = {connection: fakeConnection, session: fakeSession};1259 fakeConnection.create_session = sinon.stub().returns(fakeSession);1260 fakeConnection.close = sinon.stub();1261 fakeSession.close = () => {};1262 sinon.stub(fakeSession, 'close').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_close', fakeSessionContext)})});1263 fakeSession.open = () => {};1264 sinon.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});1265 var fakeLink = new EventEmitter();1266 fakeLink.detach = sinon.stub().callsArgWith(0);1267 amqp.connect({uri: 'uri'}, () => {1268 /*Tests_SRS_NODE_COMMON_AMQP_16_024: [The `detachSenderLink` method shall call the `done` callback with no arguments if detaching the link succeeded.]*/1269 amqp[testConfig.privateLinkArray][fakeEndpoint] = fakeLink;1270 amqp[testConfig.amqpFunc](fakeEndpoint, function(err) {1271 if (err) { return testCallback(err); }1272 assert(fakeLink.detach.calledOnce, 'attach is invoked');1273 testCallback();1274 });1275 });1276 });1277 /*Tests_SRS_NODE_COMMON_AMQP_16_025: [The `detachSenderLink` method shall call the `done` callback with no arguments if the link for this endpoint doesn't exist.]*/1278 it('calls the callback immediately if there\'s no link attached', function (testCallback) {1279 var amqp = new Amqp();1280 var fakeConnection = new EventEmitter();1281 fakeConnection.name = 'connection';1282 var fakeConnectionContext = {connection: fakeConnection};1283 sinon.stub(amqp._rheaContainer, 'connect').callsFake(() => {process.nextTick(() => {amqp._rheaConnection.emit('connection_open', fakeConnectionContext)}); return fakeConnection});1284 var fakeSession = new EventEmitter();1285 fakeSession.name = 'session';1286 var fakeSessionContext = {connection: fakeConnection, session: fakeSession};1287 fakeConnection.create_session = sinon.stub().returns(fakeSession);1288 fakeConnection.close = sinon.stub();1289 fakeSession.close = () => {};1290 sinon.stub(fakeSession, 'close').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_close', fakeSessionContext)})});1291 fakeSession.open = () => {};1292 sinon.stub(fakeSession, 'open').callsFake(() => {process.nextTick(() => {fakeSession.emit('session_open', fakeSessionContext)})});1293 var fakeLink = new EventEmitter();1294 fakeLink.detach = sinon.stub().callsArgWith(0);1295 amqp.connect({uri: 'uri'}, () => {1296 /*Tests_SRS_NODE_COMMON_AMQP_16_024: [The `detachSenderLink` method shall call the `done` callback with no arguments if detaching the link succeeded.]*/1297 amqp[testConfig.amqpFunc](fakeEndpoint, function(err) {1298 testCallback(err);1299 });1300 });1301 });1302 it('calls the callback immediately if already disconnected', function (testCallback) {1303 var amqp = new Amqp();1304 /*Tests_SRS_NODE_COMMON_AMQP_16_024: [The `detachSenderLink` method shall call the `done` callback with no arguments if detaching the link succeeded.]*/1305 amqp[testConfig.amqpFunc](fakeEndpoint, function(err) {1306 assert.isUndefined(err);1307 testCallback();1308 });1309 });1310 });1311 });1312 });1313 [1314 { functionName: 'attachSenderLink', invoke: (amqp, callback) => amqp.attachSenderLink('endpoint', null, callback) },1315 { functionName: 'attachReceiverLink', invoke: (amqp, callback) => amqp.attachReceiverLink('endpoint', null, callback) },1316 { functionName: 'initializeCBS', invoke: (amqp, callback) => amqp.initializeCBS(callback) },1317 { functionName: 'putToken', invoke: (amqp, callback) => amqp.putToken('audience', 'token', callback) }1318 ].forEach(function(testConfig) {1319 it (testConfig.functionName + ' fails with NotConnectedError if not connected', function(callback) {1320 var amqp = new Amqp();1321 testConfig.invoke(amqp, function(err) {1322 assert.instanceOf(err, errors.NotConnectedError);1323 callback();1324 });1325 });1326 });...

Full Screen

Full Screen

InitHandlerFacts.js

Source:InitHandlerFacts.js Github

copy

Full Screen

1// Copyright (c) .NET Foundation. All rights reserved.2// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.3testUtilities.module("Transports Common - InitHandler Facts");4(function (undefined) {5 function buildFakeConnection() {6 return {7 log: function () { },8 stop: function () {9 this.stopCalled = true;10 },11 _: {},12 stopCalled: false13 };14 }15 function buildFakeTransport() {16 return {17 name: "fake",18 start: function (connection, onSuccess, onFailed) {19 this.onSuccess = onSuccess;20 this.onFailed = onFailed;21 },22 stop: function () {23 this.stopCalled = true;24 },25 stopCalled: false26 };27 }28 QUnit.test("Transport cannot trigger start request after it has already failed.", function (assert) {29 // Arrange30 var fakeConnection = buildFakeConnection(),31 fakeTransport = buildFakeTransport(),32 initHandler = $.signalR.transports._logic.initHandler(fakeConnection),33 savedAjaxStart = $.signalR.transports._logic.ajaxStart,34 ajaxStartCalled = false,35 initOnSuccessCalled = false,36 initOnFallbackCalled = false,37 onFailedResult;38 $.signalR.transports._logic.ajaxStart = function () {39 ajaxStartCalled = true;40 };41 // Act42 initHandler.start(fakeTransport, function () {43 initOnSuccessCalled = true;44 }, function () {45 initOnFallbackCalled = true;46 });47 onFailedResult = fakeTransport.onFailed();48 fakeTransport.onSuccess();49 // Assert50 assert.isTrue(onFailedResult, "Transport should stop. onFailed called during initialization.");51 assert.isTrue(initOnFallbackCalled, "Transport failure triggered fallback.");52 assert.isFalse(initOnSuccessCalled, "Initialization did not complete.");53 assert.isFalse(ajaxStartCalled, "Transport failure prevented start request.");54 assert.isTrue(fakeTransport.stopCalled, "Transport failure caused the transport to be stopped.");55 assert.isFalse(fakeConnection.stopCalled, "Transport failure did not cause the connection to be stopped.");56 // Cleanup57 $.signalR.transports._logic.ajaxStart = savedAjaxStart;58 });59 QUnit.test("Transport failure during start request forces the connection to stop.", function (assert) {60 // Arrange61 var fakeConnection = buildFakeConnection(),62 fakeTransport = buildFakeTransport(),63 initHandler = $.signalR.transports._logic.initHandler(fakeConnection),64 savedAjaxStart = $.signalR.transports._logic.ajaxStart,65 ajaxStartCalled = false,66 initOnSuccessCalled = false,67 initOnFallbackCalled = false,68 onFailedResult;69 $.signalR.transports._logic.ajaxStart = function () {70 ajaxStartCalled = true;71 };72 // Act73 initHandler.start(fakeTransport, function () {74 initOnSuccessCalled = true;75 }, function () {76 initOnFallbackCalled = true;77 });78 fakeTransport.onSuccess();79 onFailedResult = fakeTransport.onFailed();80 // Assert81 assert.isTrue(onFailedResult, "Transport should stop. onFailed called during initialization.");82 assert.isFalse(initOnFallbackCalled, "Transport failure did not trigger fallback.");83 assert.isFalse(initOnSuccessCalled, "Initialization did not complete.");84 assert.isTrue(ajaxStartCalled, "Transport success triggered start request.");85 assert.isTrue(fakeConnection.stopCalled, "Transport failure caused the connection to be stopped.");86 // Cleanup87 $.signalR.transports._logic.ajaxStart = savedAjaxStart;88 });89 QUnit.test("Transport failure after successful start request has no effect.", function (assert) {90 // Arrange91 var fakeConnection = buildFakeConnection(),92 fakeTransport = buildFakeTransport(),93 initHandler = $.signalR.transports._logic.initHandler(fakeConnection),94 savedAjaxStart = $.signalR.transports._logic.ajaxStart,95 initOnSuccessCalled = false,96 initOnFallbackCalled = false,97 onFailedResult;98 $.signalR.transports._logic.ajaxStart = function (connection, onSuccess) {99 onSuccess();100 };101 // Act102 initHandler.start(fakeTransport, function () {103 initOnSuccessCalled = true;104 }, function () {105 initOnFallbackCalled = true;106 });107 fakeTransport.onSuccess();108 onFailedResult = fakeTransport.onFailed();109 // Assert110 assert.isFalse(onFailedResult, "Transport should reconnect. onFailed called after initialization.");111 assert.isFalse(initOnFallbackCalled, "Transport failure did not trigger fallback.");112 assert.isTrue(initOnSuccessCalled, "Initialization completed.");113 assert.isFalse(fakeTransport.stopCalled, "Transport failure did not cause the transport to be stopped.");114 assert.isFalse(fakeConnection.stopCalled, "Transport failure did not cause the connection to be stopped.");115 // Cleanup116 $.signalR.transports._logic.ajaxStart = savedAjaxStart;117 });118 QUnit.test("Transport failure or success after connection stop has no effect.", function (assert) {119 // Arrange120 var fakeConnection = buildFakeConnection(),121 fakeTransport = buildFakeTransport(),122 initHandler = $.signalR.transports._logic.initHandler(fakeConnection),123 savedAjaxStart = $.signalR.transports._logic.ajaxStart,124 ajaxStartCalled = false,125 initOnSuccessCalled = false,126 initOnFallbackCalled = false,127 onFailedResult;128 $.signalR.transports._logic.ajaxStart = function () {129 ajaxStartCalled = true;130 };131 // Act132 initHandler.start(fakeTransport, function () {133 initOnSuccessCalled = true;134 }, function () {135 initOnFallbackCalled = true;136 });137 initHandler.stop();138 fakeTransport.onSuccess();139 onFailedResult = fakeTransport.onFailed();140 // Assert141 assert.isTrue(onFailedResult, "Transport should stop. onFailed called after connection stopped.");142 assert.isFalse(initOnFallbackCalled, "Transport failure did not trigger fallback.");143 assert.isFalse(initOnSuccessCalled, "Initialization did not complete.");144 assert.isFalse(ajaxStartCalled, "Transport success did not trigger start request.");145 assert.isFalse(fakeConnection.stopCalled, "Transport failure did not cause the transport to be stopped.");146 assert.isFalse(fakeConnection.stopCalled, "Transport failure did not cause the connection to be stopped.");147 // Cleanup148 $.signalR.transports._logic.ajaxStart = savedAjaxStart;149 });150 QUnit.test("A single transport cannot trigger multiple fallbacks.", function (assert) {151 // Arrange152 var fakeConnection = buildFakeConnection(),153 fakeTransport = buildFakeTransport(),154 initHandler = $.signalR.transports._logic.initHandler(fakeConnection),155 initOnFallbackCount = 0,156 transportShouldStop;157 // Act158 initHandler.start(fakeTransport, undefined, function () {159 initOnFallbackCount++;160 });161 // onFailed should return true (meaning the transport should stop) each time in this test162 transportShouldStop = fakeTransport.onFailed();163 transportShouldStop = fakeTransport.onFailed() && transportShouldStop;164 // Assert165 assert.isTrue(transportShouldStop, "Transport should stop. onFailed was called during initialization each time.");166 assert.equal(initOnFallbackCount, 1, "Multiple transport failures triggered fallback exactly once.");167 assert.isTrue(fakeTransport.stopCalled, "Transport failure caused the transport to be stopped");168 assert.isFalse(fakeConnection.stopCalled, "Transport failure did not cause the connection to be stopped.");169 });170 QUnit.test("Multiple transports can trigger multiple fallbacks.", function (assert) {171 // Arrange172 var fakeConnection = buildFakeConnection(),173 fakeTransport1 = buildFakeTransport(),174 fakeTransport2 = buildFakeTransport(),175 initHandler = $.signalR.transports._logic.initHandler(fakeConnection),176 initOnFallbackCount = 0,177 transportShouldStop;178 // Act179 initHandler.start(fakeTransport1, undefined, function () {180 initOnFallbackCount++;181 });182 // onFailed should return true (meaning the transport should stop) each time in this test183 transportShouldStop = fakeTransport1.onFailed();184 initHandler.start(fakeTransport2, undefined, function () {185 initOnFallbackCount++;186 });187 transportShouldStop = fakeTransport2.onFailed() && transportShouldStop;188 // Both of the following calls should be ignored189 transportShouldStop = fakeTransport1.onFailed() && transportShouldStop;190 transportShouldStop = fakeTransport2.onFailed() && transportShouldStop;191 // Assert192 assert.isTrue(transportShouldStop, "Transports should stop. onFailed was called during initialization each time.");193 assert.isTrue(fakeTransport1.stopCalled, "Transport failure caused the first transport to be stopped");194 assert.isTrue(fakeTransport2.stopCalled, "Transport failure caused the second transport to be stopped");195 assert.equal(initOnFallbackCount, 2, "Each transport triggered fallback once.");196 assert.isFalse(fakeConnection.stopCalled, "Transport failure did not cause the connection to be stopped.");197 });198 QUnit.asyncTimeoutTest("Transport timeout can stop transport and trigger fallback.", testUtilities.defaultTestTimeout, function (end, assert) {199 // Arrange200 var fakeConnection = buildFakeConnection(),201 fakeTransport = buildFakeTransport(),202 initHandler = $.signalR.transports._logic.initHandler(fakeConnection),203 savedAjaxStart = $.signalR.transports._logic.ajaxStart,204 ajaxStartCalled = false,205 initOnSuccessCalled = false,206 initOnFallbackCalled = false;207 $.signalR.transports._logic.ajaxStart = function () {208 ajaxStartCalled = true;209 };210 fakeConnection._.totalTransportConnectTimeout = 100;211 // Act212 initHandler.start(fakeTransport, function () {213 initOnSuccessCalled = true;214 }, function () {215 initOnFallbackCalled = true;216 });217 window.setTimeout(function () {218 fakeTransport.onSuccess();219 // Assert220 assert.isTrue(initOnFallbackCalled, "Timeout triggered fallback.");221 assert.isFalse(initOnSuccessCalled, "Initialization did not complete.");222 assert.isFalse(ajaxStartCalled, "Timeout prevented start request.");223 assert.isTrue(fakeTransport.stopCalled, "Timeout caused the transport to be stopped.");224 assert.isFalse(fakeConnection.stopCalled, "Timeout did not cause the connection to be stopped.");225 end();226 }, 200);227 // Cleanup228 return function () {229 $.signalR.transports._logic.ajaxStart = savedAjaxStart;230 };231 });232 QUnit.asyncTimeoutTest("Transport timeout is not triggered after the start request is initiated.", testUtilities.defaultTestTimeout, function (end, assert) {233 // Arrange234 var fakeConnection = buildFakeConnection(),235 fakeTransport = buildFakeTransport(),236 initHandler = $.signalR.transports._logic.initHandler(fakeConnection),237 savedAjaxStart = $.signalR.transports._logic.ajaxStart,238 ajaxStartCalled = false,239 initOnSuccessCalled = false,240 initOnFallbackCalled = false;241 $.signalR.transports._logic.ajaxStart = function () {242 ajaxStartCalled = true;243 };244 fakeConnection._.totalTransportConnectTimeout = 100;245 // Act246 initHandler.start(fakeTransport, function () {247 initOnSuccessCalled = true;248 }, function () {249 initOnFallbackCalled = true;250 });251 fakeTransport.onSuccess();252 window.setTimeout(function () {253 // Assert254 assert.isFalse(initOnFallbackCalled, "Timeout did not trigger fallback.");255 assert.isFalse(initOnSuccessCalled, "Initialization did not complete.");256 assert.isTrue(ajaxStartCalled, "Timeout did not prevent start request.");257 assert.isFalse(fakeTransport.stopCalled, "Timeout did not cause the transport to be stopped.");258 assert.isFalse(fakeConnection.stopCalled, "Timeout did not cause the connection to be stopped.");259 end();260 }, 200);261 // Cleanup262 return function () {263 $.signalR.transports._logic.ajaxStart = savedAjaxStart;264 };265 });266 QUnit.asyncTimeoutTest("No callbacks are called after transport start throws.", testUtilities.defaultTestTimeout, function (end, assert) {267 // Arrange268 var fakeConnection = buildFakeConnection(),269 fakeTransport = buildFakeTransport(),270 initHandler = $.signalR.transports._logic.initHandler(fakeConnection),271 initOnSuccessCalled = false,272 initOnFallbackCalled = false;273 fakeTransport.start = function () {274 throw new Error("Fake");275 }276 fakeConnection._.totalTransportConnectTimeout = 100;277 // Act278 try {279 initHandler.start(fakeTransport, function () {280 initOnSuccessCalled = true;281 }, function () {282 initOnFallbackCalled = true;283 });284 } catch (error) {285 assert.equal(error.message, "Fake", "The error thrown from transport start bubbled up.");286 }287 window.setTimeout(function () {288 // Assert289 assert.isFalse(initOnFallbackCalled, "Timeout did not trigger fallback.");290 assert.isFalse(initOnSuccessCalled, "Initialization did not complete.");291 assert.isFalse(fakeTransport.stopCalled, "Throwing did not cause the transport to be stopped.");292 assert.isFalse(fakeConnection.stopCalled, "Throwing did not cause the connection to be stopped.");293 end();294 }, 200);295 });...

Full Screen

Full Screen

redis.test.js

Source:redis.test.js Github

copy

Full Screen

1'use strict'2var path = require('path')3var chai = require('chai')4var expect = chai.expect5var should = chai.should()6var sinon = require('sinon')7var helper = require('../../lib/agent_helper')8function FakeConnection () {9 this.writable = true10}11FakeConnection.prototype.on = function on(event, callback) {12 if (event === 'connect') return callback()13 if (event === 'data') {14 this.on_data = callback15 return callback16 }17}18FakeConnection.prototype.setNoDelay = function setNoDelay(bagel) {19 if (bagel !== false) this.bagel = true20}21FakeConnection.prototype.setTimeout = function setTimeout(timeout) {22 this.timeout = timeout23}24FakeConnection.prototype.setKeepAlive = function setKeepAlive(keepAlive){25 this.keepAlive = keepAlive26}27FakeConnection.prototype.write = function write() {}28describe('agent instrumentation of Redis', function () {29 describe('shouldn\'t cause bootstrapping to fail', function () {30 var agent31 var initialize32 before(function () {33 agent = helper.loadMockedAgent()34 initialize = require('../../../lib/instrumentation/redis')35 })36 after(function () {37 helper.unloadAgent(agent)38 })39 it('when passed no module', function () {40 expect(function () { initialize(agent); }).not.throws()41 })42 it('when passed a module with no RedisClient present.', function () {43 expect(function () { initialize(agent, {}); }).not.throws()44 })45 })46 // Redis has a lot of commands, and this is not all of them.47 describe('should instrument', function () {48 var agent49 var client50 var connection51 var mockConnection52 beforeEach(function () {53 agent = helper.instrumentMockedAgent()54 var redis = require('redis')55 connection = new FakeConnection()56 mockConnection = sinon.mock(connection)57 client = new redis.RedisClient(connection, {no_ready_check : true})58 client.host = 'fakehost.example.local'59 client.port = 876560 })61 afterEach(function () {62 mockConnection.verify()63 helper.unloadAgent(agent)64 })65 it('PING', function (done) {66 mockConnection.expects('write').withExactArgs('*1\r\n$4\r\nping\r\n').once()67 agent.once('transactionFinished', function (transaction) {68 var stats = transaction.metrics.getMetric('Datastore/operation/Redis/ping')69 expect(stats.callCount).equal(1)70 return done()71 })72 helper.runInTransaction(agent, function () {73 var transaction = agent.getTransaction()74 should.exist(transaction)75 client.PING(function cb_PING(error, results) {76 if (error) return done(error)77 should.exist(agent.getTransaction())78 expect(results, 'PING should still work').equal('PONG')79 })80 should.exist(connection.on_data)81 connection.on_data(new Buffer('+PONG\r\n'))82 transaction.end()83 })84 })85 it('PING without callback', function (done) {86 mockConnection.expects('write').withExactArgs('*1\r\n$4\r\nping\r\n').once()87 agent.once('transactionFinished', function (transaction) {88 var stats = transaction.metrics.getMetric('Datastore/operation/Redis/ping')89 expect(stats.callCount).equal(1)90 return done()91 })92 helper.runInTransaction(agent, function () {93 var transaction = agent.getTransaction()94 should.exist(transaction)95 client.PING(function cb_PING(error, results) {96 transaction.end()97 })98 should.exist(connection.on_data)99 connection.on_data(new Buffer('+PONG\r\n'))100 })101 })102 it('PING with callback in array', function (done) {103 mockConnection104 .expects('write')105 .withExactArgs('*3\r\n$4\r\nping\r\n$1\r\n1\r\n$1\r\n2\r\n')106 .once()107 agent.once('transactionFinished', function (transaction) {108 var stats = transaction.metrics.getMetric('Datastore/operation/Redis/ping')109 expect(stats.callCount).equal(1)110 return done()111 })112 helper.runInTransaction(agent, function () {113 var transaction = agent.getTransaction()114 should.exist(transaction)115 client.PING(1, 2, function (error, results) {116 if (error) return done(error)117 should.exist(agent.getTransaction())118 expect(results, 'PING should still work').equal('PONG')119 })120 should.exist(connection.on_data)121 connection.on_data(new Buffer('+PONG\r\n'))122 transaction.end()123 })124 })125 it('PING with no callback in array', function (done) {126 mockConnection127 .expects('write')128 .withExactArgs('*3\r\n$4\r\nping\r\n$1\r\n1\r\n$1\r\n2\r\n')129 .once()130 agent.once('transactionFinished', function (transaction) {131 var stats = transaction.metrics.getMetric('Datastore/operation/Redis/ping')132 expect(stats.callCount).equal(1)133 return done()134 })135 helper.runInTransaction(agent, function () {136 var transaction = agent.getTransaction()137 should.exist(transaction)138 client.PING(1, 2, function (error, results) {139 transaction.end()140 })141 should.exist(connection.on_data)142 connection.on_data(new Buffer('+PONG\r\n'))143 })144 })145 })...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('./wpt.js');2var wpt = new WebPageTest('www.webpagetest.org');3 if (err) return console.error(err);4 console.log(data);5});6var WebPageTest = require('webpagetest');7var wpt = new WebPageTest('www.webpagetest.org');8var fakeConnection = function(options, callback) {9 callback(null, {statusCode: 200}, {statusCode: 200});10};11 if (err) return console.error(err);12 console.log(data);13});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('./wpt.js');2var wpt = new WebPageTest('www.webpagetest.org');3}, function(err, data) {4 if (err) {5 console.log(err);6 } else {7 console.log(data);8 }9});10var WebPageTest = require('webpagetest');11var wpt = new WebPageTest('www.webpagetest.org');12}, function(err, data) {13 if (err) {14 console.log(err);15 } else {16 console.log(data);17 }18});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('wpt');2var wpt = new WebPageTest('www.webpagetest.org');3wpt.fakeConnection('4G');4var wpt = require('wpt');5var wpt = new WebPageTest('www.webpagetest.org');6wpt.fakeConnection('4G');7var wpt = require('wpt');8var wpt = new WebPageTest('www.webpagetest.org');9wpt.fakeConnection('4G');10var wpt = require('wpt');11var wpt = new WebPageTest('www.webpagetest.org');12wpt.fakeConnection('4G');13var wpt = require('wpt');14var wpt = new WebPageTest('www.webpagetest.org');15wpt.fakeConnection('4G');16var wpt = require('wpt');17var wpt = new WebPageTest('www.webpagetest.org');18wpt.fakeConnection('4G');19var wpt = require('wpt');20var wpt = new WebPageTest('www.webpagetest.org');21wpt.fakeConnection('4G');22var wpt = require('wpt');23var wpt = new WebPageTest('www.webpagetest.org');24wpt.fakeConnection('4G');25var wpt = require('wpt');26var wpt = new WebPageTest('www.webpagetest.org');27wpt.fakeConnection('4G');28var wpt = require('wpt');29var wpt = new WebPageTest('www.webpagetest.org');30wpt.fakeConnection('4G');31var wpt = require('wpt');32var wpt = new WebPageTest('www.webpagetest.org');

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org', 'A.6d3c6e8d7a9c9b9d7e2d2a8a7e7e7a8a');3 if (err) return console.error(err);4 console.log(data);5});6var wpt = require('webpagetest');7var wpt = new WebPageTest('www.webpagetest.org', 'A.6d3c6e8d7a9c9b9d7e2d2a8a7e7e7a8a');8 if (err) return console.error(err);9 console.log(data);10});11var wpt = require('webpagetest');12var wpt = new WebPageTest('www.webpagetest.org', 'A.6d3c6e8d7a9c9b9d7e2d2a8a7e7e7a8a');13 if (err) return console.error(err);14 console.log(data);15});16var wpt = require('

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful