Best JavaScript code snippet using mountebank
dryRunValidator.js
Source:dryRunValidator.js
1'use strict';2/**3 * Validating a syntactically correct imposter creation statically is quite difficult.4 * This module validates dynamically by running test requests through each predicate and each stub5 * to see if it throws an error. A valid request is one that passes the dry run error-free.6 * @module7 */8var utils = require('util'),9 Q = require('q'),10 exceptions = require('../util/errors'),11 helpers = require('../util/helpers'),12 combinators = require('../util/combinators'),13 ResponseResolver = require('./responseResolver');14/**15 * Creates the validator16 * @param {Object} options - Configuration for the validator17 * @param {Object} options.testRequest - The protocol-specific request used for each dry run18 * @param {Object} options.StubRepository - The creation function19 * @param {boolean} options.allowInjection - Whether JavaScript injection is allowed or not20 * @param {function} options.additionalValidation - A function that performs protocol-specific validation21 * @returns {Object}22 */23function create (options) {24 function stubForResponse (originalStub, response, withPredicates) {25 // Each dry run only validates the first response, so we26 // explode the number of stubs to dry run each response separately27 var clonedStub = helpers.clone(originalStub),28 clonedResponse = helpers.clone(response);29 clonedStub.responses = [clonedResponse];30 // If the predicates don't match the test request, we won't dry run31 // the response (although the predicates will be dry run). We remove32 // the predicates to account for this scenario.33 if (!withPredicates) {34 delete clonedStub.predicates;35 }36 // we've already validated waits and don't want to add latency to validation37 if (clonedResponse._behaviors && clonedResponse._behaviors.wait) {38 delete clonedResponse._behaviors.wait;39 }40 return clonedStub;41 }42 function dryRun (stub, encoding, logger) {43 // Need a well-formed proxy response in case a behavior decorator expects certain fields to exist44 var dryRunProxy = { to: function () { return Q(options.testProxyResponse); } },45 dryRunLogger = {46 debug: combinators.noop,47 info: combinators.noop,48 warn: combinators.noop,49 error: logger.error50 },51 resolver = ResponseResolver.create(dryRunProxy, combinators.identity),52 stubsToValidateWithPredicates = stub.responses.map(function (response) {53 return stubForResponse(stub, response, true);54 }),55 stubsToValidateWithoutPredicates = stub.responses.map(function (response) {56 return stubForResponse(stub, response, false);57 }),58 stubsToValidate = stubsToValidateWithPredicates.concat(stubsToValidateWithoutPredicates),59 dryRunRepositories = stubsToValidate.map(function (stubToValidate) {60 var stubRepository = options.StubRepository.create(resolver, false, encoding);61 stubRepository.addStub(stubToValidate);62 return stubRepository;63 });64 return Q.all(dryRunRepositories.map(function (stubRepository) {65 var testRequest = options.testRequest;66 testRequest.isDryRun = true;67 return stubRepository.resolve(testRequest, dryRunLogger);68 }));69 }70 function addDryRunErrors (stub, encoding, errors, logger) {71 var deferred = Q.defer();72 try {73 dryRun(stub, encoding, logger).done(deferred.resolve, function (reason) {74 reason.source = reason.source || JSON.stringify(stub);75 errors.push(reason);76 deferred.resolve();77 });78 }79 catch (error) {80 errors.push(exceptions.ValidationError('malformed stub request', {81 data: error.message,82 source: error.source || stub83 }));84 deferred.resolve();85 }86 return deferred.promise;87 }88 function addInvalidWaitErrors (stub, errors) {89 var hasInvalidWait = stub.responses.some(function (response) {90 return response._behaviors && response._behaviors.wait && response._behaviors.wait < 0;91 });92 if (hasInvalidWait) {93 errors.push(exceptions.ValidationError("'wait' value must be an integer greater than or equal to 0", {94 source: stub95 }));96 }97 }98 function hasStubInjection (stub) {99 var hasResponseInjections = utils.isArray(stub.responses) && stub.responses.some(function (response) {100 var hasDecorator = response._behaviors && response._behaviors.decorate;101 var hasProxyDecorator = response.proxy && response.proxy._behaviors && response.proxy._behaviors.decorate;102 return response.inject || hasDecorator || hasProxyDecorator;103 }),104 hasPredicateInjections = Object.keys(stub.predicates || {}).some(function (predicate) {105 return stub.predicates[predicate].inject;106 });107 return hasResponseInjections || hasPredicateInjections;108 }109 function addStubInjectionErrors (stub, errors) {110 if (!options.allowInjection && hasStubInjection(stub)) {111 errors.push(exceptions.InjectionError(112 'JavaScript injection is not allowed unless mb is run with the --allowInjection flag', { source: stub }));113 }114 }115 function errorsForStub (stub, encoding, logger) {116 var errors = [],117 deferred = Q.defer();118 if (!utils.isArray(stub.responses) || stub.responses.length === 0) {119 errors.push(exceptions.ValidationError("'responses' must be a non-empty array", {120 source: stub121 }));122 }123 else {124 addInvalidWaitErrors(stub, errors);125 }126 addStubInjectionErrors(stub, errors);127 if (errors.length > 0) {128 // no sense in dry-running if there are already problems;129 // it will just add noise to the errors130 deferred.resolve(errors);131 }132 else {133 addDryRunErrors(stub, encoding, errors, logger).done(function () {134 deferred.resolve(errors);135 });136 }137 return deferred.promise;138 }139 function errorsForRequest (request) {140 var errors = [],141 hasRequestInjection = request.endOfRequestResolver && request.endOfRequestResolver.inject;142 if (!options.allowInjection && hasRequestInjection) {143 errors.push(exceptions.InjectionError(144 'JavaScript injection is not allowed unless mb is run with the --allowInjection flag',145 { source: request.endOfRequestResolver }));146 }147 return errors;148 }149 /**150 * Validates that the imposter creation is syntactically valid151 * @memberOf module:models/dryRunValidator#152 * @param {Object} request - The request containing the imposter definition153 * @param {Object} logger - The logger154 * @returns {Object} Promise resolving to an object containing isValid and an errors array155 */156 function validate (request, logger) {157 var stubs = request.stubs || [],158 encoding = request.mode === 'binary' ? 'base64' : 'utf8',159 validationPromises = stubs.map(function (stub) { return errorsForStub(stub, encoding, logger); }),160 deferred = Q.defer();161 validationPromises.push(Q(errorsForRequest(request)));162 if (options.additionalValidation) {163 validationPromises.push(Q(options.additionalValidation(request)));164 }165 Q.all(validationPromises).done(function (errorsForAllStubs) {166 var allErrors = errorsForAllStubs.reduce(function (stubErrors, accumulator) {167 return accumulator.concat(stubErrors);168 }, []);169 deferred.resolve({ isValid: allErrors.length === 0, errors: allErrors });170 });171 return deferred.promise;172 }173 return {174 validate: validate175 };176}177module.exports = {178 create: create...
Using AI Code Generation
1var request = require('request');2var options = {3 json: {4 {5 {6 "is": {7 "headers": {8 },9 }10 }11 }12 }13};14request(options, function (error, response, body) {15 console.log(body);16 var options2 = {17 json: {18 {19 {20 "proxy": {21 {22 "matches": {23 }24 }25 }26 }27 }28 }29 };30 request(options2, function (error, response, body) {31 console.log(body);32 });33});
Using AI Code Generation
1const mb = require('mountebank');2const { dryRunProxy } = mb.create();3const options = {4 stubs: [{5 predicates: [{6 equals: {7 }8 }],9 responses: [{10 is: {11 }12 }]13 }],14};15dryRunProxy(options).then((result) => {16 console.log(result);17}).catch((err) => {18 console.log(err);19});20const mb = require('mountebank');21const { dryRunProxy } = mb.create();22const options = {23 stubs: [{24 predicates: [{25 equals: {26 }27 }],28 responses: [{29 is: {30 }31 }]32 }],33};34dryRunProxy(options).then((result) => {35 console.log(result);36}).catch((err) => {37 console.log(err);38});39const mb = require('mountebank');40const { dryRunProxy } = mb.create();41const options = {42 stubs: [{43 predicates: [{44 equals: {45 }46 }],47 responses: [{48 is: {49 }50 }]51 }],52};53dryRunProxy(options).then((result) => {54 console.log(result);55}).catch((err) => {56 console.log(err);57});58const mb = require('mountebank');59const { dryRunProxy } = mb.create();60const options = {61 stubs: [{62 predicates: [{63 equals: {64 }
Using AI Code Generation
1const mb = require('mountebank');2const options = {3};4mb.start(options).then(function () {5 const request = {6 {7 {8 is: {9 }10 }11 }12 };13 mb.create(request).then(function () {14 const request = {15 };16 return mb.dryRunProxy(request);17 }).then(function (response) {18 console.log(response);19 return mb.stop();20 }).then(function () {21 console.log('stopped');22 });23});24mb.create(request).then(function () {25 const request = {26 };27 return mb.dryRunProxy(request);28}).then(function (response) {29 console.log(response);30 return mb.stop();31}).then(function () {32 console.log('stopped');33});34mb.stop().then(function () {35 console.log('stopped');36});37const mb = require('mountebank');38const options = {39};40mb.start(options).then(function () {41 const request = {42 {43 {44 is: {45 }46 }47 }48 };49 mb.create(request).then(function () {50 const request = {51 };52 return mb.dryRunProxy(request
Using AI Code Generation
1var mb = require('mountebank');2var options = {3};4mb.start(options, function () {5 console.log('mountebank started');6 mb.create({7 {8 {9 is: {10 headers: {11 },12 }13 }14 }15 }, function () {16 console.log('imposter started');17 });18});19var mb = require('mountebank');20var options = {21};22mb.start(options, function () {23 console.log('mountebank started');24 mb.create({25 {26 {27 is: {28 headers: {29 },30 }31 }32 }33 }, function () {34 console.log('imposter started');35 });36});37var mb = require('mountebank');38var options = {39};40mb.start(options, function () {41 console.log('mountebank started');42 mb.create({
Using AI Code Generation
1var proxy = require('mountebank-proxy');2var options = { port: 2525, host: 'localhost' };3var mb = proxy(options);4var imposter = {5 {6 {7 is: {8 }9 }10 }11};12mb.dryRunProxy(imposter, function (error, result) {13 console.log(result);14});
Using AI Code Generation
1var mb = require('mountebank');2var dryRunProxy = mb.create({3 stubs: [{4 predicates: [{5 equals: {6 }7 }],8 responses: [{9 proxy: {10 }11 }]12 }]13}, function (error) {14 if (error) {15 console.error('Error creating dryRunProxy', error);16 } else {17 console.log('DryRunProxy created');18 }19});20 if (error) {21 console.error('Error dry running proxy', error);22 } else {23 console.log('Dry run proxy response', response);24 }25});26var mb = require('mountebank');27var dryRunProxy = mb.create({28 stubs: [{29 predicates: [{30 equals: {31 }32 }],33 responses: [{34 proxy: {35 }36 }]37 }]38}, function (error) {39 if (error) {40 console.error('Error creating dryRunProxy', error);41 } else {42 console.log('DryRunProxy created');43 }44});45 if (error) {46 console.error('Error dry running proxy', error);47 } else {48 console.log('Dry run proxy response', response);49 }50});51Error dry running proxy { [Error: connect ECONNREFUSED
Using AI Code Generation
1var mb = require('mountebank');2var port = 2525;3var host = 'localhost';4var protocol = 'http';5var api = 'api';6var path = '/api/v1.0/endpoint';7var method = 'GET';8var response = {status: 200, body: 'Hello World!'};9var stub = {responses: [response]};10var predicateGenerators = [{matches: {method: true}}];11var imposter = {port: port, protocol: protocol, stubs: [stub], predicates: predicateGenerators};12var options = {allowInjection: true};13mb.create({port: port, allowInjection: true}, function (error, mbServer) {14 if (error) {15 console.error(error);16 } else {17 mbServer.post('/imposters', imposter, function (error, response) {18 if (error) {19 console.error(error);20 } else {21 var request = {path: path, method: method};22 mbServer.dryRunProxy(request, function (error, response) {23 if (error) {24 console.error(error);25 } else {26 console.log(response.body);27 }28 });29 }30 });31 }32});33var mb = require('mountebank');34var port = 2525;35var host = 'localhost';36var protocol = 'http';37var api = 'api';38var path = '/api/v1.0/endpoint';39var method = 'GET';40var response = {status: 200, body: 'Hello World!'};41var stub = {responses: [response]};42var predicateGenerators = [{matches: {method: true}}];43var imposter = {port: port, protocol: protocol, stubs: [stub], predicates: predicateGenerators};44var options = {allowInjection: true};45mb.create({port: port, allowInjection: true}, function (error, mbServer) {46 if (error) {47 console.error(error);48 } else {49 mbServer.post('/imposters', imposter, function (error, response) {50 if (error) {51 console.error(error);52 } else {53 var request = {path: path, method: method};
Using AI Code Generation
1const request = require('request');2const mbHelper = require('./mountebankHelper');3const fs = require('fs');4const util = require('util');5const apiJSON = fs.readFileSync('api.json', 'utf8');6const api = JSON.parse(apiJSON);7mbHelper.dryRunProxy(api).then((response) => {8 console.log(util.inspect(response, { depth: null }));9});10const request = require('request');11exports.dryRunProxy = function (api) {12 return new Promise((resolve, reject) => {13 request({14 }, (err, response, body) => {15 if (err) {16 return reject(err);17 }18 return resolve(body);19 });20 });21};22{23 {24 {25 "is": {26 "headers": {27 },28 "body": {29 }30 }31 }32 }33}34{35 {36 {37 {38 "is": {39 "headers": {40 },41 "body": {42 }43 }44 }45 }46 }47}
Using AI Code Generation
1var dryRunProxy = require('mountebank').dryRunProxy;2var config = require('./config.json');3var mbHost = 'localhost';4var mbPort = 2525;5dryRunProxy(mbHost, mbPort, config, function (err, result) {6 if (err) {7 console.error(err);8 process.exit(1);9 }10 if (result.matched) {11 console.log('matched');12 } else {13 console.log('not matched');14 }15});16{17 {18 {19 "proxy": {20 }21 }22 }23}
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!!