How to use requestSpec method in mountebank

Best JavaScript code snippet using mountebank

engine_socketio.js

Source:engine_socketio.js Github

copy

Full Screen

1/* This Source Code Form is subject to the terms of the Mozilla Public2 * License, v. 2.0. If a copy of the MPL was not distributed with this3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */4'use strict';5const async = require('async');6const _ = require('lodash');7const io = require('socket.io-client');8const wildcardPatch = require('socketio-wildcard')(io.Manager);9const tough = require('tough-cookie');10const deepEqual = require('deep-equal');11const debug = require('debug')('socketio');12const engineUtil = require('./engine_util');13const EngineHttp = require('./engine_http');14const template = engineUtil.template;15module.exports = SocketIoEngine;16function SocketIoEngine(script) {17 this.config = script.config;18 this.socketioOpts = this.config.socketio || {};19 this.httpDelegate = new EngineHttp(script);20}21SocketIoEngine.prototype.createScenario = function(scenarioSpec, ee) {22 var self = this;23 let tasks = _.map(scenarioSpec.flow, function(rs) {24 if (rs.think) {25 return engineUtil.createThink(rs, _.get(self.config, 'defaults.think', {}));26 }27 return self.step(rs, ee);28 });29 return self.compile(tasks, scenarioSpec.flow, ee);30};31function markEndTime(ee, context, startedAt) {32 let endedAt = process.hrtime(startedAt);33 let delta = (endedAt[0] * 1e9) + endedAt[1];34 ee.emit('histogram', 'engine.socketio.response_time', delta/1e6);35}36function isResponseRequired(spec) {37 return (spec.emit && spec.emit.response && spec.emit.response.channel);38}39function isAcknowledgeRequired(spec) {40 return (spec.emit && spec.emit.acknowledge);41}42function processResponse(ee, data, response, context, callback) {43 // Do we have supplied data to validate?44 if (response.data && !deepEqual(data, response.data)) {45 debug('data is not valid:');46 debug(data);47 debug(response);48 let err = 'data is not valid';49 ee.emit('error', err);50 return callback(err, context);51 }52 // If no capture or match specified, then we consider it a success at this point...53 if (!response.capture && !response.match) {54 return callback(null, context);55 }56 // Construct the (HTTP) response...57 let fauxResponse = {body: JSON.stringify(data)};58 // Handle the capture or match clauses...59 engineUtil.captureOrMatch(response, fauxResponse, context, function(err, result) {60 // Were we unable to invoke captureOrMatch?61 if (err) {62 debug(data);63 ee.emit('error', err);64 return callback(err, context);65 }66 if (result !== null) {67 // Do we have any failed matches?68 let failedMatches = _.filter(result.matches, (v, k) => {69 return !v.success;70 });71 // How to handle failed matches?72 if (failedMatches.length > 0) {73 debug(failedMatches);74 // TODO: Should log the details of the match somewhere75 ee.emit('error', 'Failed match');76 return callback(new Error('Failed match'), context);77 } else {78 // Emit match events...79 // _.each(result.matches, function(v, k) {80 // ee.emit('match', v.success, {81 // expected: v.expected,82 // got: v.got,83 // expression: v.expression84 // });85 // });86 // Populate the context with captured values87 _.each(result.captures, function(v, k) {88 context.vars[k] = v.value;89 });90 }91 // Replace the base object context92 // Question: Should this be JSON object or String?93 context.vars.$ = fauxResponse.body;94 // Increment the success count...95 context._successCount++;96 return callback(null, context);97 }98 });99}100SocketIoEngine.prototype.step = function (requestSpec, ee) {101 let self = this;102 if (requestSpec.loop) {103 let steps = _.map(requestSpec.loop, function(rs) {104 if (!rs.emit && !rs.loop) {105 return self.httpDelegate.step(rs, ee);106 }107 return self.step(rs, ee);108 });109 return engineUtil.createLoopWithCount(110 requestSpec.count || -1,111 steps,112 {113 loopValue: requestSpec.loopValue,114 loopElement: requestSpec.loopElement || '$loopElement',115 overValues: requestSpec.over,116 whileTrue: self.config.processor ?117 self.config.processor[requestSpec.whileTrue] : undefined118 }119 );120 }121 let f = function(context, callback) {122 // Only process emit requests; delegate the rest to the HTTP engine (or think utility)123 if (requestSpec.think) {124 return engineUtil.createThink(requestSpec, _.get(self.config, 'defaults.think', {}));125 }126 if (!requestSpec.emit) {127 let delegateFunc = self.httpDelegate.step(requestSpec, ee);128 return delegateFunc(context, callback);129 }130 ee.emit('counter', 'engine.socketio.emit', 1);131 ee.emit('rate', 'engine.socketio.emit_rate');132 let startedAt = process.hrtime();133 let socketio = context.sockets[requestSpec.emit.namespace] || null;134 if (!(requestSpec.emit && requestSpec.emit.channel && socketio)) {135 debug('invalid arguments');136 ee.emit('error', 'invalid arguments');137 // TODO: Provide a more helpful message138 callback(new Error('socketio: invalid arguments'));139 }140 let outgoing = {141 channel: template(requestSpec.emit.channel, context),142 data: template(requestSpec.emit.data, context)143 };144 let endCallback = function (err, context, needEmit) {145 if (err) {146 debug(err);147 }148 if (isAcknowledgeRequired(requestSpec)) {149 let ackCallback = function () {150 let response = {151 data: template(requestSpec.emit.acknowledge.data, context),152 capture: template(requestSpec.emit.acknowledge.capture, context),153 match: template(requestSpec.emit.acknowledge.match, context)154 };155 // Make sure data, capture or match has a default json spec for parsing socketio responses156 _.each(response, function (r) {157 if (_.isPlainObject(r) && !('json' in r)) {158 r.json = '$.0'; // Default to the first callback argument159 }160 });161 // Acknowledge data can take up multiple arguments of the emit callback162 processResponse(ee, arguments, response, context, function (err) {163 if (!err) {164 markEndTime(ee, context, startedAt);165 }166 return callback(err, context);167 });168 }169 // Acknowledge required so add callback to emit170 if (needEmit) {171 socketio.emit(outgoing.channel, outgoing.data, ackCallback);172 } else {173 ackCallback();174 }175 } else {176 // No acknowledge data is expected, so emit without a listener177 if (needEmit) {178 socketio.emit(outgoing.channel, outgoing.data);179 }180 markEndTime(ee, context, startedAt);181 return callback(null, context);182 }183 }; // endCallback184 if (isResponseRequired(requestSpec)) {185 let response = {186 channel: template(requestSpec.emit.response.channel, context),187 data: template(requestSpec.emit.response.data, context),188 capture: template(requestSpec.emit.response.capture, context),189 match: template(requestSpec.emit.response.match, context)190 };191 // Listen for the socket.io response on the specified channel192 let done = false;193 socketio.on(response.channel, function receive(data) {194 done = true;195 processResponse(ee, data, response, context, function(err) {196 if (!err) {197 markEndTime(ee, context, startedAt);198 }199 // Stop listening on the response channel200 socketio.off(response.channel);201 return endCallback(err, context, false);202 });203 });204 // Send the data on the specified socket.io channel205 socketio.emit(outgoing.channel, outgoing.data);206 // If we don't get a response within the timeout, fire an error207 let waitTime = self.config.timeout || 10;208 waitTime *= 1000;209 setTimeout(function responseTimeout() {210 if (!done) {211 let err = 'response timeout';212 ee.emit('error', err);213 return callback(err, context);214 }215 }, waitTime);216 } else {217 endCallback(null, context, true);218 }219 };220 function preStep(context, callback){221 // Set default namespace in emit action222 requestSpec.emit.namespace = template(requestSpec.emit.namespace, context) || "";223 self.loadContextSocket(requestSpec.emit.namespace, context, function(err, socket) {224 if(err) {225 debug(err);226 ee.emit('error', err.message);227 return callback(err, context);228 }229 return f(context, callback);230 });231 }232 if(requestSpec.emit) {233 return preStep;234 } else {235 return f;236 }237};238SocketIoEngine.prototype.loadContextSocket = function(namespace, context, cb) {239 context.sockets = context.sockets || {};240 if(!context.sockets[namespace]) {241 let target = this.config.target + namespace;242 let tls = this.config.tls || {};243 const socketioOpts = template(this.socketioOpts, context);244 let options = _.extend(245 {},246 socketioOpts, // templated247 tls248 );249 let socket = io(target, options);250 context.sockets[namespace] = socket;251 wildcardPatch(socket);252 socket.on('*', function () {253 context.__receivedMessageCount++;254 });255 socket.once('connect', function() {256 cb(null, socket);257 });258 socket.once('connect_error', function(err) {259 cb(err, null);260 });261 } else {262 return cb(null, context.sockets[namespace]);263 }264};265SocketIoEngine.prototype.closeContextSockets = function (context) {266 // if(context.socketio) {267 // context.socketio.disconnect();268 // }269 if(context.sockets && Object.keys(context.sockets).length > 0) {270 var namespaces = Object.keys(context.sockets);271 namespaces.forEach(function(namespace){272 context.sockets[namespace].disconnect();273 });274 }275};276SocketIoEngine.prototype.compile = function (tasks, scenarioSpec, ee) {277 let config = this.config;278 let self = this;279 function zero(callback, context) {280 context.__receivedMessageCount = 0;281 ee.emit('started');282 self.loadContextSocket('', context, function done(err) {283 if (err) {284 ee.emit('error', err);285 return callback(err, context);286 }287 return callback(null, context);288 });289 }290 return function scenario(initialContext, callback) {291 initialContext = self.httpDelegate.setInitialContext(initialContext);292 initialContext._pendingRequests = _.size(293 _.reject(scenarioSpec, function(rs) {294 return (typeof rs.think === 'number');295 }));296 let steps = _.flatten([297 function z(cb) {298 return zero(cb, initialContext);299 },300 tasks301 ]);302 async.waterfall(303 steps,304 function scenarioWaterfallCb(err, context) {305 if (err) {306 debug(err);307 }308 if (context) {309 self.closeContextSockets(context);310 }311 return callback(err, context);312 });313 };...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1const async = require('async');2const debug = require('debug')('meteor');3const DDPClient = require('ddp');4const _ = require('lodash')5const helpers = require('artillery/core/lib/engine_util');6module.exports = MeteorEngine;7function MeteorEngine (script){8 this.config = script.config;9 this.helpers = helpers;10}11MeteorEngine.prototype.createScenario = function(scenarioSpec, ee) {12 var self = this;13 let tasks = _.map(scenarioSpec.flow, function(rs) {14 if(rs.think){15 return helpers.createThink(rs, _.get(self.config, 'defaults.think', {}))16 }17 return self.step(rs, ee);18 });19 return self.compile(tasks, scenarioSpec.flow, ee);20}21MeteorEngine.prototype.step = function(requestSpec, ee) {22 let self = this;23 if (requestSpec.loop) {24 let steps = _.map(requestSpec.loop, function(rs) {25 return self.step(rs, ee);26 });27 return helpers.createLoopWithCount(28 requestSpec.count || -1,29 steps,30 {31 loopValue: requestSpec.loopValue || '$loopCount',32 overValues: requestSpec.over,33 whileTrue: self.config.processor ?34 self.config.processor[requestSpec.whileTrue] : undefined35 });36 }37 if (requestSpec.think) {38 return helpers.createThink(requestSpec, _.get(self.config, 'defaults.think', {}));39 }40 if (requestSpec.function) {41 return function(context, callback) {42 let processFunc = self.config.processor[requestSpec.function];43 if (processFunc) {44 processFunc(context, ee, function () {45 return callback(null, context);46 });47 }48 }49 }50 let call = function(context, callback) {51 ee.emit('request');52 let startedAt = process.hrtime();53 const method = requestSpec.call.name;54 const payload = helpers.template(requestSpec.call.payload, context);55 debug('Meteor call: %s', method, payload);56 context.ddpclient.call(method, payload, (err, result) => {57 if (err) {58 debug(err);59 ee.emit('error', err);60 } else {61 let endedAt = process.hrtime(startedAt);62 let delta = (endedAt[0] * 1e9) + endedAt[1];63 ee.emit('response', delta, 0, context._uid);64 }65 return callback(err, context);66 });67 };68 if(requestSpec.call){69 return call;70 }71 let subscribe = function(context, callback) {72 ee.emit('request');73 let startedAt = process.hrtime();74 const pubName = requestSpec.subscribe.name;75 const payload = helpers.template(requestSpec.subscribe.payload, context);76 debug('Meteor subscribe: %s', pubName, payload);77 context.ddpclient.subscribe(pubName, payload, (err) => { 78 if (err) {79 debug(err);80 ee.emit('error', err);81 } else {82 let endedAt = process.hrtime(startedAt);83 let delta = (endedAt[0] * 1e9) + endedAt[1];84 ee.emit('response', delta, 0, context._uid);85 }86 return callback(err, context);87 });88 }89 if(requestSpec.subscribe){90 return subscribe91 }92 let login = function(context, callback) {93 ee.emit('request');94 let startedAt = process.hrtime();95 const payload = helpers.template(requestSpec.login, context);96 debug('Meteor login: %s', payload);97 const userProps = {};98 if(payload.username){99 userProps.username = payload.username;100 } else if(payload.email) {101 userProps.email = payload.email;102 }103 context.ddpclient.call("login", [{104 user: userProps,105 password: payload.password106 }], (err) => { 107 if (err) {108 debug(err);109 ee.emit('error', err);110 } else {111 let endedAt = process.hrtime(startedAt);112 let delta = (endedAt[0] * 1e9) + endedAt[1];113 ee.emit('response', delta, 0, context._uid);114 }115 return callback(err, context);116 });117 }118 if(requestSpec.login){119 return login;120 }121}122MeteorEngine.prototype.compile = function(tasks, scenarioSpec, ee) {123 let config = this.config;124 return function scenario(initialContext, callback) {125 function zero(callback) {126 ee.emit('started');127 const ddpclient = new DDPClient({128 maintainCollections: false,129 ddpVersion : '1',130 url: config.target131 })132 133 ddpclient.connect((error) => {134 if(error) {135 debug(error);136 ee.emit('error', error.message || error.code);137 return callback(error, {});138 } else {139 initialContext.ddpclient = ddpclient;140 return callback(null, initialContext)141 }142 });143 }144 initialContext._successCount = 0;145 let steps = _.flatten([146 zero,147 tasks148 ]);149 async.waterfall(150 steps,151 function scenarioWaterfallCb(err, context) {152 if (err) {153 debug(err);154 }155 if (context && context.ddpclient) {156 context.ddpclient.close();157 }158 return callback(err, context);159 });160 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var request = require('request');2var options = {3 headers: {4 },5 body: {6 stubs: [{7 responses: [{8 is: {9 headers: {10 },11 body: '{ "status": "ok" }'12 }13 }]14 }]15 },16};17request(options, function (error, response, body) {18 if (error) throw new Error(error);19 console.log(body);20});21var request = require('request');22var options = {23 headers: {24 },25 body: {26 stubs: [{27 responses: [{28 is: {29 headers: {30 },31 body: '{ "status": "ok" }'32 }33 }]34 }]35 },36};37request(options, function (error, response, body) {38 if (error) throw new Error(error);39 console.log(body);40});41var assert = require('assert');42var request = require('request');43var options = {44 headers: {45 },46 body: {47 stubs: [{48 responses: [{49 is: {50 headers: {51 },52 body: '{ "status": "ok" }'53 }54 }]55 }]56 },

Full Screen

Using AI Code Generation

copy

Full Screen

1var request = require('request');2var options = {3 json: {4 "stubs": [{5 "responses": [{6 "is": {7 "headers": {8 },9 }10 }]11 }]12 }13};14request(options, function(error, response, body) {15 console.log(body);16});

Full Screen

Using AI Code Generation

copy

Full Screen

1var request = require('request');2var options = {3 json: {4 "stubs": [{5 "responses": [{6 "is": {7 "headers": {8 },9 "body": JSON.stringify({10 })11 }12 }]13 }]14 }15};16request(options, function(error, response, body) {17 if (!error && response.statusCode == 200) {18 console.log(body)19 }20});

Full Screen

Using AI Code Generation

copy

Full Screen

1var request = require('request');2var options = {3 json: {4 {5 {6 "is": {7 "headers": {8 },9 "body": {10 }11 }12 }13 }14 }15};16request(options, function(error, response, body) {17 if (!error && response.statusCode == 201) {18 console.log("imposter created");19 }20 else {21 console.log("error");22 }23});24var request = require('request');25var options = {26 json: {27 {28 {29 "is": {30 "headers": {31 },32 "body": {33 }34 }35 }36 }37 }38};39request(options, function(error, response, body) {40 if (!error && response.statusCode == 201) {41 console.log("imposter created");42 }43 else {44 console.log("error");45 }46});47var request = require('request');48var options = {49 json: {50 {51 {52 "is": {53 "headers": {54 },55 "body": {56 }57 }58 }59 }60 }61};62request(options, function(error, response, body) {

Full Screen

Using AI Code Generation

copy

Full Screen

1var request = require('request');2var assert = require('assert');3var options = {4 json: {5 {6 {7 equals: {8 }9 }10 {11 is: {12 }13 }14 }15 }16};17request(options, function (error, response, body) {18 assert.equal(response.statusCode, 201);19 console.log(body);20});21var request = require('request');22var assert = require('assert');23var options = {24};25request(options, function (error, response, body) {26 assert.equal(response.statusCode, 200);27 assert.equal(body, 'Hello, World!');28 console.log(body);29});30var request = require('request');31var assert = require('assert');32var options = {33 json: {

Full Screen

Using AI Code Generation

copy

Full Screen

1var request = require('request');2var fs = require('fs');3var mb = require('mountebank');4var imposter = JSON.parse(fs.readFileSync('imposter.json', 'utf-8'));5mb.create(imposter, 2525, function (error, imposter) {6});7var request = require('request');8var fs = require('fs');9var mb = require('mountebank');10var imposter = JSON.parse(fs.readFileSync('imposter.json', 'utf-8'));11mb.create(imposter, 2525, function (error, imposter) {12});13var request = require('request');14var fs = require('fs');15var mb = require('mountebank');16var imposter = JSON.parse(fs.readFileSync('imposter.json', 'utf-8'));17mb.create(imposter, 2525, function (error, imposter) {18});19var request = require('request');20var fs = require('fs');21var mb = require('mountebank');22var imposter = JSON.parse(fs.readFileSync('imposter.json', 'utf-8'));23mb.create(imposter, 2525, function (error, imposter) {24});25var request = require('request');26var fs = require('fs');27var mb = require('mountebank');28var imposter = JSON.parse(fs.readFileSync('imposter.json', 'utf-8'));29mb.create(imposter, 2525, function (error, imposter) {30});31var request = require('request');32var fs = require('fs');33var mb = require('mountebank');34var imposter = JSON.parse(fs.readFileSync('imposter.json', 'utf-8'));35mb.create(imposter, 2525, function (error, imposter) {36});37var request = require('request');38var fs = require('fs');

Full Screen

Using AI Code Generation

copy

Full Screen

1var request = require('request');2var port = 2525;3var host = 'localhost';4var path = '/imposters';5var stubs = {6 {7 equals: {8 }9 }10 {11 is: {12 }13 }14};15var options = {16 body: {17 }18};19request(options, function (error, response, body) {20 console.log('error:', error);21 console.log('statusCode:', response && response.statusCode);22 console.log('body:', body);23});24var request = require('request');25var port = 2525;26var host = 'localhost';27var path = '/imposters/3000';28var options = {29};30request(options, function (error, response, body) {31 console.log('error:', error);32 console.log('statusCode:', response && response.statusCode);33 console.log('body:', body);34});35var request = require('request');36var port = 2525;37var host = 'localhost';38var path = '/imposters/3000';39var options = {40};41request(options, function (error, response, body) {42 console.log('error:', error);43 console.log('statusCode:', response && response.statusCode);44 console.log('body:', body);45});

Full Screen

Using AI Code Generation

copy

Full Screen

1var request = require('request');2var assert = require('assert');3var fs = require('fs');4var mbHelper = require('./mbHelper');5var mbPort = 8080;6var mbHelperObj = new mbHelper(mbUrl, mbPort);7var stubs = fs.readFileSync('./stubs.json', 'utf8');8var stubsObj = JSON.parse(stubs);9describe('Test Mountebank', function () {10 it('should return a response', function (done) {11 mbHelperObj.createImposter(stubsObj, function (err, res, body) {12 if (err) {13 done(err);14 } else {15 var imposterId = JSON.parse(body).port;16 if (err) {17 done(err);18 } else {19 assert.equal(res.statusCode, 200);20 assert.equal(res.body, 'Hello');21 mbHelperObj.deleteImposter(imposterId, function (err, res, body) {22 if (err) {23 done(err);24 } else {25 done();26 }27 });28 }29 });30 }31 });32 });33});34var request = require('request');35var mbHelper = function (mbUrl, mbPort) {36 this.mbUrl = mbUrl;37 this.mbPort = mbPort;38};39mbHelper.prototype.createImposter = function (stubsObj, callback) {40 var options = {41 };42 request(options, callback);43};44mbHelper.prototype.deleteImposter = function (imposterId, callback) {45 var options = {46 };47 request(options, callback);48};49module.exports = mbHelper;50{51 {52 {53 "is": {54 "headers": {

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 mountebank 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