Best JavaScript code snippet using mountebank
imposter.js
Source:imposter.js
1'use strict';2/**3 * An imposter represents a protocol listening on a socket. Most imposter4 * functionality is in each particular protocol implementation. This module5 * exists as a bridge between the API and the protocol, mapping back to pretty6 * JSON for the end user.7 * @module8 */9function createErrorHandler (deferred, port) {10 return error => {11 const errors = require('../util/errors');12 if (error.errno === 'EADDRINUSE') {13 deferred.reject(errors.ResourceConflictError(`Port ${port} is already in use`));14 }15 else if (error.errno === 'EACCES') {16 deferred.reject(errors.InsufficientAccessError());17 }18 else {19 deferred.reject(error);20 }21 };22}23/**24 * Create the imposter25 * @param {Object} Protocol - The protocol factory for creating servers of that protocol26 * @param {Object} creationRequest - the parsed imposter JSON27 * @param {Object} baseLogger - the logger28 * @param {Object} config - command line options29 * @param {Function} isAllowedConnection - function to determine if the IP address of the requestor is allowed30 * @returns {Object}31 */32function create (Protocol, creationRequest, baseLogger, config, isAllowedConnection) {33 function scopeFor (port) {34 let scope = `${creationRequest.protocol}:${port}`;35 if (creationRequest.name) {36 scope += ' ' + creationRequest.name;37 }38 return scope;39 }40 const Q = require('q'),41 deferred = Q.defer(),42 domain = require('domain').create(),43 errorHandler = createErrorHandler(deferred, creationRequest.port),44 compatibility = require('./compatibility'),45 logger = require('../util/scopedLogger').create(baseLogger, scopeFor(creationRequest.port)),46 helpers = require('../util/helpers'),47 imposterState = {},48 unresolvedProxies = {},49 header = helpers.clone(creationRequest);50 // Free up the memory by allowing garbage collection of stubs when using filesystemBackedImpostersRepository51 delete header.stubs;52 let stubs;53 let resolver;54 let encoding;55 let numberOfRequests = 0;56 compatibility.upcast(creationRequest);57 // If the CLI --mock flag is passed, we record even if the imposter level recordRequests = false58 const recordRequests = config.recordRequests || creationRequest.recordRequests;59 function findFirstMatch (request) {60 const filter = stubPredicates => {61 const predicates = require('./predicates');62 return stubPredicates.every(predicate =>63 predicates.evaluate(predicate, request, encoding, logger, imposterState));64 };65 return stubs.first(filter).then(match => {66 if (match.success) {67 logger.debug(`using predicate match: ${JSON.stringify(match.stub.predicates || {})}`);68 }69 else {70 logger.debug('no predicate match');71 }72 return match;73 });74 }75 function recordMatch (stub, request, response, responseConfig, start) {76 if (response.proxy) {77 // Out of process proxying, so we don't have the actual response yet.78 const parts = response.callbackURL.split('/'),79 proxyResolutionKey = parts[parts.length - 1];80 unresolvedProxies[proxyResolutionKey] = {81 recordMatch: proxyResponse => {82 return stub.recordMatch(request, proxyResponse, responseConfig, new Date() - start);83 }84 };85 return Q();86 }87 else if (response.response) {88 // Out of process responses wrap the result in an outer response object89 return stub.recordMatch(request, response.response, responseConfig, new Date() - start);90 }91 else {92 // In process resolution93 return stub.recordMatch(request, response, responseConfig, new Date() - start);94 }95 }96 // requestDetails are not stored with the imposter97 // It was created to pass the raw URL to maintain the exact querystring during http proxying98 // without having to change the path / query options on the stored request99 function getResponseFor (request, requestDetails) {100 if (!isAllowedConnection(request.ip, logger)) {101 return Q({ blocked: true, code: 'unauthorized ip address' });102 }103 const start = new Date();104 numberOfRequests += 1;105 if (recordRequests) {106 stubs.addRequest(request);107 }108 return findFirstMatch(request).then(match => {109 return match.stub.nextResponse().then(responseConfig => {110 logger.debug(`generating response from ${JSON.stringify(responseConfig)}`);111 return resolver.resolve(responseConfig, request, logger, imposterState, requestDetails).then(response => {112 if (config.recordMatches) {113 return recordMatch(match.stub, request, response, responseConfig, start).then(() => response);114 }115 return response;116 });117 });118 });119 }120 function getProxyResponseFor (proxyResponse, proxyResolutionKey) {121 return resolver.resolveProxy(proxyResponse, proxyResolutionKey, logger).then(response => {122 let promise = Q();123 if (config.recordMatches && unresolvedProxies[String(proxyResolutionKey)].recordMatch) {124 promise = unresolvedProxies[String(proxyResolutionKey)].recordMatch(response);125 }126 delete unresolvedProxies[String(proxyResolutionKey)];127 return promise.then(() => response);128 });129 }130 domain.on('error', errorHandler);131 domain.run(() => {132 if (!helpers.defined(creationRequest.host) && helpers.defined(config.host)) {133 creationRequest.host = config.host;134 }135 Protocol.createServer(creationRequest, logger, getResponseFor).done(server => {136 if (creationRequest.port !== server.port) {137 creationRequest.port = server.port;138 logger.changeScope(scopeFor(server.port));139 }140 logger.info('Open for business...');141 stubs = server.stubs;142 resolver = server.resolver;143 encoding = server.encoding;144 function stop () {145 const stopDeferred = Q.defer();146 server.close(() => {147 logger.info('Ciao for now');148 return stopDeferred.resolve({});149 });150 return stopDeferred.promise;151 }152 function loadRequests () {153 return recordRequests ? stubs.loadRequests() : require('q')([]);154 }155 const printer = require('./imposterPrinter').create(header, server, loadRequests),156 toJSON = options => printer.toJSON(numberOfRequests, options);157 return deferred.resolve({158 port: server.port,159 url: '/imposters/' + server.port,160 creationRequest: creationRequest,161 toJSON,162 stop,163 getResponseFor,164 getProxyResponseFor165 });166 });167 });168 return deferred.promise;169}...
Using AI Code Generation
1const request = require('request');2const options = {3 headers: {4 },5 body: {6 {7 {8 is: {9 }10 }11 {12 equals: {13 }14 },15 {16 equals: {17 }18 }19 }20 },21};22request(options, function (error, response, body) {23 if (error) throw new Error(error);24 console.log(body);25});26const request = require('request');27const options = {28 headers: {29 },30 body: {31 {32 {33 is: {34 }35 }36 {37 equals: {38 }39 },40 {41 equals: {42 }43 }44 }45 },46};47request(options, function (error, response, body) {48 if (error) throw new Error(error);49 console.log(body);50});51const request = require('request');52const options = {53 headers: {54 },55 body: {56 {57 {58 is: {59 }60 }61 {62 equals: {63 }64 },65 {
Using AI Code Generation
1var mb = require('mountebank');2var mbServer = mb.create({3});4mbServer.then(function (server) {5 server.addStub({6 {7 equals: {8 }9 }10 {11 is: {12 }13 }14 });15 server.addStub({16 {17 equals: {18 }19 }20 {21 proxy: {22 }23 }24 });25 server.addStub({26 {27 equals: {28 }29 }30 {31 proxy: {32 }33 }34 });35});36var mb = require('mountebank');37var mbServer = mb.create({38});39mbServer.then(function (server) {40 server.addStub({41 {42 equals: {43 }44 }45 {46 is: {47 }48 }49 });50 server.addStub({51 {52 equals: {53 }54 }55 {56 proxy: {57 }58 }59 });
Using AI Code Generation
1var mb = require('mountebank');2var proxyResolutionKey = mb.proxyResolutionKey;3var port = 2525;4var imposter = {5 {6 {7 proxy: {8 }9 }10 }11};12mb.createImposter(imposter, function (error, imposter) {13});14var mb = require('mountebank');15var proxyResolutionKey = mb.proxyResolutionKey;16var port = 2525;17var imposter = {18 {19 {20 proxy: {21 }22 }23 }24};25mb.createImposter(imposter, function (error, imposter) {26});27var mb = require('mountebank');28var proxyResolutionKey = mb.proxyResolutionKey;29var port = 2525;30var imposter = {31 {32 {33 proxy: {34 }35 }36 }37};38mb.createImposter(imposter, function (error, imposter) {39});40var mb = require('mountebank');41var proxyResolutionKey = mb.proxyResolutionKey;42var port = 2525;43var imposter = {44 {45 {46 proxy: {
Using AI Code Generation
1var mb = require('mountebank');2var http = require('http');3var Q = require('q');4var fs = require('fs');5var path = require('path');6var util = require('util');7var config = require('config');8var Imposter = function (port, protocol, stubs, name) {9 this.port = port;10 this.protocol = protocol;11 this.stubs = stubs;12 this.name = name;13};14Imposter.prototype.create = function () {15 var deferred = Q.defer();16 mb.create(this.port, this.protocol, this.stubs, this.name, function (error, imposter) {17 if (error) {18 deferred.reject(error);19 } else {20 deferred.resolve(imposter);21 }22 });23 return deferred.promise;24};25Imposter.prototype.stop = function () {26 var deferred = Q.defer();27 mb.stop(this.port, function (error) {28 if (error) {29 deferred.reject(error);30 } else {31 deferred.resolve();32 }33 });34 return deferred.promise;35};36var getImposter = function (imposter) {37 var deferred = Q.defer();38 mb.get(imposter.port, function (error, imposter) {39 if (error) {40 deferred.reject(error);41 } else {42 deferred.resolve(imposter);43 }44 });45 return deferred.promise;46};47var postImposter = function (imposter, stub) {48 var deferred = Q.defer();49 mb.post(imposter.port, stub, function (error, imposter) {50 if (error) {51 deferred.reject(error);52 } else {53 deferred.resolve(imposter);54 }55 });56 return deferred.promise;57};58var deleteImposter = function (imposter, stub) {59 var deferred = Q.defer();60 mb.del(imposter.port, stub, function (error, imposter) {61 if (error) {62 deferred.reject(error);63 } else {64 deferred.resolve(imposter);65 }66 });67 return deferred.promise;68};69var getProxyResolutionKey = function (imposter) {70 var deferred = Q.defer();71 mb.proxyResolutionKey(imposter.port, function (error, key) {72 if (error) {73 deferred.reject(error);74 } else {75 deferred.resolve(key);76 }77 });78 return deferred.promise;79};80var getRequests = function (imposter) {
Using AI Code Generation
1var mb = require('mountebank');2var options = {3}4mb.create(options, function (error, mb) {5 if (error) {6 console.error(error);7 } else {8 mb.post('/imposters', {9 {10 {11 is: {12 }13 }14 }15 }, function (error, response) {16 if (error) {17 console.error(error);18 } else {19 console.log('Imposter created at port %s', response.port);20 console.log('Proxy resolution key is %s', response.proxyResolutionKey);21 }22 });23 }24});25var mb = require('mountebank');26var options = {27}28mb.create(options, function (error, mb) {29 if (error) {30 console.error(error);31 } else {32 mb.post('/imposters', {33 {34 {35 is: {36 }37 }38 }39 }, function (error, response) {40 if (error) {41 console.error(error);42 } else {43 console.log('Imposter created at port %s', response.port);44 console.log('Proxy resolution key is %s', response.proxyResolutionKey);45 }46 });47 }48});49var mb = require('mountebank');50var options = {51}52mb.create(options, function (error, mb) {53 if (error) {54 console.error(error);55 } else {56 mb.post('/imposters', {57 {58 {
Using AI Code Generation
1var proxy = require('mountebank-proxy');2var mb = proxy.create({ port: 2525 });3mb.proxyResolutionKey('test');4var proxy = require('mountebank-proxy');5var mb = proxy.create({ port: 2525 });6mb.proxyResolutionKey('test');7var proxy = require('mountebank-proxy');8var mb = proxy.create({ port: 2525 });9mb.proxyResolutionKey('test');10var proxy = require('mountebank-proxy');11var mb = proxy.create({ port: 2525 });12mb.proxyResolutionKey('test');13var proxy = require('mountebank-proxy');14var mb = proxy.create({ port: 2525 });15mb.proxyResolutionKey('test');16var proxy = require('mountebank-proxy');17var mb = proxy.create({ port: 2525 });18mb.proxyResolutionKey('test');19var proxy = require('mountebank-proxy');20var mb = proxy.create({ port: 2525 });21mb.proxyResolutionKey('test');22var proxy = require('mountebank-proxy');23var mb = proxy.create({ port: 2525 });24mb.proxyResolutionKey('test');25var proxy = require('mountebank-proxy');
Using AI Code Generation
1const mb = require('mountebank');2const port = 2525;3const protocol = 'http';4const proxyResolutionKey = 'X-My-Proxy-Resolution-Key';5const proxy = mb.create({ port, protocol, proxyServer, proxyResolutionKey });6proxy.then(() => {7 console.log(`Running on port ${port}`);8});
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!!