How to use stubsToValidateWithPredicates 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

Using AI Code Generation

copy

Full Screen

1var assert = require('assert');2var mb = require('mountebank');3var stubsToValidateWithPredicates = mb.stubsToValidateWithPredicates;4var stubs = [{5 predicates: [{6 equals: {7 }8 }],9 responses: [{10 is: {11 headers: {12 },13 body: JSON.stringify({ test: 'test' })14 }15 }]16}];17var result = stubsToValidateWithPredicates(stubs);18assert.deepEqual(result, stubs);

Full Screen

Using AI Code Generation

copy

Full Screen

1var imposter = require('mountebank').create({2 stubs: [{3 predicates: [{4 equals: {5 }6 }],7 responses: [{8 is: {9 }10 }]11 }]12});13var imposter = require('mountebank').create({14 stubs: [{15 predicates: [{16 equals: {17 }18 }],19 responses: [{20 is: {21 }22 }]23 }]24});25var imposter = require('mountebank').create({26 stubs: [{27 predicates: [{28 equals: {29 }30 }],31 responses: [{32 is: {33 }34 }]35 }]36});37var imposter = require('mountebank').create({38 stubs: [{39 predicates: [{40 equals: {41 }42 }],43 responses: [{44 is: {45 }46 }]47 }]48});49var imposter = require('mountebank').create({50 stubs: [{51 predicates: [{52 equals: {53 }54 }],55 responses: [{56 is: {57 }58 }]59 }]60});61var imposter = require('mounteb

Full Screen

Using AI Code Generation

copy

Full Screen

1var assert = require('assert');2var mb = require('mountebank');3var request = require('request');4var port = 2525;5var host = 'localhost';6describe('Test', function () {7 before(function (done) {8 mb.create({ port: port, pidfile: 'mb.pid', logfile: 'mb.log' }, done);9 });10 after(function (done) {11 mb.stop({ pidfile: 'mb.pid' }, done);12 });13 it('should return 200', function (done) {14 var predicate = {15 "matches": {16 }17 };18 {19 {20 "is": {21 "headers": {22 },23 "body": {24 }25 }26 }27 }28 ];29 mb.stub({ port: port, stubs: stubs }, function (error) {30 assert.ifError(error);31 request.get(url + '/test?name=test', function (error, response, body) {32 assert.ifError(error);33 assert.strictEqual(response.statusCode, 200);34 assert.strictEqual(body, '{"name":"test"}');35 done();36 });37 });38 });39});40AssertionError: expected { Object (body, headers, ...) } to deeply equal '{"name":"test"}'41 at Request._callback (test.js:39:28)42 at Request.self.callback (node_modules/request/request.js:185:22)43 at emitTwo (events.js:106:13)44 at Request.emit (events.js:191:7)45 at Request. (node_modules/request/request.js:1161:10)46 at emitOne (events.js:96:13)47 at Request.emit (events.js:188:7)48 at IncomingMessage. (node_modules/request/request.js:1083:12)49 at Object.onceWrapper (events.js:293:19)50 at emitNone (events.js:86:13)51 at IncomingMessage.emit (events.js

Full Screen

Using AI Code Generation

copy

Full Screen

1const mb = require('mountebank');2const stubsToValidateWithPredicates = require('./stubsToValidateWithPredicates');3const stubs = stubsToValidateWithPredicates.getStubsToValidateWithPredicates();4mb.start({5}, function () {6 mb.createImposter(3000, stubs, function () {7 console.log('Imposter created');8 });9});10const mb = require('mountebank');11const stubs = {12 {13 {14 "equals": {15 "query": {16 }17 }18 }19 {20 "is": {21 "headers": {22 },23 "body": {24 }25 }26 }27 }28};29exports.getStubsToValidateWithPredicates = function () {30 return stubs;31};

Full Screen

Using AI Code Generation

copy

Full Screen

1var assert = require('assert');2var mb = require('mountebank');3var stub = {4 { equals: { method: 'GET' } },5 { equals: { path: '/test' } }6 { is: { statusCode: 200, body: 'OK' } }7};8mb.start({9}, function (error) {10 if (error) {11 console.error(error);12 process.exit(1);13 }14 mb.stub(server, stub, function (error) {15 if (error) {16 console.error(error);17 process.exit(1);18 }19 mb.stubsToValidateWithPredicates(server, function (error, stubs) {20 if (error) {21 console.error(error);22 process.exit(1);23 }24 assert.deepEqual(stubs, [stub]);25 mb.stop(server, function (error) {26 if (error) {27 console.error(error);28 process.exit(1);29 }30 });31 });32 });33});

Full Screen

Using AI Code Generation

copy

Full Screen

1const chai = require('chai');2const chaiAsPromised = require('chai-as-promised');3const chaiSubset = require('chai-subset');4const expect = chai.expect;5const mountebank = require('mountebank');6const port = 2525;7const stubs = require('./stubs');8const predicates = require('./predicates');9const path = require('path');10const fs = require('fs');11const imposter = require('./imposter');12const request = require('request');13chai.use(chaiAsPromised);14chai.use(chaiSubset);15describe('create imposter', () => {16 it('should create imposter', () => {17 return mb.post('/imposters', imposter)18 .then(response => {19 expect(response.statusCode).to.equal(201);20 });21 });22});23describe('add stubs', () => {24 it('should add stubs', () => {25 return mb.stubsToValidateWithPredicates(2525, stubs, predicates)26 .then(response => {27 expect(response.statusCode).to.equal(201);28 });29 });30});31describe('get request', () => {32 it('should return response', () => {33 return mb.get('/imposters/2525')34 .then(response => {35 expect(response.body.stubs[0].responses[0].body).to.equal('{"name":"test"}');36 });37 });38});39describe('delete imposter', () => {40 it('should delete imposter', () => {41 return mb.del('/imposters/2525')42 .then(response => {43 expect(response.statusCode).to.equal(200);44 });45 });46});47module.exports = [{48 responses: [{49 is: {50 body: '{"name":"test"}'51 }52 }]53}];54module.exports = [{55 and: [{56 equals: {57 }58 }]59}];60module.exports = {61 stubs: [{62 responses: [{63 is: {

Full Screen

Using AI Code Generation

copy

Full Screen

1var imposter = require('mountebank').create();2imposter.useLogger(console);3imposter.useFile('imposters.json');4imposter.start(2525, function () {5 console.log("imposter started");6 imposter.addStub({7 predicates: [{8 equals: {9 }10 }],11 responses: [{12 is: {13 headers: { 'Content-Type': 'application/json' },14 body: { message: 'Hello World' }15 }16 }]17 }, function () {18 console.log("stub added");19 });20});21{22 {23 {24 "equals": {25 }26 }27 {28 "is": {29 "headers": {30 },31 "body": {32 }33 }34 }35 }36}37const imposter = require('mountebank').create();38imposter.useLogger(console);39imposter.useFile('imposters.json');40imposter.start(2525, function () {41 console.log("imposter started");42 imposter.stubsToValidateWithPredicates([43 {44 equals: {45 }46 }47 ], function (error, stubs) {48 console.log("stubs", stubs);49 });50});51{52 {53 {54 "equals": {55 }56 }57 {58 "is": {59 "headers": {60 },61 "body": {62 }63 }

Full Screen

Using AI Code Generation

copy

Full Screen

1const mb = require('mountebank');2const fs = require('fs');3const path = require('path');4const logger = require('winston');5const os = require('os');6const stubsToValidateWithPredicates = require('./stubsToValidateWithPredicates');7const stubsToValidateWithPredicates = require('./stubsToValidateWithPredicates');8const imposter = mb.create({9});10const stub = {11 {12 equals: {13 }14 }15 {16 is: {17 }18 }19};20const stub = {21 {22 equals: {23 }24 }25 {26 is: {27 }

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