How to use hasResponseInjections method in mountebank

Best JavaScript code snippet using mountebank

dryRunValidator.js

Source:dryRunValidator.js Github

copy

Full Screen

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

Full Screen

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