How to use keyCaseTransform method in mountebank

Best JavaScript code snippet using mountebank

predicates.js

Source:predicates.js Github

copy

Full Screen

1'use strict';2/**3 * All the predicates that determine whether a stub matches a request4 * @module5 */6function sortObjects (a, b) {7 const stringify = require('json-stable-stringify'),8 isObject = require('../util/helpers').isObject;9 if (isObject(a) && isObject(b)) {10 // Make best effort at sorting arrays of objects to make11 // deepEquals order-independent12 return sortObjects(stringify(a), stringify(b));13 }14 else if (a < b) {15 return -1;16 }17 else {18 return 1;19 }20}21function forceStrings (value) {22 const isObject = require('../util/helpers').isObject;23 if (value === null) {24 return 'null';25 }26 else if (Array.isArray(value)) {27 return value.map(forceStrings);28 }29 else if (isObject(value)) {30 return Object.keys(value).reduce((accumulator, key) => {31 accumulator[key] = forceStrings(value[key]);32 return accumulator;33 }, {});34 }35 else if (typeof value.toString === 'function') {36 return value.toString();37 }38 else {39 return value;40 }41}42function select (type, selectFn, encoding) {43 if (encoding === 'base64') {44 const errors = require('../util/errors');45 throw errors.ValidationError(`the ${type} predicate parameter is not allowed in binary mode`);46 }47 const nodeValues = selectFn();48 // Return either a string if one match or array if multiple49 // This matches the behavior of node's handling of query parameters,50 // which allows us to maintain the same semantics between deepEquals51 // (all have to match, passing in an array if necessary) and the other52 // predicates (any can match)53 if (nodeValues && nodeValues.length === 1) {54 return nodeValues[0];55 }56 else {57 return nodeValues;58 }59}60function orderIndependent (possibleArray) {61 const util = require('util');62 if (util.isArray(possibleArray)) {63 return possibleArray.sort(sortObjects);64 }65 else {66 return possibleArray;67 }68}69function transformObject (obj, transform) {70 Object.keys(obj).forEach(key => {71 obj[key] = transform(obj[key]);72 });73 return obj;74}75function selectXPath (config, encoding, text) {76 const xpath = require('./xpath'),77 combinators = require('../util/combinators'),78 selectFn = combinators.curry(xpath.select, config.selector, config.ns, text);79 return orderIndependent(select('xpath', selectFn, encoding));80}81function selectTransform (config, options) {82 const combinators = require('../util/combinators'),83 helpers = require('../util/helpers'),84 cloned = helpers.clone(config);85 if (config.jsonpath) {86 const stringTransform = options.shouldForceStrings ? forceStrings : combinators.identity;87 // use keyCaseSensitive instead of caseSensitive to help "matches" predicates too88 // see https://github.com/bbyars/mountebank/issues/36189 if (!cloned.keyCaseSensitive) {90 cloned.jsonpath.selector = cloned.jsonpath.selector.toLowerCase();91 }92 return combinators.curry(selectJSONPath, cloned.jsonpath, options.encoding, config, stringTransform);93 }94 else if (config.xpath) {95 if (!cloned.caseSensitive) {96 cloned.xpath.ns = transformObject(cloned.xpath.ns || {}, lowercase);97 cloned.xpath.selector = cloned.xpath.selector.toLowerCase();98 }99 return combinators.curry(selectXPath, cloned.xpath, options.encoding);100 }101 else {102 return combinators.identity;103 }104}105function lowercase (text) {106 return text.toLowerCase();107}108function caseTransform (config) {109 const combinators = require('../util/combinators');110 return config.caseSensitive ? combinators.identity : lowercase;111}112function exceptTransform (config) {113 const combinators = require('../util/combinators'),114 exceptRegexOptions = config.caseSensitive ? 'g' : 'gi';115 if (config.except) {116 return text => text.replace(new RegExp(config.except, exceptRegexOptions), '');117 }118 else {119 return combinators.identity;120 }121}122function encodingTransform (encoding) {123 const combinators = require('../util/combinators');124 if (encoding === 'base64') {125 return text => Buffer.from(text, 'base64').toString();126 }127 else {128 return combinators.identity;129 }130}131function tryJSON (value, predicateConfig) {132 try {133 const keyCaseTransform = predicateConfig.keyCaseSensitive === false ? lowercase : caseTransform(predicateConfig),134 valueTransforms = [exceptTransform(predicateConfig), caseTransform(predicateConfig)];135 // We can't call normalize because we want to avoid the array sort transform,136 // which will mess up indexed selectors like $..title[1]137 return transformAll(JSON.parse(value), [keyCaseTransform], valueTransforms, []);138 }139 catch (e) {140 return value;141 }142}143function selectJSONPath (config, encoding, predicateConfig, stringTransform, text) {144 const jsonpath = require('./jsonpath'),145 combinators = require('../util/combinators'),146 possibleJSON = stringTransform(tryJSON(text, predicateConfig)),147 selectFn = combinators.curry(jsonpath.select, config.selector, possibleJSON);148 return orderIndependent(select('jsonpath', selectFn, encoding));149}150function transformAll (obj, keyTransforms, valueTransforms, arrayTransforms) {151 const combinators = require('../util/combinators'),152 apply = fns => combinators.compose.apply(null, fns),153 isObject = require('../util/helpers').isObject;154 if (Array.isArray(obj)) {155 return apply(arrayTransforms)(obj.map(element => transformAll(element, keyTransforms, valueTransforms, arrayTransforms)));156 }157 else if (isObject(obj)) {158 return Object.keys(obj).reduce((accumulator, key) => {159 accumulator[apply(keyTransforms)(key)] = transformAll(obj[key], keyTransforms, valueTransforms, arrayTransforms);160 return accumulator;161 }, {});162 }163 else if (typeof obj === 'string') {164 return apply(valueTransforms)(obj);165 }166 else {167 return obj;168 }169}170function normalize (obj, config, options) {171 // Needed to solve a tricky case conversion for "matches" predicates with jsonpath/xpath parameters172 if (typeof config.keyCaseSensitive === 'undefined') {173 config.keyCaseSensitive = config.caseSensitive;174 }175 const keyCaseTransform = config.keyCaseSensitive === false ? lowercase : caseTransform(config),176 sortTransform = array => array.sort(sortObjects),177 transforms = [];178 if (options.withSelectors) {179 transforms.push(selectTransform(config, options));180 }181 transforms.push(exceptTransform(config));182 transforms.push(caseTransform(config));183 transforms.push(encodingTransform(options.encoding));184 // sort to provide deterministic comparison for deepEquals,185 // where the order in the array for multi-valued querystring keys186 // and xpath selections isn't important187 return transformAll(obj, [keyCaseTransform], transforms, [sortTransform]);188}189function testPredicate (expected, actual, predicateConfig, predicateFn) {190 const helpers = require('../util/helpers');191 if (!helpers.defined(actual)) {192 actual = '';193 }194 if (helpers.isObject(expected)) {195 return predicateSatisfied(expected, actual, predicateConfig, predicateFn);196 }197 else {198 return predicateFn(expected, actual);199 }200}201function bothArrays (expected, actual) {202 return Array.isArray(actual) && Array.isArray(expected);203}204function allExpectedArrayValuesMatchActualArray (expectedArray, actualArray, predicateConfig, predicateFn) {205 return expectedArray.every(expectedValue =>206 actualArray.some(actualValue => testPredicate(expectedValue, actualValue, predicateConfig, predicateFn)));207}208function onlyActualIsArray (expected, actual) {209 return Array.isArray(actual) && !Array.isArray(expected);210}211function expectedMatchesAtLeastOneValueInActualArray (expected, actualArray, predicateConfig, predicateFn) {212 return actualArray.some(actual => testPredicate(expected, actual, predicateConfig, predicateFn));213}214function expectedLeftOffArraySyntaxButActualIsArrayOfObjects (expected, actual, fieldName) {215 const helpers = require('../util/helpers');216 return !Array.isArray(expected[fieldName]) && !helpers.defined(actual[fieldName]) && Array.isArray(actual);217}218function predicateSatisfied (expected, actual, predicateConfig, predicateFn) {219 if (!actual) {220 return false;221 }222 // Support predicates that reach into fields encoded in JSON strings (e.g. HTTP bodies)223 if (typeof actual === 'string') {224 actual = tryJSON(actual, predicateConfig);225 }226 return Object.keys(expected).every(fieldName => {227 const isObject = require('../util/helpers').isObject;228 if (bothArrays(expected[fieldName], actual[fieldName])) {229 return allExpectedArrayValuesMatchActualArray(230 expected[fieldName], actual[fieldName], predicateConfig, predicateFn);231 }232 else if (onlyActualIsArray(expected[fieldName], actual[fieldName])) {233 if (predicateConfig.exists && expected[fieldName]) {234 return true;235 }236 else {237 return expectedMatchesAtLeastOneValueInActualArray(238 expected[fieldName], actual[fieldName], predicateConfig, predicateFn);239 }240 }241 else if (expectedLeftOffArraySyntaxButActualIsArrayOfObjects(expected, actual, fieldName)) {242 // This is a little confusing, but predated the ability for users to specify an243 // array for the expected values and is left for backwards compatibility.244 // The predicate might be:245 // { equals: { examples: { key: 'third' } } }246 // and the request might be247 // { examples: '[{ "key": "first" }, { "different": true }, { "key": "third" }]' }248 // We expect that the "key" field in the predicate definition matches any object key249 // in the actual array250 return expectedMatchesAtLeastOneValueInActualArray(expected, actual, predicateConfig, predicateFn);251 }252 else if (isObject(expected[fieldName])) {253 return predicateSatisfied(expected[fieldName], actual[fieldName], predicateConfig, predicateFn);254 }255 else {256 return testPredicate(expected[fieldName], actual[fieldName], predicateConfig, predicateFn);257 }258 });259}260function create (operator, predicateFn) {261 return (predicate, request, encoding) => {262 const expected = normalize(predicate[operator], predicate, { encoding: encoding }),263 actual = normalize(request, predicate, { encoding: encoding, withSelectors: true });264 return predicateSatisfied(expected, actual, predicate, predicateFn);265 };266}267function deepEquals (predicate, request, encoding) {268 const expected = normalize(forceStrings(predicate.deepEquals), predicate, { encoding: encoding }),269 actual = normalize(forceStrings(request), predicate, { encoding: encoding, withSelectors: true, shouldForceStrings: true }),270 stringify = require('json-stable-stringify'),271 isObject = require('../util/helpers').isObject;272 return Object.keys(expected).every(fieldName => {273 // Support predicates that reach into fields encoded in JSON strings (e.g. HTTP bodies)274 if (isObject(expected[fieldName]) && typeof actual[fieldName] === 'string') {275 const possibleJSON = tryJSON(actual[fieldName], predicate);276 actual[fieldName] = normalize(forceStrings(possibleJSON), predicate, { encoding: encoding });277 }278 return stringify(expected[fieldName]) === stringify(actual[fieldName]);279 });280}281function matches (predicate, request, encoding) {282 // We want to avoid the lowerCase transform on values so we don't accidentally butcher283 // a regular expression with upper case metacharacters like \W and \S284 // However, we need to maintain the case transform for keys like http header names (issue #169)285 // eslint-disable-next-line no-unneeded-ternary286 const caseSensitive = predicate.caseSensitive ? true : false, // convert to boolean even if undefined287 helpers = require('../util/helpers'),288 clone = helpers.merge(predicate, { caseSensitive: true, keyCaseSensitive: caseSensitive }),289 noexcept = helpers.merge(clone, { except: '' }),290 expected = normalize(predicate.matches, noexcept, { encoding: encoding }),291 actual = normalize(request, clone, { encoding: encoding, withSelectors: true }),292 options = caseSensitive ? '' : 'i',293 errors = require('../util/errors');294 if (encoding === 'base64') {295 throw errors.ValidationError('the matches predicate is not allowed in binary mode');296 }297 return predicateSatisfied(expected, actual, clone, (a, b) => new RegExp(a, options).test(b));298}299function not (predicate, request, encoding, logger, imposterState) {300 return !evaluate(predicate.not, request, encoding, logger, imposterState);301}302function evaluateFn (request, encoding, logger, imposterState) {303 return subPredicate => evaluate(subPredicate, request, encoding, logger, imposterState);304}305function or (predicate, request, encoding, logger, imposterState) {306 return predicate.or.some(evaluateFn(request, encoding, logger, imposterState));307}308function and (predicate, request, encoding, logger, imposterState) {309 return predicate.and.every(evaluateFn(request, encoding, logger, imposterState));310}311function inject (predicate, request, encoding, logger, imposterState) {312 if (request.isDryRun === true) {313 return true;314 }315 const helpers = require('../util/helpers'),316 config = {317 request: helpers.clone(request),318 state: imposterState,319 logger: logger320 },321 compatibility = require('./compatibility');322 compatibility.downcastInjectionConfig(config);323 const injected = `(${predicate.inject})(config, logger, imposterState);`,324 errors = require('../util/errors');325 try {326 return eval(injected);327 }328 catch (error) {329 logger.error(`injection X=> ${error}`);330 logger.error(` source: ${JSON.stringify(injected)}`);331 logger.error(` config.request: ${JSON.stringify(config.request)}`);332 logger.error(` config.state: ${JSON.stringify(config.state)}`);333 throw errors.InjectionError('invalid predicate injection', { source: injected, data: error.message });334 }335}336function toString (value) {337 if (value !== null && typeof value !== 'undefined' && typeof value.toString === 'function') {338 return value.toString();339 }340 else {341 return value;342 }343}344const predicates = {345 equals: create('equals', (expected, actual) => toString(expected) === toString(actual)),346 deepEquals,347 contains: create('contains', (expected, actual) => actual.indexOf(expected) >= 0),348 startsWith: create('startsWith', (expected, actual) => actual.indexOf(expected) === 0),349 endsWith: create('endsWith', (expected, actual) => actual.indexOf(expected, actual.length - expected.length) >= 0),350 matches,351 exists: create('exists', function (expected, actual) {352 return expected ? (typeof actual !== 'undefined' && actual !== '') : (typeof actual === 'undefined' || actual === '');353 }),354 not,355 or,356 and,357 inject358};359/**360 * Resolves all predicate keys in given predicate361 * @param {Object} predicate - The predicate configuration362 * @param {Object} request - The protocol request object363 * @param {string} encoding - utf8 or base64364 * @param {Object} logger - The logger, useful for debugging purposes365 * @param {Object} imposterState - The current state for the imposter366 * @returns {boolean}367 */368function evaluate (predicate, request, encoding, logger, imposterState) {369 const predicateFn = Object.keys(predicate).find(key => Object.keys(predicates).indexOf(key) >= 0),370 errors = require('../util/errors'),371 helpers = require('../util/helpers'),372 clone = helpers.clone(predicate);373 if (predicateFn) {374 return predicates[predicateFn](clone, request, encoding, logger, imposterState);375 }376 else {377 throw errors.ValidationError('missing predicate', { source: predicate });378 }379}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var request = require('request');3var imposter = {4 {5 {6 "is": {7 }8 }9 }10};11mb.create(imposter, function () {12 var options = {13 headers: {14 },15 body: JSON.stringify(imposter)16 };17 request(options, function (error, response, body) {18 if (error) throw new Error(error);19 console.log(body);20 });21});22var mb = require('mountebank');23var request = require('request');24var imposter = {25 {26 {27 "is": {28 }29 }30 }31};32mb.create(imposter, function () {33 var options = {34 headers: {35 },36 body: JSON.stringify(imposter)37 };38 request(options, function (error, response, body) {39 if (error) throw new Error(error);40 console.log(body);41 });42});43var mb = require('mountebank');44var request = require('request');45var imposter = {46 {47 {48 "is": {49 }50 }51 }52};53mb.create(imposter, function () {54 var options = {55 headers: {56 },57 body: JSON.stringify(imposter)58 };

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var options = {3};4mb.start(options, function (error) {5 if (error) {6 console.log(error);7 }8 else {9 console.log('mountebank started');10 }11});

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var options = {3};4mb.create(options, function () {5 console.log('Mountebank started');6});7{8 {9 {10 "is": {11 "headers": {12 },13 "body": {14 }15 }16 }17 }18}19var mb = require('mountebank');20var options = {21};22mb.create(options, function () {23 console.log('Mountebank started');24});25{26 {27 {28 "is": {29 "headers": {30 },31 "body": {32 }33 }34 }35 }36}37var mb = require('mountebank');38var options = {39};40mb.create(options, function () {41 console.log('Mountebank started');42});43{

Full Screen

Using AI Code Generation

copy

Full Screen

1var mbHelper = require('mountebank-helper');2var mb = mbHelper.create({3});4mb.start()5 .then(function () {6 return mb.post('/imposters', {7 stubs: [{8 responses: [{9 is: {10 }11 }]12 }]13 });14 })15 .then(function () {16 return mb.post('/imposters', {17 stubs: [{18 responses: [{19 is: {20 }21 }]22 }]23 });24 })25 .then(function () {26 return mb.get('/imposters/3000');27 })28 .then(function (imposter) {29 console.log(imposter);30 return mb.delete('/imposters');31 })32 .then(function () {33 return mb.stop();34 })35 .then(function () {36 console.log('done');37 })38 .catch(function (err) {39 console.error(err);40 });41### create(options)42### start()43### post(path, data)44### get(path, data)45### put(path, data)46### delete(path, data)

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var obj = { 'foo-bar': 'foo', 'bar-foo': 'bar' };3var transformedObj = mb.keyCaseTransform(obj, 'camel');4console.log(transformedObj);5var mb = require('mountebank');6var obj = { 'fooBar': 'foo', 'barFoo': 'bar' };7var transformedObj = mb.keyCaseTransform(obj, 'dash');8console.log(transformedObj);9var mb = require('mountebank');10var obj = { 'foo-bar': 'foo', 'bar-foo': 'bar' };11var transformedObj = mb.keyCaseTransform(obj, 'snake');12console.log(transformedObj);13var mb = require('mountebank');14var obj = { 'foo_bar': 'foo', 'bar_foo': 'bar' };15var transformedObj = mb.keyCaseTransform(obj, 'title');16console.log(transformedObj);17var mb = require('mountebank');18var obj = { 'Foo Bar': 'foo', 'Bar Foo': 'bar' };19var transformedObj = mb.keyCaseTransform(obj, 'capital');20console.log(transformedObj);21var mb = require('mountebank');22var obj = { 'foo-bar': 'foo', 'bar-foo': 'bar' };23var transformedObj = mb.keyCaseTransform(obj, 'upper');24console.log(transformedObj);25var mb = require('mountebank');26var obj = { '

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var imposter = mb.create({3 stubs: [{4 predicates: [{5 equals: {6 }7 }],8 responses: [{9 is: {10 }11 }]12 }]13});14imposter.create().then(function (createdImposter) {15 createdImposter.keyCaseTransform().then(function (imposter) {16 console.log(imposter);17 imposter.del();18 });19});

Full Screen

Using AI Code Generation

copy

Full Screen

1const mb = require('mountebank');2const mbHelper = require('mountebank-helper');3const imposter = mbHelper.Imposter.create({ port: 8080 });4const stub = mbHelper.Stub.create({5 mbHelper.Predicate.create({6 equals: {7 },8 }),9 mbHelper.Response.create({10 is: {11 body: {12 },13 },14 }),15});16imposter.addStub(stub);17mb.create(imposter).then(() => {18 console.log('Imposter created');19});

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var keyCaseTransform = mb.keyCaseTransform;3var request = require('request');4var fs = require('fs');5var stub = {6 {7 equals: {8 }9 }10 {11 is: {12 }13 }14};15var imposter = {16};17mb.create({18}, function () {19 mb.post('/imposters', imposter, function (error, response) {20 if (error) {21 console.error('Error creating imposter', error);22 }23 else {24 var imposter = JSON.parse(response.body);25 request({26 headers: {27 },28 body: JSON.stringify({29 })30 }, function (error, response, body) {31 if (error) {32 console.error('Error making request', error);33 }34 else {35 console.log(response.statusCode, body);36 mb.del('/imposters/' + imposter.port, function (error, response) {37 if (error) {38 console.error('Error deleting imposter', error);39 }40 else {41 console.log('Deleted imposter');42 mb.stop(function () {43 console.log('Deleted mountebank server');44 });45 }46 });

Full Screen

Using AI Code Generation

copy

Full Screen

1const mb = require('mountebank');2const transform = mb.transform;3const { keyCaseTransform } = transform;4const { createImposter, createResponse, createPredicate } = mb.mbHelper;5const imposter = createImposter(4545, 'http');6imposter.addStub(7 createResponse(200, 'OK', { 'Content-Type': 'application/json' }, { 'foo-bar': 'baz' }),8 createPredicate('path', '/foo', 'exact', true, keyCaseTransform('camelCase'))9);10imposter.save('test.json');11const mb = require('mountebank');12const transform = mb.transform;13const { keyCaseTransform } = transform;14const { createImposter, createResponse, createPredicate } = mb.mbHelper;15const imposter = createImposter(4545, 'http');16imposter.addStub(17 createResponse(200, 'OK', { 'Content-Type': 'application/json' }, { 'foo-bar': 'baz' }),18 createPredicate('path', '/foo', 'exact', true, keyCaseTransform('snakeCase'))19);20imposter.save('test.json');

Full Screen

Using AI Code Generation

copy

Full Screen

1const mb = require('mountebank');2const fs = require('fs');3var json = JSON.parse(fs.readFileSync('./test.json', 'utf8'));4var jsonString = JSON.stringify(json);5var jsonObj = JSON.parse(jsonString);6var transformedJson = mb.keyCaseTransform(jsonObj);7console.log(transformedJson);8console.log(JSON.stringify(transformedJson));9{ 'test-key': 'test-value' }10{"test-key":"test-value"}

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