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

setup_servers.js

Source:setup_servers.js Github

copy

Full Screen

1/*2 * Copyright © 2019 Lisk Foundation3 *4 * See the LICENSE file at the top-level directory of this distribution5 * for licensing information.6 *7 * Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,8 * no part of this software, including this file, may be copied, modified,9 * propagated, or distributed except according to the terms contained in the10 * LICENSE file.11 *12 * Removal or modification of this copyright notice is prohibited.13 */14'use strict';15const _ = require('lodash');16const rewire = require('rewire');17const fs = require('fs');18const https = require('https');19const http = require('http');20const im = require('istanbul-middleware');21const setupServers = rewire(22 '../../../../../../src/modules/http_api/init_steps/setup_servers',23);24describe('init_steps/setup_servers', () => {25 let servers;26 let expressStub;27 let socketIOStub;28 const stub = {29 components: {30 logger: {31 debug: sinonSandbox.stub(),32 },33 },34 config: {35 coverage: false,36 trustProxy: false,37 ssl: {38 enabled: false,39 options: {40 key: './ssl/lisk.key',41 cert: './ssl/lisk.crt',42 },43 },44 },45 };46 beforeEach(async () => {47 sinonSandbox.stub(im);48 });49 afterEach(async () => {50 sinonSandbox.restore();51 });52 describe('ssl.enabled=false', () => {53 beforeEach(async () => {54 sinonSandbox.stub(fs, 'readFileSync');55 sinonSandbox.stub(https, 'createServer').returns('https');56 sinonSandbox.stub(http, 'createServer').returns('http');57 socketIOStub = sinonSandbox.stub().returns('socket');58 setupServers.__set__('socketIO', socketIOStub);59 expressStub = {60 use: sinonSandbox.stub(),61 enable: sinonSandbox.stub(),62 };63 setupServers.__set__('express', () => expressStub);64 const clonedStub = _.cloneDeep(stub);65 clonedStub.config.trustProxy = true;66 clonedStub.config.coverage = true;67 servers = setupServers(clonedStub);68 });69 it('should create an http server and assign it to object instance', async () => {70 expect(http.createServer).to.be.called;71 expect(https.createServer).to.not.be.called;72 expect(servers.httpServer).to.equal('http');73 expect(servers.httpsServer).to.equal(undefined);74 });75 it('should create a ws server with socket.io and assign it to object instance', async () => {76 expect(socketIOStub).to.be.calledOnce;77 expect(servers.wsServer).to.equal('socket');78 expect(servers.wssServer).to.equal(undefined);79 });80 it('should enable coverage if enabled in config', async () =>81 expect(stub.components.logger.debug).to.be.called);82 it('should call express.enable("trustProxy") if trustProxy is enabled in config', async () =>83 expect(expressStub.enable).to.be.calledOnce);84 it('should return object holding correct 5 properties', async () =>85 expect(servers).to.have.keys(86 'expressApp',87 'httpServer',88 'httpsServer',89 'wsServer',90 'wssServer',91 ));92 });93 describe('ssl.enabled=true', () => {94 beforeEach(async () => {95 sinonSandbox.stub(fs, 'readFileSync');96 sinonSandbox.stub(https, 'createServer').returns('https');97 sinonSandbox.stub(http, 'createServer').returns('http');98 socketIOStub = sinonSandbox.stub().returns('socket');99 setupServers.__set__('socketIO', socketIOStub);100 expressStub = {101 use: sinonSandbox.stub(),102 enable: sinonSandbox.stub(),103 };104 setupServers.__set__('express', () => expressStub);105 const clonedStub = _.cloneDeep(stub);106 clonedStub.config.ssl.enabled = true;107 servers = setupServers(clonedStub);108 });109 it('should create https server if ssl is enabled in config and assign it to object instance', async () => {110 expect(https.createServer).to.be.called;111 expect(servers.httpsServer).to.equal('https');112 });113 it('should create wss server if ssl is enabled in config and assign it to object instance', async () => {114 expect(socketIOStub.callCount).to.equal(2);115 expect(servers.wssServer).to.equal('socket');116 });117 it('should read ssl options from filesystem for privateKey and certificate', async () => {118 expect(fs.readFileSync.callCount).to.equal(2);119 });120 it('should call readFileSync with correct parameters', async () => {121 expect(fs.readFileSync).to.be.calledWithExactly(122 stub.config.ssl.options.cert,123 );124 expect(fs.readFileSync).to.be.calledWithExactly(125 stub.config.ssl.options.key,126 );127 });128 });...

Full Screen

Full Screen

clone.ts

Source:clone.ts Github

copy

Full Screen

1import { expect } from 'chai';2import * as fc from 'fast-check';3import { clone } from '../lib';4const stub = {5 obj: {6 a: true,7 b: false8 },9 arr: [1,2,3],10 map: new Map([[1,2], [3,4]]),11 set: new Set([1, 2, 3, 4])12}13describe('Clones', function () {14 it('should clone any kind of value', function () {15 const predicate = (a) => {16 clone(a);17 };18 fc.assert(19 fc.property(20 fc.anything(),21 predicate22 ),23 { numRuns: 10000,verbose: true }24 );25 fc.assert(26 fc.property(27 fc.date(),28 predicate29 )30 );31 });32 it('clones different data types', () => {33 const obj = clone(stub.obj);34 expect(obj).not.to.equal(stub.obj);35 const arr = clone(stub.arr);36 expect(arr).not.to.equal(stub.arr);37 const map = clone(stub.map);38 expect(map).not.to.equal(stub.map);39 const set = clone(stub.set);40 expect(set).not.to.equal(stub.set);41 });42 it('clones nested objects', () => {43 const clonedStub = clone(stub);44 expect(clonedStub).not.to.equal(stub);45 expect(clonedStub.obj).not.to.equal(stub.obj);46 expect(clonedStub.arr).not.to.equal(stub.arr);47 expect(clonedStub.map).not.to.equal(stub.map);48 expect(clonedStub.set).not.to.equal(stub.set);49 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const stub = {2 {3 equals: {4 }5 }6 {7 is: {8 }9 }10};11const clonedStub = await mb.cloneStub(stub);12const stub = {13 {14 equals: {15 }16 }17 {18 is: {19 }20 }21};22const clonedStub = await mb.cloneStub(stub);

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var stub = {3 {4 equals: {5 }6 }7 {8 is: {9 headers: {10 },11 body: {12 }13 }14 }15};16mb.create(stub).then(function (impostor) {17 console.log(impostor.port);18});19var mb = require('mountebank');20mb.create({21 {22 {23 equals: {24 }25 }26 {27 is: {28 headers: {29 },30 body: {31 }32 }33 }34 }35}).then(function (impostor) {36 console.log(impostor.port);37});38{ [Error: connect ECONNREFUSED

Full Screen

Using AI Code Generation

copy

Full Screen

1var imposter = {2 {3 {4 equals: {5 }6 }7 {8 is: {9 headers: {10 },11 body: {12 }13 }14 }15 }16};17var mb = require('mountebank'),18 Q = require('q');19mb.create(imposter).then(function (server) {20 return Q.all([21 server.get('/test').then(function (response) {22 console.log(response.body);23 }),24 server.get('/test').then(function (response) {25 console.log(response.body);26 }),27 server.get('/test').then(function (response) {28 console.log(response.body);29 })30 ]);31});32var imposter = {33 {34 {35 equals: {36 }37 }38 {39 is: {40 headers: {41 },42 body: {43 }44 }45 }46 }47};48var mb = require('mountebank'),49 Q = require('q');50mb.create(imposter).then(function (server) {51 return Q.all([52 server.get('/test').then(function (response) {53 console.log(response.body);54 }),55 server.get('/test').then(function (response) {56 console.log(response.body);57 }),58 server.get('/test').then(function (response) {59 console.log(response.body);60 })61 ]);62});

Full Screen

Using AI Code Generation

copy

Full Screen

1var stub = {2 {3 equals: {4 }5 }6 {7 is: {8 headers: {9 },10 body: {11 }12 }13 }14};15var mb = require('mountebank');16var Q = require('q');17var port = 2525;18var imposterPort = 3000;19var mbServer = mb.create({20});21mbServer.then(function (server) {22 server.start()23 .then(function () {24 return server.createImposter({25 });26 })27 .then(function (imposter) {28 return imposter.addStub(stub);29 })30 .then(function () {31 })32 .then(function () {33 return server.stop();34 })35 .catch(function (error) {36 console.log(error);37 });38});

Full Screen

Using AI Code Generation

copy

Full Screen

1var stub = {2 {3 is: {4 }5 }6};7var clonedStub = require('mountebank').clone(stub);8clonedStub.responses[0].is.statusCode = 500;9var stub = {10 {11 is: {12 }13 }14};15var clonedStub = require('mountebank').clone(stub);16clonedStub.responses[0].is.statusCode = 500;

Full Screen

Using AI Code Generation

copy

Full Screen

1var assert = require('assert');2var mb = require('mountebank');3var Q = require('q');4var port = 2525;5var protocol = 'http';6 {7 {8 {9 equals: {10 }11 }12 {13 is: {14 headers: {15 },16 }17 }18 }19 }20];21var test = function () {22 var deferred = Q.defer();23 mb.create({port: port, allowInjection: true}, function (error, mbServer) {24 mbServer.createImposter(imposters[0], function (error, imposter) {25 var request = require('request');26 request.get({27 }, function (error, response, body) {28 assert.equal(response.statusCode, 200);29 assert.equal(body, 'test');30 deferred.resolve();31 });32 });33 });34 return deferred.promise;35};36test()37 .then(function () {38 console.log('Test passed');39 })40 .fail(function (error) {41 console.log('Test failed');42 console.log(error);43 });44{45 "dependencies": {46 }47}

Full Screen

Using AI Code Generation

copy

Full Screen

1const stub = require('./stub.json');2const mb = require('mountebank');3const port = 2525;4const imposters = [{ port: 3000, protocol: 'http', stubs: [stub] }];5const options = { imposters };6mb.create(options, port).then(function (imposters) {7 console.log('imposters created: ' + JSON.stringify(imposters));8});9{10 {11 "equals": {12 }13 }14 {15 "is": {16 "headers": {17 },18 "body": {19 }20 }21 }22}23{"message":"Hello World"}

Full Screen

Using AI Code Generation

copy

Full Screen

1const mb = require('mountebank');2const request = require('request-promise');3const assert = require('assert');4const port = 2525;5const imposterPort = 3000;6const imposters = {7 stubs: [{8 predicates: [{9 equals: {10 }11 }],12 responses: [{13 is: {14 }15 }]16 }]17};18const options = {19};20async function test() {21 await mb.create(port);22 await mb.post(`/imposters`, imposters);23 const response = await request(options);24 assert.equal(response, 'Hello World!');25 await mb.del(`/imposters/${imposterPort}`);26 await mb.stop(port);27}28test();

Full Screen

Using AI Code Generation

copy

Full Screen

1const mb = require('mountebank');2const config = require('./config.json');3const port = config.port;4const protocol = config.protocol;5const host = config.host;6const stub = require('./stub.json');7const imposters = require('./imposters.json');8const server = require('./server.json');9const request = require('request');10const imposter = require('./imposter.json');11const imposterConfig = require('./imposterConfig.json');12const imposterConfig2 = require('./imposterConfig2.json');13const imposterConfig3 = require('./imposterConfig3.json');14mb.cloneStub(port, stub, imposterConfig, function (error, response) {15 if (error) {16 console.log(error);17 } else {18 console.log(response);19 }20});21mb.cloneStub(port, stub, imposterConfig2, function (error, response) {22 if (error) {23 console.log(error);24 } else {25 console.log(response);26 }27});28mb.cloneStub(port, stub, imposterConfig3, function (error, response) {29 if (error) {30 console.log(error);31 } else {32 console.log(response);33 }34});35mb.cloneStub(port, stub, imposterConfig4, function (error, response) {36 if (error) {37 console.log(error);38 } else {39 console.log(response);40 }41});42mb.cloneStub(port, stub, imposterConfig5, function (error, response) {43 if (error) {44 console.log(error);45 } else {46 console.log(response);47 }48});49mb.cloneStub(port, stub, imposterConfig6, function (error, response) {50 if (error) {51 console.log(error);52 } else {53 console.log(response);54 }55});56mb.cloneStub(port, stub, imposterConfig7, function (error, response) {57 if (error) {58 console.log(error);59 } else {60 console.log(response);61 }62});63mb.cloneStub(port, stub, imposterConfig8,

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