Best JavaScript code snippet using mountebank
test_protocols.js
Source:test_protocols.js
...28var createProtocol = protocols.createProtocol;29suite('protocols', function () {30 suite('Protocol', function () {31 test('get name and types', function () {32 var p = createProtocol({33 namespace: 'foo',34 protocol: 'HelloWorld',35 types: [36 {37 name: 'Greeting',38 type: 'record',39 fields: [{name: 'message', type: 'string'}]40 },41 {42 name: 'Curse',43 type: 'error',44 fields: [{name: 'message', type: 'string'}]45 }46 ],47 messages: {48 hello: {49 request: [{name: 'greeting', type: 'Greeting'}],50 response: 'Greeting',51 errors: ['Curse']52 },53 hi: {54 request: [{name: 'hey', type: 'string'}],55 response: 'null',56 'one-way': true57 }58 }59 });60 assert.equal(p.getName(), 'foo.HelloWorld');61 assert.equal(p.getType('foo.Greeting').getName(true), 'record');62 });63 test('missing message', function () {64 var ptcl = createProtocol({namespace: 'com.acme', protocol: 'Hello'});65 assert.throws(function () {66 ptcl.on('add', function () {});67 }, /unknown/);68 });69 test('missing name', function () {70 assert.throws(function () {71 createProtocol({namespace: 'com.acme', messages: {}});72 });73 });74 test('missing type', function () {75 assert.throws(function () {76 createProtocol({77 namespace: 'com.acme',78 protocol: 'HelloWorld',79 messages: {80 hello: {81 request: [{name: 'greeting', type: 'Greeting'}],82 response: 'Greeting'83 }84 }85 });86 });87 });88 test('get messages', function () {89 var ptcl;90 ptcl = createProtocol({protocol: 'Empty'});91 assert.deepEqual(ptcl.getMessages(), {});92 ptcl = createProtocol({93 protocol: 'Ping',94 messages: {95 ping: {96 request: [],97 response: 'string'98 }99 }100 });101 var messages = ptcl.getMessages();102 assert.equal(Object.keys(messages).length, 1);103 assert(messages.ping !== undefined);104 });105 test('create listener', function (done) {106 var ptcl = createProtocol({protocol: 'Empty'});107 var transport = new stream.PassThrough();108 var ee = ptcl.createListener(transport, function (pending) {109 assert.equal(pending, 0);110 done();111 });112 ee.destroy();113 });114 test('subprotocol', function () {115 var ptcl = createProtocol({namespace: 'com.acme', protocol: 'Hello'});116 var subptcl = ptcl.subprotocol();117 assert.strictEqual(subptcl._emitterResolvers, ptcl._emitterResolvers);118 assert.strictEqual(subptcl._listenerResolvers, ptcl._listenerResolvers);119 });120 test('invalid emitter', function (done) {121 var ptcl = createProtocol({protocol: 'Empty'});122 ptcl.emit('hi', {}, null, function (err) {123 assert(/invalid emitter/.test(err.string));124 done();125 });126 });127 test('inspect', function () {128 var p = createProtocol({129 namespace: 'hello',130 protocol: 'World',131 });132 assert.equal(p.inspect(), '<Protocol "hello.World">');133 });134 });135 suite('Message', function () {136 var Message = protocols.Message;137 test('empty errors', function () {138 var m = new Message('Hi', {139 request: [{name: 'greeting', type: 'string'}],140 response: 'int'141 });142 assert.deepEqual(m.errorType.toString(), '["string"]');143 });144 test('missing response', function () {145 assert.throws(function () {146 new Message('Hi', {147 request: [{name: 'greeting', type: 'string'}]148 });149 });150 });151 test('invalid one-way', function () {152 // Non-null response.153 assert.throws(function () {154 new Message('Hi', {155 request: [{name: 'greeting', type: 'string'}],156 response: 'string',157 'one-way': true158 });159 });160 // Non-empty errors.161 assert.throws(function () {162 new Message('Hi', {163 request: [{name: 'greeting', type: 'string'}],164 response: 'null',165 errors: ['int'],166 'one-way': true167 });168 });169 });170 });171 suite('MessageDecoder', function () {172 var MessageDecoder = protocols.streams.MessageDecoder;173 test('ok', function (done) {174 var parts = [175 new Buffer([0, 1]),176 new Buffer([2]),177 new Buffer([]),178 new Buffer([3, 4, 5]),179 new Buffer([])180 ];181 var messages = [];182 var readable = createReadableStream(parts.map(frame), true);183 var writable = createWritableStream(messages, true)184 .on('finish', function () {185 assert.deepEqual(186 messages,187 [new Buffer([0, 1, 2]), new Buffer([3, 4, 5])]188 );189 done();190 });191 readable.pipe(new MessageDecoder()).pipe(writable);192 });193 test('trailing data', function (done) {194 var parts = [195 new Buffer([0, 1]),196 new Buffer([2]),197 new Buffer([]),198 new Buffer([3])199 ];200 var messages = [];201 var readable = createReadableStream(parts.map(frame), true);202 var writable = createWritableStream(messages, true);203 readable204 .pipe(new MessageDecoder())205 .on('error', function () {206 assert.deepEqual(messages, [new Buffer([0, 1, 2])]);207 done();208 })209 .pipe(writable);210 });211 test('empty', function (done) {212 var readable = createReadableStream([], true);213 readable214 .pipe(new MessageDecoder(true))215 .on('error', function () { done(); });216 });217 });218 suite('MessageEncoder', function () {219 var MessageEncoder = protocols.streams.MessageEncoder;220 test('invalid frame size', function () {221 assert.throws(function () { new MessageEncoder(); });222 });223 test('ok', function (done) {224 var messages = [225 new Buffer([0, 1]),226 new Buffer([2])227 ];228 var frames = [];229 var readable = createReadableStream(messages, true);230 var writable = createWritableStream(frames, true);231 readable232 .pipe(new MessageEncoder(64))233 .pipe(writable)234 .on('finish', function () {235 assert.deepEqual(236 frames,237 [238 new Buffer([0, 0, 0, 2, 0, 1, 0, 0, 0, 0]),239 new Buffer([0, 0, 0, 1, 2, 0, 0, 0, 0])240 ]241 );242 done();243 });244 });245 test('all zeros', function (done) {246 var messages = [new Buffer([0, 0, 0, 0])];247 var frames = [];248 var readable = createReadableStream(messages, true);249 var writable = createWritableStream(frames, true);250 readable251 .pipe(new MessageEncoder(64))252 .pipe(writable)253 .on('finish', function () {254 assert.deepEqual(255 frames,256 [new Buffer([0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0])]257 );258 done();259 });260 });261 test('short frame size', function (done) {262 var messages = [263 new Buffer([0, 1, 2]),264 new Buffer([2])265 ];266 var frames = [];267 var readable = createReadableStream(messages, true);268 var writable = createWritableStream(frames, true);269 readable270 .pipe(new MessageEncoder(2))271 .pipe(writable)272 .on('finish', function () {273 assert.deepEqual(274 frames,275 [276 new Buffer([0, 0, 0, 2, 0, 1, 0, 0, 0, 1, 2, 0, 0, 0, 0]),277 new Buffer([0, 0, 0, 1, 2, 0, 0, 0, 0])278 ]279 );280 done();281 });282 });283 });284 suite('StatefulEmitter', function () {285 test('ok handshake', function (done) {286 var buf = HANDSHAKE_RESPONSE_TYPE.toBuffer({match: 'BOTH'});287 var bufs = [];288 var ptcl = createProtocol({protocol: 'Empty'});289 var handshake = false;290 ptcl.createEmitter(createTransport([buf], bufs))291 .on('handshake', function (req, res) {292 handshake = true;293 assert(res.match === 'BOTH');294 assert.deepEqual(295 Buffer.concat(bufs),296 HANDSHAKE_REQUEST_TYPE.toBuffer({297 clientHash: new Buffer(ptcl._hashString, 'binary'),298 serverHash: new Buffer(ptcl._hashString, 'binary')299 })300 );301 this.destroy();302 })303 .on('eot', function () {304 assert(handshake);305 done();306 });307 });308 test('no server match handshake', function (done) {309 var ptcl = createProtocol({protocol: 'Empty'});310 var resBufs = [311 {312 match: 'NONE',313 serverHash: {'org.apache.avro.ipc.MD5': new Buffer(16)},314 serverProtocol: {string: ptcl.toString()},315 },316 {match: 'BOTH'}317 ].map(function (val) { return HANDSHAKE_RESPONSE_TYPE.toBuffer(val); });318 var reqBufs = [];319 var handshakes = 0;320 ptcl.createEmitter(createTransport(resBufs, reqBufs))321 .on('handshake', function (req, res) {322 if (handshakes++) {323 assert(res.match === 'BOTH');324 this.destroy();325 } else {326 assert(res.match === 'NONE');327 }328 })329 .on('eot', function () {330 assert.equal(handshakes, 2);331 done();332 });333 });334 test('incompatible protocol', function (done) {335 var ptcl = createProtocol({protocol: 'Empty'});336 var hash = new Buffer(16); // Pretend the hash was different.337 var resBufs = [338 {339 match: 'NONE',340 serverHash: {'org.apache.avro.ipc.MD5': hash},341 serverProtocol: {string: ptcl.toString()},342 },343 {344 match: 'NONE',345 serverHash: {'org.apache.avro.ipc.MD5': hash},346 serverProtocol: {string: ptcl.toString()},347 meta: {map: {error: new Buffer('abcd')}}348 }349 ].map(function (val) { return HANDSHAKE_RESPONSE_TYPE.toBuffer(val); });350 var error = false;351 ptcl.createEmitter(createTransport(resBufs, []))352 .on('error', function (err) {353 error = true;354 assert.equal(err.message, 'abcd');355 })356 .on('eot', function () {357 assert(error);358 done();359 });360 });361 test('handshake error', function (done) {362 var resBufs = [363 new Buffer([4, 0, 0]), // Invalid handshakes.364 new Buffer([4, 0, 0])365 ];366 var ptcl = createProtocol({protocol: 'Empty'});367 var error = false;368 ptcl.createEmitter(createTransport(resBufs, []))369 .on('error', function (err) {370 error = true;371 assert.equal(err.message, 'handshake error');372 })373 .on('eot', function () {374 assert(error);375 done();376 });377 });378 test('orphan response', function (done) {379 var ptcl = createProtocol({protocol: 'Empty'});380 var idType = protocols.IdType.createMetadataType();381 var resBufs = [382 new Buffer([0, 0, 0]), // OK handshake.383 idType.toBuffer(23)384 ];385 var error = false;386 ptcl.createEmitter(createTransport(resBufs, []))387 .on('error', function (err) {388 error = true;389 assert(/orphan response:/.test(err.message));390 })391 .on('eot', function () {392 assert(error);393 done();394 });395 });396 test('ended readable', function (done) {397 var bufs = [];398 var ptcl = createProtocol({protocol: 'Empty'});399 ptcl.createEmitter(createTransport([], bufs))400 .on('eot', function () {401 assert.equal(bufs.length, 1); // A single handshake was sent.402 done();403 });404 });405 test('interrupted', function (done) {406 var ptcl = createProtocol({407 protocol: 'Empty',408 messages: {409 id: {request: [{name: 'id', type: 'int'}], response: 'int'}410 }411 });412 var resBufs = [413 new Buffer([0, 0, 0]), // OK handshake.414 ];415 var interrupted = 0;416 var transport = createTransport(resBufs, []);417 var ee = ptcl.createEmitter(transport, function () {418 assert.equal(interrupted, 2);419 done();420 });421 ptcl.emit('id', {id: 123}, ee, cb);422 ptcl.emit('id', {id: 123}, ee, cb);423 function cb(err) {424 assert.deepEqual(err, {string: 'interrupted'});425 interrupted++;426 }427 });428 test('missing client message', function (done) {429 var ptcl1 = createProtocol({430 protocol: 'Ping',431 messages: {432 ping: {request: [], response: 'string'}433 }434 });435 var ptcl2 = createProtocol({436 protocol: 'Ping',437 messages: {438 ping: {request: [], response: 'string'},439 pong: {request: [], response: 'string'}440 }441 }).on('ping', function (req, ee, cb) { cb(null, 'ok'); });442 var transports = createPassthroughTransports();443 ptcl2.createListener(transports[1]);444 var ee = ptcl1.createEmitter(transports[0]);445 ptcl1.emit('ping', {}, ee, function (err, res) {446 assert.equal(res, 'ok');447 done();448 });449 });450 test('missing server message', function (done) {451 var ptcl1 = createProtocol({452 protocol: 'Ping',453 messages: {454 ping: {request: [], response: 'string'}455 }456 });457 var ptcl2 = createProtocol({protocol: 'Empty'});458 var transports = createPassthroughTransports();459 ptcl2.createListener(transports[1]);460 ptcl1.createEmitter(transports[0])461 .on('error', function (err) {462 assert(/missing server message: ping/.test(err.message));463 done();464 });465 });466 test('trailing data', function (done) {467 var ptcl = createProtocol({468 protocol: 'Ping',469 messages: {470 ping: {request: [], response: 'string'}471 }472 });473 var transports = createPassthroughTransports();474 ptcl.createEmitter(transports[0])475 .on('error', function (err) {476 assert(/trailing data/.test(err.message));477 done();478 });479 transports[0].readable.end(new Buffer([2, 3]));480 });481 test('invalid metadata', function (done) {482 var ptcl = createProtocol({483 protocol: 'Ping',484 messages: {485 ping: {request: [], response: 'string'}486 }487 });488 var transports = createPassthroughTransports();489 ptcl.createListener(transports[1]);490 ptcl.createEmitter(transports[0])491 .on('error', function (err) {492 assert(/invalid metadata:/.test(err.message));493 done();494 })495 .on('handshake', function () {496 transports[0].readable.write(frame(new Buffer([2, 3])));497 transports[0].readable.write(frame(new Buffer(0)));498 });499 });500 test('invalid response', function (done) {501 var ptcl = createProtocol({502 protocol: 'Ping',503 messages: {504 ping: {request: [], response: 'string'}505 }506 });507 var transports = createPassthroughTransports();508 var ml = ptcl.createListener(transports[1]);509 var me = ptcl.createEmitter(transports[0])510 .on('handshake', function () {511 ml.destroy();512 ptcl.emit('ping', {}, me, function (err) {513 assert(/invalid response:/.test(err.string));514 done();515 });516 var idType = protocols.IdType.createMetadataType();517 var bufs = [518 idType.toBuffer(1), // Metadata.519 new Buffer([3]) // Invalid response.520 ];521 transports[0].readable.write(frame(Buffer.concat(bufs)));522 transports[0].readable.write(frame(new Buffer(0)));523 });524 });525 test('one way', function (done) {526 var beats = 0;527 var ptcl = createProtocol({528 protocol: 'Heartbeat',529 messages: {530 beat: {request: [], response: 'null', 'one-way': true}531 }532 }).on('beat', function (req, ee, cb) {533 assert.strictEqual(cb, undefined);534 if (++beats === 2) {535 done();536 }537 });538 var transports = createPassthroughTransports();539 ptcl.createListener(transports[1]);540 var ee = ptcl.createEmitter(transports[0]);541 ptcl.emit('beat', {}, ee);542 ptcl.emit('beat', {}, ee);543 });544 });545 suite('StatelessEmitter', function () {546 test('interrupted before response data', function (done) {547 var ptcl = createProtocol({548 protocol: 'Ping',549 messages: {ping: {request: [], response: 'boolean'}}550 });551 var readable = stream.PassThrough()552 .on('end', done);553 var writable = createWritableStream([]);554 var ee = ptcl.createEmitter(function (cb) {555 cb(readable);556 return writable;557 });558 ptcl.emit('ping', {}, ee, function (err) {559 assert(/interrupted/.test(err.string));560 readable.write(frame(new Buffer(2)));561 readable.end(frame(new Buffer(0)));562 });563 ee.destroy(true);564 });565 });566 suite('StatefulListener', function () {567 test('end readable', function (done) {568 var ptcl = createProtocol({protocol: 'Empty'});569 var transports = createPassthroughTransports();570 ptcl.createListener(transports[0])571 .on('eot', function (pending) {572 assert.equal(pending, 0);573 done();574 });575 transports[0].readable.end();576 });577 test('finish writable', function (done) {578 var ptcl = createProtocol({protocol: 'Empty'});579 var transports = createPassthroughTransports();580 ptcl.createListener(transports[0])581 .on('eot', function (pending) {582 assert.equal(pending, 0);583 done();584 });585 transports[0].writable.end();586 });587 test('invalid handshake', function (done) {588 var ptcl = createProtocol({protocol: 'Empty'});589 var transport = createTransport(590 [new Buffer([4])], // Invalid handshake.591 []592 );593 ptcl.createListener(transport)594 .on('handshake', function (req, res) {595 assert(!req.$isValid());596 assert.equal(res.match, 'NONE');597 done();598 });599 });600 test('missing server message', function (done) {601 var ptcl1 = createProtocol({protocol: 'Empty'});602 var ptcl2 = createProtocol({603 protocol: 'Heartbeat',604 messages: {beat: {request: [], response: 'boolean'}}605 });606 var hash = new Buffer(ptcl2._hashString, 'binary');607 var req = {608 clientHash: hash,609 clientProtocol: {string: ptcl2.toString()},610 serverHash: hash611 };612 var transport = createTransport(613 [HANDSHAKE_REQUEST_TYPE.toBuffer(req)],614 []615 );616 ptcl1.createListener(transport)617 .on('handshake', function (req, res) {618 assert(req.$isValid());619 assert.equal(res.match, 'NONE');620 var msg = res.meta.map.error.toString();621 assert(/missing server message/.test(msg));622 done();623 });624 });625 test('invalid metadata', function (done) {626 var ptcl = createProtocol({627 protocol: 'Heartbeat',628 messages: {beat: {request: [], response: 'boolean'}}629 });630 var transports = createPassthroughTransports();631 ptcl.createListener(transports[1])632 .on('error', function (err) {633 assert(/invalid metadata/.test(err.message));634 done();635 });636 ptcl.createEmitter(transports[0])637 .on('handshake', function () {638 // Handshake is complete now.639 var writable = transports[0].writable;640 writable.write(frame(new Buffer([0]))); // Empty metadata.641 writable.write(frame(new Buffer(0)));642 });643 });644 test('unknown message', function (done) {645 var ptcl = createProtocol({646 protocol: 'Heartbeat',647 messages: {beat: {request: [], response: 'boolean'}}648 });649 var transports = createPassthroughTransports();650 var ee = ptcl.createListener(transports[1])651 .on('eot', function () {652 transports[1].writable.end();653 });654 ptcl.createEmitter(transports[0])655 .on('handshake', function () {656 // Handshake is complete now.657 this.destroy();658 var idType = ee._idType;659 var bufs = [];660 transports[0].readable661 .pipe(new protocols.streams.MessageDecoder())662 .on('data', function (buf) { bufs.push(buf); })663 .on('end', function () {664 assert.equal(bufs.length, 1);665 var tap = new utils.Tap(bufs[0]);666 idType._read(tap);667 assert(tap.buf[tap.pos++]); // Error byte.668 tap.pos++; // Union marker.669 assert(/unknown message/.test(tap.readString()));670 done();671 });672 [673 idType.toBuffer(-1),674 new Buffer([4, 104, 105]), // `hi` message.675 new Buffer(0) // End of frame.676 ].forEach(function (buf) {677 transports[0].writable.write(frame(buf));678 });679 transports[0].writable.end();680 });681 });682 test('invalid request', function (done) {683 var ptcl = createProtocol({684 protocol: 'Heartbeat',685 messages: {beat: {686 request: [{name: 'id', type: 'string'}],687 response: 'boolean'688 }}689 });690 var transports = createPassthroughTransports();691 var ee = ptcl.createListener(transports[1])692 .on('eot', function () { transports[1].writable.end(); });693 ptcl.createEmitter(transports[0])694 .on('handshake', function () {695 // Handshake is complete now.696 this.destroy();697 var idType = ee._idType;698 var bufs = [];699 transports[0].readable700 .pipe(new protocols.streams.MessageDecoder())701 .on('data', function (buf) { bufs.push(buf); })702 .on('end', function () {703 assert.equal(bufs.length, 1);704 var tap = new utils.Tap(bufs[0]);705 idType._read(tap);706 assert.equal(tap.buf[tap.pos++], 1); // Error byte.707 assert.equal(tap.buf[tap.pos++], 0); // Union marker.708 assert(/invalid request/.test(tap.readString()));709 done();710 });711 [712 idType.toBuffer(-1),713 new Buffer([8, 98, 101, 97, 116]), // `beat` message.714 new Buffer([8]), // Invalid Avro string encoding.715 new Buffer(0) // End of frame.716 ].forEach(function (buf) {717 transports[0].writable.write(frame(buf));718 });719 transports[0].writable.end();720 });721 });722 test('destroy', function (done) {723 var ptcl = createProtocol({724 protocol: 'Heartbeat',725 messages: {beat: {request: [], response: 'boolean'}}726 }).on('beat', function (req, ee, cb) {727 ee.destroy();728 setTimeout(function () { cb(null, true); }, 10);729 });730 var transports = createPassthroughTransports();731 var responded = false;732 ptcl.createListener(transports[1])733 .on('eot', function () {734 assert(responded); // Works because the transport is sync.735 done();736 });737 ptcl.emit('beat', {}, ptcl.createEmitter(transports[0]), function () {738 responded = true;739 });740 });741 });742 suite('StatelessListener', function () {743 test('unknown message', function (done) {744 var ptcl = createProtocol({745 protocol: 'Heartbeat',746 messages: {beat: {request: [], response: 'boolean'}}747 });748 var readable = new stream.PassThrough();749 var writable = new stream.PassThrough();750 var ee = ptcl.createListener(function (cb) {751 cb(writable);752 return readable;753 });754 var bufs = [];755 writable.pipe(new protocols.streams.MessageDecoder())756 .on('data', function (buf) { bufs.push(buf); })757 .on('end', function () {758 assert.equal(bufs.length, 1);759 var tap = new utils.Tap(bufs[0]);760 tap.pos = 4; // Skip handshake response.761 ee._idType._read(tap); // Skip metadata.762 assert.equal(tap.buf[tap.pos++], 1); // Error.763 assert.equal(tap.buf[tap.pos++], 0); // Union flag.764 assert(/unknown message/.test(tap.readString()));765 done();766 });767 var hash = new Buffer(ptcl._hashString, 'binary');768 var req = {769 clientHash: hash,770 clientProtocol: null,771 serverHash: hash772 };773 var encoder = new protocols.streams.MessageEncoder(64);774 encoder.pipe(readable);775 encoder.end(Buffer.concat([776 HANDSHAKE_REQUEST_TYPE.toBuffer(req),777 new Buffer([0]), // Empty metadata.778 new Buffer([4, 104, 105]) // `id` message.779 ]));780 });781 test('late writable', function (done) {782 var ptcl = createProtocol({783 protocol: 'Heartbeat',784 messages: {beat: {request: [], response: 'boolean'}}785 }).on('beat', function (req, ee, cb) {786 cb(null, true);787 });788 var readable = new stream.PassThrough();789 var writable = new stream.PassThrough();790 ptcl.createListener(function (cb) {791 setTimeout(function () { cb(readable); }, 10);792 return writable;793 });794 var ee = ptcl.createEmitter(function (cb) {795 cb(readable);796 return writable;797 });798 ptcl.emit('beat', {}, ee, function (err, res) {799 assert.strictEqual(err, null);800 assert.equal(res, true);801 done();802 });803 });804 });805 suite('emit', function () {806 suite('stateful', function () {807 run(function (emitterPtcl, listenerPtcl, cb) {808 var pt1 = new stream.PassThrough();809 var pt2 = new stream.PassThrough();810 var opts = {bufferSize: 48};811 cb(812 emitterPtcl.createEmitter({readable: pt1, writable: pt2}, opts),813 listenerPtcl.createListener({readable: pt2, writable: pt1}, opts)814 );815 });816 });817 suite('stateless', function () {818 run(function (emitterPtcl, listenerPtcl, cb) {819 cb(emitterPtcl.createEmitter(writableFactory));820 function writableFactory(emitterCb) {821 var reqPt = new stream.PassThrough()822 .on('finish', function () {823 listenerPtcl.createListener(function (listenerCb) {824 var resPt = new stream.PassThrough()825 .on('finish', function () { emitterCb(resPt); });826 listenerCb(resPt);827 return reqPt;828 });829 });830 return reqPt;831 }832 });833 });834 function run(setupFn) {835 test('single', function (done) {836 var ptcl = createProtocol({837 protocol: 'Math',838 messages: {839 negate: {840 request: [{name: 'n', type: 'int'}],841 response: 'int'842 }843 }844 });845 setupFn(ptcl, ptcl, function (ee) {846 ee.on('eot', function () { done(); });847 ptcl.on('negate', function (req, ee, cb) { cb(null, -req.n); });848 ptcl.emit('negate', {n: 20}, ee, function (err, res) {849 assert.equal(this, ptcl);850 assert.strictEqual(err, null);851 assert.equal(res, -20);852 this.emit('negate', {n: 'hi'}, ee, function (err) {853 assert(/invalid "int"/.test(err.string));854 ee.destroy();855 });856 });857 });858 });859 test('invalid request', function (done) {860 var ptcl = createProtocol({861 protocol: 'Math',862 messages: {863 negate: {864 request: [{name: 'n', type: 'int'}],865 response: 'int'866 }867 }868 }).on('negate', function () { assert(false); });869 setupFn(ptcl, ptcl, function (ee) {870 ee.on('eot', function () { done(); });871 ptcl.emit('negate', {n: 'a'}, ee, function (err) {872 assert(/invalid "int"/.test(err.string), null);873 ee.destroy();874 });875 });876 });877 test('error response', function (done) {878 var msg = 'must be non-negative';879 var ptcl = createProtocol({880 protocol: 'Math',881 messages: {882 sqrt: {883 request: [{name: 'n', type: 'float'}],884 response: 'float'885 }886 }887 }).on('sqrt', function (req, ee, cb) {888 var n = req.n;889 if (n < 0) {890 cb({string: msg});891 } else {892 cb(null, Math.sqrt(n));893 }894 });895 setupFn(ptcl, ptcl, function (ee) {896 ptcl.emit('sqrt', {n: 100}, ee, function (err, res) {897 assert(Math.abs(res - 10) < 1e-5);898 ptcl.emit('sqrt', {n: - 10}, ee, function (err) {899 assert.equal(this, ptcl);900 assert.equal(err.string, msg);901 done();902 });903 });904 });905 });906 test('invalid response', function (done) {907 var ptcl = createProtocol({908 protocol: 'Math',909 messages: {910 sqrt: {911 request: [{name: 'n', type: 'float'}],912 response: 'float'913 }914 }915 }).on('sqrt', function (req, ee, cb) {916 var n = req.n;917 if (n < 0) {918 cb(null, 'complex'); // Invalid response.919 } else {920 cb(null, Math.sqrt(n));921 }922 });923 setupFn(ptcl, ptcl, function (ee) {924 ptcl.emit('sqrt', {n: - 10}, ee, function (err) {925 // The server error message is propagated to the client.926 assert(/invalid "float"/.test(err.string));927 ptcl.emit('sqrt', {n: 100}, ee, function (err, res) {928 // And the server doesn't die (we can make a new request).929 assert(Math.abs(res - 10) < 1e-5);930 done();931 });932 });933 });934 });935 test('invalid error', function (done) {936 var ptcl = createProtocol({937 protocol: 'Math',938 messages: {939 sqrt: {940 request: [{name: 'n', type: 'float'}],941 response: 'float'942 }943 }944 }).on('sqrt', function (req, ee, cb) {945 var n = req.n;946 if (n < 0) {947 cb({error: 'complex'}); // Invalid error.948 } else {949 cb(null, Math.sqrt(n));950 }951 });952 setupFn(ptcl, ptcl, function (ee) {953 ptcl.emit('sqrt', {n: - 10}, ee, function (err) {954 assert(/invalid \["string"\]/.test(err.string));955 ptcl.emit('sqrt', {n: 100}, ee, function (err, res) {956 // The server still doesn't die (we can make a new request).957 assert(Math.abs(res - 10) < 1e-5);958 done();959 });960 });961 });962 });963 test('out of order', function (done) {964 var ptcl = createProtocol({965 protocol: 'Delay',966 messages: {967 wait: {968 request: [969 {name: 'ms', type: 'float'},970 {name: 'id', type: 'string'}971 ],972 response: 'string'973 }974 }975 }).on('wait', function (req, ee, cb) {976 var delay = req.ms;977 if (delay < 0) {978 cb(new Error('delay must be non-negative'));979 return;980 }981 setTimeout(function () { cb(null, req.id); }, delay);982 });983 var ids = [];984 setupFn(ptcl, ptcl, function (ee) {985 ee.on('eot', function (pending) {986 assert.equal(pending, 0);987 assert.deepEqual(ids, [null, 'b', 'a']);988 done();989 });990 ptcl.emit('wait', {ms: 100, id: 'a'}, ee, function (err, res) {991 assert.strictEqual(err, null);992 ids.push(res);993 });994 ptcl.emit('wait', {ms: 10, id: 'b'}, ee, function (err, res) {995 assert.strictEqual(err, null);996 ids.push(res);997 ee.destroy();998 });999 ptcl.emit('wait', {ms: -100, id: 'c'}, ee, function (err, res) {1000 assert(/non-negative/.test(err.string));1001 ids.push(res);1002 });1003 });1004 });1005 test('compatible protocols', function (done) {1006 var emitterPtcl = createProtocol({1007 protocol: 'emitterProtocol',1008 messages: {1009 age: {1010 request: [{name: 'name', type: 'string'}],1011 response: 'long'1012 }1013 }1014 });1015 var listenerPtcl = createProtocol({1016 protocol: 'serverProtocol',1017 messages: {1018 age: {1019 request: [1020 {name: 'name', type: 'string'},1021 {name: 'address', type: ['null', 'string'], 'default': null}1022 ],1023 response: 'int'1024 },1025 id: {1026 request: [{name: 'name', type: 'string'}],1027 response: 'long'1028 }1029 }1030 });1031 setupFn(1032 emitterPtcl,1033 listenerPtcl,1034 function (ee) {1035 listenerPtcl.on('age', function (req, ee, cb) {1036 assert.equal(req.name, 'Ann');1037 cb(null, 23);1038 });1039 emitterPtcl.emit('age', {name: 'Ann'}, ee, function (err, res) {1040 assert.strictEqual(err, null);1041 assert.equal(res, 23);1042 done();1043 });1044 }1045 );1046 });1047 test('cached compatible protocols', function (done) {1048 var ptcl1 = createProtocol({1049 protocol: 'emitterProtocol',1050 messages: {1051 age: {1052 request: [{name: 'name', type: 'string'}],1053 response: 'long'1054 }1055 }1056 });1057 var ptcl2 = createProtocol({1058 protocol: 'serverProtocol',1059 messages: {1060 age: {1061 request: [1062 {name: 'name', type: 'string'},1063 {name: 'address', type: ['null', 'string'], 'default': null}1064 ],1065 response: 'int'1066 },1067 id: {1068 request: [{name: 'name', type: 'string'}],1069 response: 'long'1070 }1071 }1072 }).on('age', function (req, ee, cb) { cb(null, 48); });1073 setupFn(1074 ptcl1,1075 ptcl2,1076 function (ee1) {1077 ptcl1.emit('age', {name: 'Ann'}, ee1, function (err, res) {1078 assert.equal(res, 48);1079 setupFn(1080 ptcl1,1081 ptcl2,1082 function (ee2) { // ee2 has the server's protocol.1083 ptcl1.emit('age', {name: 'Bob'}, ee2, function (err, res) {1084 assert.equal(res, 48);1085 done();1086 });1087 }1088 );1089 });1090 }1091 );1092 });1093 test('incompatible protocols', function (done) {1094 var emitterPtcl = createProtocol({1095 protocol: 'emitterProtocol',1096 messages: {1097 age: {request: [{name: 'name', type: 'string'}], response: 'long'}1098 }1099 });1100 var listenerPtcl = createProtocol({1101 protocol: 'serverProtocol',1102 messages: {1103 age: {request: [{name: 'name', type: 'int'}], response: 'long'}1104 }1105 }).on('age', function (req, ee, cb) { cb(null, 0); });1106 setupFn(1107 emitterPtcl,1108 listenerPtcl,1109 function (ee) {1110 ee.on('error', function () {}); // For stateful protocols.1111 emitterPtcl.emit('age', {name: 'Ann'}, ee, function (err) {1112 assert(err);1113 done();1114 });1115 }1116 );1117 });1118 test('unknown message', function (done) {1119 var ptcl = createProtocol({protocol: 'Empty'});1120 setupFn(ptcl, ptcl, function (ee) {1121 ptcl.emit('echo', {}, ee, function (err) {1122 assert(/unknown/.test(err.string));1123 done();1124 });1125 });1126 });1127 test('unsupported message', function (done) {1128 var ptcl = createProtocol({1129 protocol: 'Echo',1130 messages: {1131 echo: {1132 request: [{name: 'id', type: 'string'}],1133 response: 'string'1134 }1135 }1136 });1137 setupFn(ptcl, ptcl, function (ee) {1138 ptcl.emit('echo', {id: ''}, ee, function (err) {1139 assert(/unsupported/.test(err.string));1140 done();1141 });1142 });1143 });1144 test('destroy emitter noWait', function (done) {1145 var ptcl = createProtocol({1146 protocol: 'Delay',1147 messages: {1148 wait: {1149 request: [{name: 'ms', type: 'int'}],1150 response: 'string'1151 }1152 }1153 }).on('wait', function (req, ee, cb) {1154 setTimeout(function () { cb(null, 'ok'); }, req.ms);1155 });1156 var interrupted = 0;1157 var eoted = false;1158 setupFn(ptcl, ptcl, function (ee) {1159 ee.on('eot', function (pending) {1160 eoted = true;1161 assert.equal(interrupted, 2);1162 assert.equal(pending, 2);1163 done();1164 });1165 ptcl.emit('wait', {ms: 75}, ee, interruptedCb);1166 ptcl.emit('wait', {ms: 50}, ee, interruptedCb);1167 ptcl.emit('wait', {ms: 10}, ee, function (err, res) {1168 assert.equal(res, 'ok');1169 ee.destroy(true);1170 });1171 function interruptedCb(err) {1172 assert(/interrupted/.test(err.string));1173 interrupted++;1174 }1175 });1176 });1177 test('destroy emitter', function (done) {1178 var ptcl = createProtocol({1179 protocol: 'Math',1180 messages: {1181 negate: {1182 request: [{name: 'n', type: 'int'}],1183 response: 'int'1184 }1185 }1186 });1187 setupFn(ptcl, ptcl, function (ee) {1188 ptcl.on('negate', function (req, ee, cb) { cb(null, -req.n); });1189 ptcl.emit('negate', {n: 20}, ee, function (err, res) {1190 assert.strictEqual(err, null);1191 assert.equal(res, -20);1192 ee.destroy();...
Using AI Code Generation
1var mb = require('mountebank');2mb.create({3}).then(function (imposter) {4 console.log('Imposter created');5});6var mb = require('mountebank');7mb.create({8}).then(function (imposter) {9 console.log('Imposter created');10});11var mb = require('mountebank');12mb.create({13}).then(function (imposter) {14 console.log('Imposter created');15});16var mb = require('mountebank');17mb.create({18}).then(function (imposter) {19 console.log('Imposter created');20});21var mb = require('mountebank');22mb.create({23}).then(function (imposter) {24 console.log('Imposter created');25});26var mb = require('mountebank');27mb.create({
Using AI Code Generation
1var mb = require('mountebank');2var imposter = {3 {4 {5 equals: {6 }7 }8 {9 is: {10 headers: {11 },12 body: JSON.stringify({test: 'test'})13 }14 }15 }16};17mb.create(imposter).then(function (imposter) {18 console.log(imposter.port);19});20var mb = require('mountebank');21var imposter = {22 {23 {24 equals: {25 }26 }27 {28 is: {29 headers: {30 },31 body: JSON.stringify({test: 'test'})32 }33 }34 }35};36mb.create(imposter).then(function (imposter) {37 console.log(imposter.port);38});39var mb = require('mountebank');40var imposter = {41 {42 {43 equals: {44 }45 }46 {47 is: {48 headers: {49 },50 body: JSON.stringify({test: 'test'})51 }52 }53 }54};55mb.create(imposter).then(function (imposter) {
Using AI Code Generation
1var mb = require('mountebank');2 {3 {4 {5 is: {6 }7 }8 }9 }10];11mb.create({ imposters: imposters }).then(function () {12 console.log('Mountebank is ready!');13});14{15 "scripts": {16 },17 "dependencies": {18 }19}
Using AI Code Generation
1var mb = require('mountebank');2var imposter = {3 stubs: [{4 responses: [{5 is: {6 }7 }]8 }]9};10mb.createImposter(imposter, function (error, imposter) {11 if (error) {12 console.error('Error creating imposter', error);13 } else {14 console.log('Created imposter', imposter.port);15 }16});17var mb = require('mountebank');18var imposter = {19 stubs: [{20 responses: [{21 is: {22 }23 }]24 }]25};26mb.createImposter(imposter, function (error, imposter) {27 if (error) {28 console.error('Error creating imposter', error);29 } else {30 console.log('Created imposter', imposter.port);31 }32});33var mb = require('mountebank');34var imposter = {35 stubs: [{36 responses: [{37 is: {38 }39 }]40 }]41};42mb.createImposter(imposter, function (error, imposter) {43 if (error) {44 console.error('Error creating imposter', error);45 } else {46 console.log('Created imposter', imposter.port);47 }48});49var mb = require('mountebank');50var imposter = {51 stubs: [{52 responses: [{53 is: {54 }55 }]56 }]57};58mb.createImposter(imposter, function (error, imposter) {59 if (error) {60 console.error('Error creating imposter', error);61 } else {62 console.log('Created imposter', imposter.port);63 }64});65var mb = require('mountebank');66var imposter = {
Using AI Code Generation
1const mb = require('mountebank');2const port = 2525;3const protocol = 'http';4const stub = {5 {6 is: {7 }8 }9};10const imposter = {11};12mb.createProtocol(protocol, port, stub).then(() => {13 console.log(`Protocol ${protocol} created on port ${port}`);14}).catch((error) => {15 console.error(error);16});17const mb = require('mountebank');18const port = 2525;19const protocol = 'http';20const stub = {21 {22 is: {23 }24 }25};26const imposter = {27};28mb.createProtocol(protocol, port, stub).then(() => {29 console.log(`Protocol ${protocol} created on port ${port}`);30}).catch((error) => {31 console.error(error);32});33const mb = require('mountebank');34const port = 2525;35const protocol = 'http';36const stub = {37 {38 is: {39 }40 }41};42const imposter = {43};44mb.createProtocol(protocol, port, stub).then(() => {45 console.log(`Protocol ${protocol} created on port ${port}`);46}).catch((error) => {47 console.error(error);48});
Using AI Code Generation
1var mb = require('mountebank');2var imposters = 2525;3var imposter = {4 {5 {6 is: {7 headers: {8 },9 }10 }11 }12};13mb.create({port: imposters, ipWhitelist: ['*']}, function (error, server) {14 server.createImposter(imposter, function (error, imposter) {15 console.log(imposter.port);16 });17});18var mb = require('mountebank');19var imposters = 2525;20var imposter = {21 {22 {23 is: {24 headers: {25 },26 }27 }28 }29};30mb.create({port: imposters, ipWhitelist: ['*']}, function (error, server) {31 server.createImposter(imposter, function (error, imposter) {32 console.log(imposter.port);33 });34});35var mb = require('mountebank');36var imposters = 2525;37var imposter = {38 {39 {40 is: {41 headers: {42 },43 }44 }45 }46};47mb.create({port: imposters, ipWhitelist: ['*']}, function (error, server) {48 server.createImposter(imposter, function (error, imposter) {49 console.log(imposter.port);50 });51});52var mb = require('mountebank');53var imposters = 2525;54var imposter = {
Using AI Code Generation
1var mb = require('mountebank');2mb.create({ port: 2525, pidfile: 'mb.pid' }, function () {3});4var mb = require('mountebank');5mb.create({ port: 2525, pidfile: 'mb.pid' }, function () {6});7var mb = require('mountebank');8mb.create({ port: 2525, pidfile: 'mb.pid' }, function () {9});10var mb = require('mountebank');11mb.create({ port: 2525, pidfile: 'mb.pid' }, function () {12});13var mb = require('mountebank');14mb.create({ port: 2525, pidfile: 'mb.pid' }, function () {15});16var mb = require('mountebank');17mb.create({ port: 2525, pidfile: 'mb.pid' }, function () {18});19var mb = require('mountebank');20mb.create({ port: 2525, pidfile: 'mb.pid' }, function () {21});22var mb = require('mountebank');23mb.create({ port: 2525, pidfile: 'mb.pid' }, function () {24});25var mb = require('mountebank');26mb.create({ port: 2525, pidfile: 'mb.pid' }, function () {27});28var mb = require('mountebank');29mb.create({ port: 2525, pidfile:
Using AI Code Generation
1const mb = require('mountebank').create();2mb.start()3 .then(() => {4 console.log('Mountebank started');5 return mb.post('/imposters', {6 });7 })8 .then(() => {9 console.log('Imposter created');10 return mb.get('/imposters');11 })12 .then(response => {13 console.log('Imposter list: ' + JSON.stringify(response.body));14 return mb.stop();15 })16 .then(() => {17 console.log('Mountebank stopped');18 })19 .catch(error => {20 console.error(error);21 });
Using AI Code Generation
1var mb = require('mountebank');2var protocol = mb.createProtocol('https');3protocol.get({4}, function (response) {5 response.on('data', function (data) {6 console.log(data.toString());7 });8});9var mb = require('mountebank');10var protocol = mb.createProtocol('https');11protocol.get({12}, function (response) {13 response.on('data', function (data) {14 console.log(data.toString());15 });16});17var mb = require('mountebank');18var protocol = mb.createProtocol('https');19protocol.get({20}, function (response) {21 response.on('data', function (data) {22 console.log(data.toString());23 });24});25var mb = require('mountebank');26var protocol = mb.createProtocol('https');27protocol.get({28}, function (response) {29 response.on('data', function (data) {30 console.log(data.toString());31 });32});
Using AI Code Generation
1const mb = require('mountebank');2const imposter = {3 {4 {5 is: {6 }7 }8 }9};10mb.createImposter(imposter, () => {11 console.log('Imposter created');12});13const mb = require('mountebank');14const imposter = {15 {16 {17 is: {18 }19 }20 }21};22mb.createImposter(imposter, () => {23 console.log('Imposter created');24});25const mb = require('mountebank');26const imposter = {27 {28 {29 is: {30 }31 }32 }33};34mb.createImposter(imposter, () => {35 console.log('Imposter created');36});37const mb = require('mountebank');38const imposter = {39 {40 {41 is: {42 }43 }44 }45};46mb.createImposter(imposter, () => {47 console.log('Imposter created');48});
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!!