How to use imposterize method in mountebank

Best JavaScript code snippet using mountebank

impostersRepositoryContractTest.js

Source:impostersRepositoryContractTest.js Github

copy

Full Screen

...57 });58 afterEach(type.afterEach);59 describe('#add', function () {60 it('should allow a reciprocal get', async function () {61 await repo.add(imposterize({ port: 1, value: 2 }));62 const imposter = await repo.get(1);63 assert.deepEqual(deimposterize(imposter), { port: 1, value: 2, stubs: [] });64 });65 it('should accept a string add and a number get', async function () {66 await repo.add(imposterize({ port: '1', value: 2 }));67 const imposter = await repo.get(1);68 assert.deepEqual(deimposterize(imposter), { port: '1', value: 2, stubs: [] });69 });70 it('should accept a number add and a string get', async function () {71 await repo.add(imposterize({ port: 1, value: 2 }));72 const imposter = await repo.get('1');73 assert.deepEqual(deimposterize(imposter), { port: 1, value: 2, stubs: [] });74 });75 it('should save functions on imposter', async function () {76 const imposter = {77 port: 1,78 truthy: () => true,79 falsy: () => false80 };81 await repo.add(imposterize(imposter));82 const saved = await repo.get('1');83 assert.ok(saved.truthy());84 assert.ok(!saved.falsy());85 });86 });87 describe('#get', function () {88 it('should return null if no imposter exists', async function () {89 const imposter = await repo.get(1);90 assert.strictEqual(imposter, null);91 });92 it('should retrieve with stubs', async function () {93 const imposter = {94 port: 1,95 protocol: 'test',96 stubs: [{97 predicates: [{ equals: { key: 1 } }],98 responses: [{ is: { field: 'value' } }]99 }]100 };101 await repo.add(imposterize(imposter));102 const saved = await repo.get('1');103 assert.deepEqual(deimposterize(saved), imposter);104 });105 });106 describe('#all', function () {107 it('should return an empty list if nothing added', async function () {108 const imposters = await repo.all();109 assert.deepEqual(imposters, []);110 });111 it('should return all previously added', async function () {112 await repo.add(imposterize({ port: 1, value: 2 }));113 await repo.add(imposterize({ port: 2, value: 3 }));114 const imposters = await repo.all();115 assert.deepEqual(deimposterize(imposters), [116 { port: 1, value: 2, stubs: [] },117 { port: 2, value: 3, stubs: [] }118 ]);119 });120 it('should return all added with stubs', async function () {121 const first = {122 port: 1,123 stubs: [{124 predicates: [{ equals: { key: 1 } }],125 responses: [{ is: { field: 'value' } }]126 }]127 },128 second = {129 port: 2,130 stubs: [{131 predicates: [],132 responses: [{ is: { key: 1 } }]133 }]134 };135 await repo.add(imposterize(first));136 await repo.add(imposterize(second));137 const imposters = await repo.all();138 assert.deepEqual(deimposterize(imposters), [first, second]);139 });140 });141 describe('#exists', function () {142 it('should return false if given port has not been added', async function () {143 await repo.add(imposterize({ port: 1, value: 2 }));144 const exists = await repo.exists(2);145 assert.strictEqual(exists, false);146 });147 it('should return true if given port has been added', async function () {148 await repo.add(imposterize({ port: 1, value: 2 }));149 const exists = await repo.exists(1);150 assert.strictEqual(exists, true);151 });152 it('should do type conversion if needed', async function () {153 await repo.add(imposterize({ port: 1, value: 2 }));154 const exists = await repo.exists('1');155 assert.strictEqual(exists, true);156 });157 });158 describe('#del', function () {159 it('should return null if imposter never added', async function () {160 const imposter = await repo.del(1);161 assert.strictEqual(imposter, null);162 });163 it('should return imposter and remove from list', async function () {164 await repo.add(imposterize({165 port: 1,166 value: 2,167 stop: mock().returns(Promise.resolve())168 }));169 const imposter = await repo.del(1);170 assert.deepEqual(deimposterize(imposter), { port: 1, value: 2, stubs: [] });171 const saved = await repo.get(1);172 assert.strictEqual(saved, null);173 });174 it('should call stop() on the imposter', async function () {175 const imposter = { port: 1, value: 2, stop: mock().returns(Promise.resolve()) };176 await repo.add(imposterize(imposter));177 await repo.del(1);178 assert.ok(imposter.stop.wasCalled(), imposter.stop.message());179 });180 it('should empty the stubs associated with the imposter', async function () {181 const stub = { responses: [{ is: { key: 'value' } }] },182 imposter = { port: 1, stubs: [stub], stop: mock().returns(Promise.resolve()) };183 await repo.add(imposterize(imposter));184 await repo.del(1);185 const count = await repo.stubsFor(1).count();186 assert.strictEqual(count, 0);187 });188 });189 describe('#stopAllSync', function () {190 it('should call stop() on all imposters and empty list', async function () {191 const first = { port: 1, value: 2, stop: mock().returns(Promise.resolve()) },192 second = { port: 2, value: 3, stop: mock().returns(Promise.resolve()) };193 await repo.add(imposterize(first));194 await repo.add(imposterize(second));195 repo.stopAllSync();196 assert.ok(first.stop.wasCalled(), first.stop.message());197 assert.ok(second.stop.wasCalled(), second.stop.message());198 const imposters = await repo.all();199 assert.deepEqual(imposters, []);200 });201 });202 describe('#deleteAll', function () {203 it('should call stop() on all imposters and empty list', async function () {204 const first = { port: 1, value: 2, stop: mock().returns(Promise.resolve()) },205 second = { port: 2, value: 3, stop: mock().returns(Promise.resolve()) };206 await repo.add(imposterize(first));207 await repo.add(imposterize(second));208 await repo.deleteAll();209 assert.ok(first.stop.wasCalled(), first.stop.message());210 assert.ok(second.stop.wasCalled(), second.stop.message());211 const imposters = await repo.all();212 assert.deepEqual(imposters, []);213 });214 });215 describe('#loadAll', function () {216 it('should load an empty set if nothing previously saved', async function () {217 await repo.loadAll();218 const imposters = await repo.all();219 assert.deepStrictEqual(imposters, []);220 });221 it('should load previously saved imposters', async function () {222 if (type.name === 'inMemoryImpostersRepository') {223 // Does not persist224 return;225 }226 const options = { log: { level: 'info' } };227 // FakeLogger hangs, maybe something to do with the ScopedLogger wrapping it in imposter.js228 const logger = require('../../src/util/logger').createLogger({229 console: {230 colorize: true,231 format: '%level: %message'232 }233 });234 const protocols = require('../../src/models/protocols').loadProtocols(options, '', logger, () => true, repo);235 await repo.add(imposterize({ port: 2526, protocol: 'tcp' }));236 await repo.add(imposterize({ port: 2527, protocol: 'tcp' }));237 await repo.stopAll();238 // Validate clean state239 const imposters = await repo.all();240 assert.deepStrictEqual(imposters, []);241 await repo.loadAll(protocols);242 const loaded = await repo.all();243 const ports = loaded.map(imposter => imposter.port);244 assert.deepStrictEqual(ports, [2526, 2527]);245 await repo.stopAll();246 });247 });248 describe('#stubsFor', function () {249 describe('#count', function () {250 it('should be 0 if no stubs on the imposter', async function () {251 await repo.add(imposterize({ port: 1 }));252 const count = await repo.stubsFor(1).count();253 assert.strictEqual(0, count);254 });255 it('should provide count of all stubs on imposter added initially', async function () {256 const imposter = {257 port: 1,258 protocol: 'test',259 stubs: [260 { responses: [{ is: { field: 1 } }] },261 { responses: [{ is: { field: 2 } }] }262 ]263 };264 await repo.add(imposterize(imposter));265 const count = await repo.stubsFor(1).count();266 assert.strictEqual(2, count);267 });268 it('should all stubs added after creation', async function () {269 const imposter = {270 port: 1,271 protocol: 'test',272 stubs: [{ responses: [{ is: { field: 1 } }] }]273 };274 await repo.add(imposterize(imposter));275 await repo.stubsFor(1).add({ responses: [{ is: { field: 2 } }] });276 const count = await repo.stubsFor(1).count();277 assert.strictEqual(2, count);278 });279 });280 describe('#first', function () {281 it('should default empty array to filter function if no predicates on stub', async function () {282 const imposter = {283 port: 1,284 stubs: [{ responses: [] }]285 };286 await repo.add(imposterize(imposter));287 await repo.stubsFor(1).first(predicates => {288 assert.deepEqual(predicates, []);289 return true;290 });291 });292 it('should return default stub if no match', async function () {293 const imposter = { port: 1, protocol: 'test' };294 await repo.add(imposterize(imposter));295 const match = await repo.stubsFor(1).first(() => false);296 assert.strictEqual(match.success, false);297 const response = await match.stub.nextResponse();298 assert.deepEqual(stripFunctions(response), { is: {} });299 });300 it('should return match with index', async function () {301 const stubs = repo.stubsFor(1),302 firstStub = { predicates: [{ equals: { field: 'value' } }], responses: [{ is: 'first' }] },303 secondStub = { responses: [{ is: 'third' }, { is: 'fourth' }] },304 thirdStub = { responses: [{ is: 'fifth' }, { is: 'sixth' }] },305 imposter = { port: 1, protocol: 'test', stubs: [firstStub, secondStub, thirdStub] };306 await repo.add(imposterize(imposter));307 const match = await stubs.first(predicates => predicates.length === 0);308 assert.strictEqual(match.success, true);309 const response = await match.stub.nextResponse();310 assert.deepEqual(stripFunctions(response), { is: 'third' });311 const index = await response.stubIndex();312 assert.strictEqual(index, 1);313 });314 it('should loop through responses on nextResponse()', async function () {315 const stub = { responses: [{ is: 'first' }, { is: 'second' }] },316 imposter = { port: 1, stubs: [stub] };317 await repo.add(imposterize(imposter));318 const match = await repo.stubsFor(1).first(() => true),319 firstResponse = await match.stub.nextResponse(),320 secondResponse = await match.stub.nextResponse(),321 thirdResponse = await match.stub.nextResponse();322 assert.deepEqual(stripFunctions(firstResponse), { is: 'first' });323 assert.deepEqual(stripFunctions(secondResponse), { is: 'second' });324 assert.deepEqual(stripFunctions(thirdResponse), { is: 'first' });325 });326 it('should handle repeat behavior on nextResponse()', async function () {327 const stub = { responses: [{ is: 'first', repeat: 2 }, { is: 'second' }] },328 imposter = { port: 1, stubs: [stub] };329 await repo.add(imposterize(imposter));330 const match = await repo.stubsFor(1).first(() => true),331 firstResponse = await match.stub.nextResponse(),332 secondResponse = await match.stub.nextResponse(),333 thirdResponse = await match.stub.nextResponse(),334 fourthResponse = await match.stub.nextResponse();335 assert.deepEqual(firstResponse.is, 'first');336 assert.deepEqual(secondResponse.is, 'first');337 assert.deepEqual(thirdResponse.is, 'second');338 assert.deepEqual(fourthResponse.is, 'first');339 });340 it('should support adding responses through addResponse()', async function () {341 const imposter = { port: 1, stubs: [{}] };342 await repo.add(imposterize(imposter));343 const match = await repo.stubsFor(1).first(() => true);344 await match.stub.addResponse({ is: { field: 1 } });345 const secondMatch = await repo.stubsFor(1).first(() => true),346 response = await secondMatch.stub.nextResponse();347 assert.deepEqual(stripFunctions(response), { is: { field: 1 } });348 });349 it('should support recording matches', async function () {350 const imposter = { port: 1, stubs: [{}] };351 await repo.add(imposterize(imposter));352 const match = await repo.stubsFor(1).first(() => true);353 await match.stub.recordMatch('REQUEST', 'RESPONSE');354 const all = await repo.stubsFor(1).toJSON({ debug: true });355 assert.strictEqual(1, all[0].matches.length);356 delete all[0].matches[0].timestamp;357 assert.deepEqual(all[0].matches, [{ request: 'REQUEST', response: 'RESPONSE' }]);358 });359 });360 describe('#toJSON', function () {361 it('should return empty array if nothing added', async function () {362 const json = await repo.stubsFor(1).toJSON();363 assert.deepEqual(json, []);364 });365 it('should return all predicates and original response order of all stubs', async function () {366 const first = {367 predicates: [{ equals: { field: 'value' } }],368 responses: [{ is: { field: 1 } }, { is: { field: 2 } }]369 },370 second = {371 responses: [{ is: { key: 'value' }, behaviors: [{ repeat: 2 }] }]372 },373 imposter = { port: 1, stubs: [first, second] };374 await repo.add(imposterize(imposter));375 const match = await repo.stubsFor(1).first(() => true);376 await match.stub.nextResponse();377 const json = await repo.stubsFor(1).toJSON();378 assert.deepEqual(json, [first, second]);379 });380 it('should not return matches if debug option not set', async function () {381 const imposter = { port: 1, stubs: [{}] };382 await repo.add(imposterize(imposter));383 const match = await repo.stubsFor(1).first(() => true);384 await match.stub.recordMatch('REQUEST', 'RESPONSE');385 const all = await repo.stubsFor(1).toJSON();386 assert.strictEqual(typeof all[0].matches, 'undefined');387 });388 });389 describe('#deleteSavedProxyResponses', function () {390 it('should remove recorded responses and stubs', async function () {391 const first = {392 predicates: [{ equals: { key: 1 } }],393 responses: [{ is: { field: 1, _proxyResponseTime: 100 } }]394 },395 second = {396 predicates: [{ equals: { key: 2 } }],397 responses: [398 { is: { field: 2, _proxyResponseTime: 100 } },399 { is: { field: 3 } }400 ]401 },402 third = {403 responses: [{ proxy: { to: 'http://test.com' } }]404 },405 imposter = { port: 1, stubs: [first, second, third] };406 await repo.add(imposterize(imposter));407 await repo.stubsFor(1).deleteSavedProxyResponses();408 const json = await repo.stubsFor(1).toJSON();409 assert.deepEqual(json, [410 {411 predicates: [{ equals: { key: 2 } }],412 responses: [{ is: { field: 3 } }]413 },414 {415 responses: [{ proxy: { to: 'http://test.com' } }]416 }417 ]);418 });419 });420 describe('#overwriteAll', function () {421 it('should overwrite entire list', async function () {422 const first = { responses: [{ is: 'first' }, { is: 'second' }] },423 second = { responses: [{ is: 'third' }, { is: 'fourth' }] },424 newStub = { responses: [{ is: 'fifth' }, { is: 'sixth' }] },425 imposter = { port: 1, stubs: [first, second] };426 await repo.add(imposterize(imposter));427 await repo.stubsFor(1).overwriteAll([newStub]);428 const all = await repo.stubsFor(1).toJSON(),429 responses = all.map(stub => stub.responses);430 assert.deepEqual(responses, [431 [{ is: 'fifth' }, { is: 'sixth' }]432 ]);433 });434 });435 describe('#overwriteAtIndex', function () {436 it('should overwrite single stub', async function () {437 const first = { responses: [{ is: 'first' }, { is: 'second' }] },438 second = { responses: [{ is: 'third' }, { is: 'fourth' }] },439 newStub = { responses: [{ is: 'fifth' }, { is: 'sixth' }] },440 imposter = { port: 1, stubs: [first, second] };441 await repo.add(imposterize(imposter));442 await repo.stubsFor(1).overwriteAtIndex(newStub, 1);443 const all = await repo.stubsFor(1).toJSON(),444 responses = all.map(stub => stub.responses);445 assert.deepEqual(responses, [446 [{ is: 'first' }, { is: 'second' }],447 [{ is: 'fifth' }, { is: 'sixth' }]448 ]);449 });450 it('should reject the promise if no stub at that index', async function () {451 const imposter = { port: 1 };452 await repo.add(imposterize(imposter));453 try {454 await repo.stubsFor(1).overwriteAtIndex({}, 0);455 assert.fail('Should have rejected');456 }457 catch (err) {458 assert.deepEqual(err, {459 code: 'no such resource',460 message: 'no stub at index 0'461 });462 }463 });464 });465 describe('#deleteAtIndex', function () {466 it('should delete single stub', async function () {467 const first = { responses: [{ is: 'first' }, { is: 'second' }] },468 second = { responses: [{ is: 'third' }, { is: 'fourth' }] },469 third = { responses: [{ is: 'fifth' }, { is: 'sixth' }] },470 imposter = { port: 1, stubs: [first, second, third] };471 await repo.add(imposterize(imposter));472 await repo.stubsFor(1).deleteAtIndex(0);473 const all = await repo.stubsFor(1).toJSON(),474 responses = all.map(stub => stub.responses);475 assert.deepEqual(responses, [476 [{ is: 'third' }, { is: 'fourth' }],477 [{ is: 'fifth' }, { is: 'sixth' }]478 ]);479 });480 it('should reject the promise if no stub at that index', async function () {481 const imposter = { port: 1 };482 await repo.add(imposterize(imposter));483 try {484 await repo.stubsFor(1).deleteAtIndex(0);485 assert.fail('Should have rejected');486 }487 catch (err) {488 assert.deepEqual(err, {489 code: 'no such resource',490 message: 'no stub at index 0'491 });492 }493 });494 });495 describe('#insertAtIndex', function () {496 it('should add single stub at given index', async function () {497 const first = { responses: [{ is: 'first' }, { is: 'second' }] },498 second = { responses: [{ is: 'third' }, { is: 'fourth' }] },499 insertedStub = { responses: [{ is: 'fifth' }, { is: 'sixth' }] },500 imposter = { port: 1, stubs: [first, second] };501 await repo.add(imposterize(imposter));502 await repo.stubsFor(1).insertAtIndex(insertedStub, 0);503 const all = await repo.stubsFor(1).toJSON(),504 responses = all.map(stub => stub.responses);505 assert.deepEqual(responses, [506 [{ is: 'fifth' }, { is: 'sixth' }],507 [{ is: 'first' }, { is: 'second' }],508 [{ is: 'third' }, { is: 'fourth' }]509 ]);510 });511 });512 describe('#addRequest', function () {513 it('should save request with timestamp', async function () {514 const imposter = { port: 1 };515 await repo.add(imposterize(imposter));516 await repo.stubsFor(1).addRequest({ field: 'value' });517 const requests = await repo.stubsFor(1).loadRequests();518 assert.deepEqual(requests, [{ field: 'value', timestamp: requests[0].timestamp }]);519 const delta = new Date() - Date.parse(requests[0].timestamp);520 assert.ok(delta < 1000);521 });522 });523 describe('#deleteSavedRequests', function () {524 it('should clear the requests list', async function () {525 const imposter = { port: 1 };526 await repo.add(imposterize(imposter));527 await repo.stubsFor(1).addRequest({ field: 'value' });528 const requests = await repo.stubsFor(1).loadRequests();529 assert.deepEqual(requests, [{ field: 'value', timestamp: requests[0].timestamp }]);530 await repo.stubsFor(1).deleteSavedRequests();531 const secondRequests = await repo.stubsFor(1).loadRequests();532 assert.deepEqual(secondRequests, []);533 });534 });535 describe('#loadRequests', function () {536 it('should return requests in order without losing any', async function () {537 // Simulate enough rapid load to add two with the same millisecond timestamp538 // The filesystemBackedImpostersRepository has to add some metadata to ensure539 // we capture both if they occur at the same millisecond.540 const stubs = repo.stubsFor(1);...

Full Screen

Full Screen

filesystemBackedImpostersRepositoryTest.js

Source:filesystemBackedImpostersRepositoryTest.js Github

copy

Full Screen

...41 }42 describe('#add', function () {43 it('should create a header file for imposter', async function () {44 const imposter = { port: 1000, protocol: 'test', customField: true, stubs: [], requests: [] };45 await repo.add(imposterize(imposter));46 const saved = read('.mbtest/1000/imposter.json');47 assert.deepEqual(saved, { port: 1000, protocol: 'test', customField: true, stubs: [] });48 });49 it('should add stubs for the imposter', async function () {50 const imposter = {51 port: 1000,52 protocol: 'test',53 stubs: [{54 responses: [{ is: { field: 'value' } }]55 }]56 };57 await repo.add(imposterize(imposter));58 const saved = read('.mbtest/1000/imposter.json');59 assert.strictEqual(saved.stubs.length, 1);60 const meta = read(`.mbtest/1000/${saved.stubs[0].meta.dir}/meta.json`);61 assert.strictEqual(meta.responseFiles.length, 1);62 const response = read(`.mbtest/1000/${saved.stubs[0].meta.dir}/${meta.responseFiles[0]}`);63 assert.deepEqual(response, { is: { field: 'value' } });64 });65 });66 describe('#addReference', function () {67 it('should allow loading without overwriting existing files', async function () {68 const imposter = { port: 1000, protocol: 'test', fn: mock() },69 saved = { port: 1000, protocol: 'test', customField: true, stubs: [] };70 write('.mbtest/1000/imposter.json', saved);71 repo.addReference(imposterize(imposter));72 assert.deepEqual(read('.mbtest/1000/imposter.json'), saved);73 const retrieved = await repo.get(1000);74 retrieved.fn();75 assert.ok(imposter.fn.wasCalled());76 });77 });78 describe('#all', function () {79 it('should not retrieve imposters in database that have not been added', async function () {80 const imposter = { port: 1000, protocol: 'test' };81 // Simulate another process adding the imposter82 write('.mbtest/2000/imposter.json', { port: 2000, protocol: 'test' });83 await repo.add(imposterize(imposter));84 const all = await repo.all();85 assert.deepEqual(stripFunctions(all), [{ port: 1000, protocol: 'test', stubs: [] }]);86 });87 });88 describe('#del', function () {89 it('should return imposter and delete all files', async function () {90 const imposter = {91 port: 1000,92 protocol: 'test',93 stubs: [{94 responses: [{ is: { key: 'value' } }]95 }]96 };97 await repo.add(imposterize(imposter));98 const deleted = await repo.del(1000);99 assert.strictEqual(fs.existsSync('.mbtest/1000'), false);100 assert.deepEqual(stripFunctions(deleted), imposter);101 });102 it('should call stop() even if another process has deleted the directory', async function () {103 const imposter = {104 port: 1000,105 protocol: 'test',106 stop: mock().returns(Promise.resolve())107 };108 await repo.add(imposterize(imposter));109 fs.removeSync('.mbtest/1000');110 await repo.del(1000);111 assert.ok(imposter.stop.wasCalled());112 });113 describe('#deleteAll', function () {114 it('does nothing if no database', async function () {115 await repo.deleteAll();116 assert.strictEqual(fs.existsSync('.mbtest'), false);117 });118 it('removes all added imposters from the filesystem', async function () {119 const first = { port: 1000, protocol: 'test' },120 second = { port: 2000, protocol: 'test' };121 await repo.add(imposterize(first));122 await repo.add(imposterize(second));123 await repo.deleteAll();124 assert.strictEqual(fs.existsSync('.mbtest'), false);125 });126 it('calls stop() on all added imposters even if another process already deleted the database', async function () {127 const first = { port: 1000, protocol: 'test', stop: mock().returns(Promise.resolve()) },128 second = { port: 2000, protocol: 'test', stop: mock().returns(Promise.resolve()) };129 await repo.add(imposterize(first));130 await repo.add(imposterize(second));131 fs.removeSync('.mbtest');132 await repo.deleteAll();133 assert.ok(first.stop.wasCalled());134 assert.ok(second.stop.wasCalled());135 });136 it('does not remove any files not referenced by the repository', async function () {137 const imposter = { port: 1000, protocol: 'test' };138 write('.mbtest/2000/imposter.json', { port: 2000, protocol: 'test' });139 await repo.add(imposterize(imposter));140 await repo.deleteAll();141 assert.strictEqual(fs.existsSync('.mbtest/2000/imposter.json'), true);142 });143 });144 describe('#stopAllSync', function () {145 it('calls stop() on all added imposters even if another process already deleted the database', async function () {146 const first = { port: 1000, protocol: 'test', stop: mock().returns(Promise.resolve()) },147 second = { port: 2000, protocol: 'test', stop: mock().returns(Promise.resolve()) };148 await repo.add(imposterize(first));149 await repo.add(imposterize(second));150 fs.removeSync('.mbtest');151 repo.stopAllSync();152 assert.ok(first.stop.wasCalled());153 assert.ok(second.stop.wasCalled());154 });155 });156 describe('#stubsFor', function () {157 describe('#add', function () {158 it('should merge stubs with imposter header information', async function () {159 const stubs = repo.stubsFor(3000),160 imposter = {161 port: 3000,162 protocol: 'test',163 stubs: []164 },165 stub = {166 predicates: [{ equals: { field: 'request' } }],167 responses: [{ is: { field: 'response' } }]168 };169 await repo.add(imposterize(imposter));170 await stubs.add(stub);171 const header = read('.mbtest/3000/imposter.json'),172 stubDir = header.stubs[0].meta.dir;173 assert.deepEqual(header, {174 port: 3000,175 protocol: 'test',176 stubs: [{177 predicates: [{ equals: { field: 'request' } }],178 meta: { dir: stubDir }179 }]180 });181 const meta = read(`.mbtest/3000/${stubDir}/meta.json`),182 responseFile = meta.responseFiles[0];183 assert.deepEqual(meta, {184 responseFiles: [responseFile],185 orderWithRepeats: [0],186 nextIndex: 0187 });188 assert.deepEqual(read(`.mbtest/3000/${stubDir}/${responseFile}`), { is: { field: 'response' } });189 });190 it('should add to stubs file if it already exists', async function () {191 const stubs = repo.stubsFor(3000),192 firstStub = {193 predicates: [{ equals: { field: 'request-0' } }],194 responses: [{ is: { field: 'response-0' } }]195 },196 secondStub = {197 predicates: [{ equals: { field: 'request-1' } }],198 responses: [{ is: { field: 'response-1' } }]199 },200 imposter = { port: 3000, stubs: [firstStub] };201 await repo.add(imposterize(imposter));202 await stubs.add(secondStub);203 const header = read('.mbtest/3000/imposter.json'),204 stubDirs = header.stubs.map(stub => stub.meta.dir);205 assert.deepEqual(header, {206 port: 3000,207 stubs: [208 {209 predicates: [{ equals: { field: 'request-0' } }],210 meta: { dir: stubDirs[0] }211 },212 {213 predicates: [{ equals: { field: 'request-1' } }],214 meta: { dir: stubDirs[1] }215 }216 ]217 });218 stubDirs.forEach((stubDir, index) => {219 const meta = read(`.mbtest/3000/${stubDir}/meta.json`),220 responseFile = meta.responseFiles[0];221 assert.deepEqual(meta, {222 responseFiles: [responseFile],223 orderWithRepeats: [0],224 nextIndex: 0225 });226 assert.deepEqual(read(`.mbtest/3000/${stubDir}/${responseFile}`),227 { is: { field: `response-${index}` } });228 });229 });230 it('should save multiple responses in separate files', async function () {231 const stubs = repo.stubsFor(3000),232 stub = {233 predicates: [{ equals: { field: 'request' } }],234 responses: [235 { is: { field: 'first-response' } },236 { is: { field: 'second-response' } }237 ]238 },239 imposter = { port: 3000, stubs: [] };240 await repo.add(imposterize(imposter));241 await stubs.add(stub);242 const header = read('.mbtest/3000/imposter.json'),243 stubDir = header.stubs[0].meta.dir,244 meta = read(`.mbtest/3000/${stubDir}/meta.json`),245 responseFiles = meta.responseFiles;246 assert.deepEqual(meta, {247 responseFiles: responseFiles,248 orderWithRepeats: [0, 1],249 nextIndex: 0250 });251 assert.deepEqual(read(`.mbtest/3000/${stubDir}/${responseFiles[0]}`), { is: { field: 'first-response' } });252 assert.deepEqual(read(`.mbtest/3000/${stubDir}/${responseFiles[1]}`), { is: { field: 'second-response' } });253 });254 it('should apply repeat behavior', async function () {255 const stubs = repo.stubsFor(3000),256 stub = {257 predicates: [{ equals: { field: 'request' } }],258 responses: [259 { is: { field: 'first-response' }, repeat: 2 },260 { is: { field: 'second-response' } },261 { is: { field: 'third-response' }, repeat: 3 }262 ]263 },264 imposter = { port: 3000, stubs: [] };265 await repo.add(imposterize(imposter));266 await stubs.add(stub);267 const header = read('.mbtest/3000/imposter.json'),268 stubDir = header.stubs[0].meta.dir,269 meta = read(`.mbtest/3000/${stubDir}/meta.json`);270 assert.deepEqual(meta, {271 responseFiles: meta.responseFiles,272 orderWithRepeats: [0, 0, 1, 2, 2, 2],273 nextIndex: 0274 });275 });276 });277 describe('#insertAtIndex', function () {278 it('should create stub files if empty stubs array and inserting at index 0', async function () {279 const stubs = repo.stubsFor(3000),280 stub = {281 predicates: [{ equals: { field: 'request' } }],282 responses: [{ is: { field: 'response' } }]283 },284 imposter = { port: 3000 };285 await repo.add(imposterize(imposter));286 await stubs.insertAtIndex(stub, 0);287 const header = read('.mbtest/3000/imposter.json'),288 stubDir = header.stubs[0].meta.dir;289 assert.deepEqual(header, {290 port: 3000,291 stubs: [{292 predicates: [{ equals: { field: 'request' } }],293 meta: { dir: stubDir }294 }]295 });296 const meta = read(`.mbtest/3000/${stubDir}/meta.json`),297 responseFile = meta.responseFiles[0];298 assert.deepEqual(meta, {299 responseFiles: [responseFile],300 orderWithRepeats: [0],301 nextIndex: 0302 });303 assert.deepEqual(read(`.mbtest/3000/${stubDir}/${responseFile}`), { is: { field: 'response' } });304 });305 it('should add to stubs file if it already exists', async function () {306 const stubs = repo.stubsFor(3000),307 first = {308 predicates: [{ equals: { field: 'first-request' } }],309 responses: [{ is: { field: 'first-response' } }]310 },311 second = {312 predicates: [{ equals: { field: 'second-request' } }],313 responses: [{ is: { field: 'second-response' } }]314 },315 imposter = { port: 3000, stubs: [first, second] },316 newStub = {317 predicates: [{ equals: { field: 'NEW-REQUEST' } }],318 responses: [{ is: { field: 'NEW-RESPONSE' } }]319 };320 await repo.add(imposterize(imposter));321 await stubs.insertAtIndex(newStub, 1);322 const header = read('.mbtest/3000/imposter.json'),323 stubDirs = header.stubs.map(stub => stub.meta.dir);324 assert.deepEqual(header, {325 port: 3000,326 stubs: [327 {328 predicates: [{ equals: { field: 'first-request' } }],329 meta: { dir: stubDirs[0] }330 },331 {332 predicates: [{ equals: { field: 'NEW-REQUEST' } }],333 meta: { dir: stubDirs[1] }334 },335 {336 predicates: [{ equals: { field: 'second-request' } }],337 meta: { dir: stubDirs[2] }338 }339 ]340 });341 const meta = read(`.mbtest/3000/${stubDirs[1]}/meta.json`),342 responseFile = meta.responseFiles[0];343 assert.deepEqual(read(`.mbtest/3000/${stubDirs[1]}/${responseFile}`),344 { is: { field: 'NEW-RESPONSE' } });345 });346 });347 describe('#deleteAtIndex', function () {348 it('should delete stub and stub dir at specified index', async function () {349 const stubs = repo.stubsFor(3000),350 first = {351 predicates: [{ equals: { field: 'first-request' } }],352 responses: [{ is: { field: 'first-response' } }]353 },354 second = {355 predicates: [{ equals: { field: 'second-request' } }],356 responses: [{ is: { field: 'second-response' } }]357 },358 third = {359 predicates: [{ equals: { field: 'third-request' } }],360 responses: [{ is: { field: 'third-response' } }]361 },362 imposter = { port: 3000, stubs: [first, second, third] };363 await repo.add(imposterize(imposter));364 const header = read('.mbtest/3000/imposter.json');365 const stubDirToDelete = header.stubs[1].meta.dir;366 await stubs.deleteAtIndex(1);367 const newHeader = read('.mbtest/3000/imposter.json'),368 stubDirs = newHeader.stubs.map(stub => stub.meta.dir);369 assert.deepEqual(newHeader, {370 port: 3000,371 stubs: [372 {373 predicates: [{ equals: { field: 'first-request' } }],374 meta: { dir: stubDirs[0] }375 },376 {377 predicates: [{ equals: { field: 'third-request' } }],378 meta: { dir: stubDirs[1] }379 }380 ]381 });382 assert.ok(!fs.existsSync(`.mbtest/3000/${stubDirToDelete}`));383 });384 });385 describe('#overwriteAtIndex', function () {386 it('should overwrite at given index', async function () {387 const stubs = repo.stubsFor(3000),388 first = {389 predicates: [{ equals: { field: 'first-request' } }],390 responses: [{ is: { field: 'first-response' } }]391 },392 second = {393 predicates: [{ equals: { field: 'second-request' } }],394 responses: [{ is: { field: 'second-response' } }]395 },396 imposter = { port: 3000, stubs: [first, second] },397 newStub = {398 predicates: [{ equals: { field: 'third-request' } }],399 responses: [{ is: { field: 'third-response' } }]400 };401 await repo.add(imposterize(imposter));402 const header = read('.mbtest/3000/imposter.json');403 const stubDirToDelete = header.stubs[0].meta.dir;404 await stubs.overwriteAtIndex(newStub, 0);405 const newHeader = read('.mbtest/3000/imposter.json'),406 stubDirs = newHeader.stubs.map(stub => stub.meta.dir);407 assert.deepEqual(read('.mbtest/3000/imposter.json'), {408 port: 3000,409 stubs: [410 {411 predicates: [{ equals: { field: 'third-request' } }],412 meta: { dir: stubDirs[0] }413 },414 {415 predicates: [{ equals: { field: 'second-request' } }],416 meta: { dir: stubDirs[1] }417 }418 ]419 });420 assert.ok(!fs.existsSync(`.mbtest/3000/${stubDirToDelete}`));421 });422 });423 describe('#toJSON', function () {424 it('should error if database corrupted via deleted response file', async function () {425 const stubs = repo.stubsFor(3000),426 stub = {427 predicates: [{ equals: { field: 'request' } }],428 responses: [429 { is: { field: 'first-response' } },430 { is: { field: 'second-response' } }431 ]432 },433 imposter = { port: 3000, stubs: [stub] };434 await repo.add(imposterize(imposter));435 const header = read('.mbtest/3000/imposter.json'),436 stubDir = header.stubs[0].meta.dir,437 meta = read(`.mbtest/3000/${stubDir}/meta.json`),438 lastResponseFile = meta.responseFiles[1],439 responsePath = `.mbtest/3000/${stubDir}/${lastResponseFile}`;440 fs.removeSync(responsePath);441 try {442 await stubs.toJSON();443 assert.fail('should have errored');444 }445 catch (err) {446 assert.strictEqual(err.code, 'corrupted database');447 assert.strictEqual(err.message, 'file not found');448 }449 });450 it('should error if database corrupted via deleted meta file', async function () {451 const stubs = repo.stubsFor(3000),452 stub = {453 predicates: [{ equals: { field: 'request' } }],454 responses: [455 { is: { field: 'first-response' } },456 { is: { field: 'second-response' } }457 ]458 },459 imposter = { port: 3000, stubs: [stub] };460 await repo.add(imposterize(imposter));461 const header = read('.mbtest/3000/imposter.json'),462 stubDir = header.stubs[0].meta.dir,463 metaPath = `.mbtest/3000/${stubDir}/meta.json`;464 fs.removeSync(metaPath);465 try {466 await stubs.toJSON();467 assert.fail('should have errored');468 }469 catch (err) {470 assert.strictEqual(err.code, 'corrupted database');471 assert.strictEqual(err.message, 'file not found');472 }473 });474 it('should error if database corrupted via corrupted JSON', async function () {475 const stubs = repo.stubsFor(3000),476 stub = {477 predicates: [{ equals: { field: 'request' } }],478 responses: [479 { is: { field: 'first-response' } },480 { is: { field: 'second-response' } }481 ]482 },483 imposter = { port: 3000, stubs: [stub] };484 await repo.add(imposterize(imposter));485 const header = read('.mbtest/3000/imposter.json'),486 stubDir = header.stubs[0].meta.dir,487 meta = read(`.mbtest/3000/${stubDir}/meta.json`),488 lastResponseFile = meta.responseFiles[1],489 responsePath = `.mbtest/3000/${stubDir}/${lastResponseFile}`;490 fs.writeFileSync(responsePath, 'CORRUPTED');491 try {492 await stubs.toJSON();493 assert.fail('should have errored');494 }495 catch (err) {496 assert.deepEqual(err, {497 code: 'corrupted database',498 message: `invalid JSON in ${responsePath}`,499 details: 'Unexpected token C in JSON at position 0'500 });501 }502 });503 });504 describe('#deleteSavedRequests', function () {505 it('should delete the imposter\'s requests/ directory', async function () {506 const stubs = repo.stubsFor(3000),507 imposter = { port: 3000, protocol: 'test', stubs: [] };508 await repo.add(imposterize(imposter));509 await stubs.addRequest({ field: 'value' });510 const requestFiles = fs.readdirSync('.mbtest/3000/requests');511 assert.strictEqual(requestFiles.length, 1);512 const requests = await stubs.loadRequests();513 assert.deepEqual(requests, [{ field: 'value', timestamp: requests[0].timestamp }]);514 await stubs.deleteSavedRequests();515 const imposterDir = fs.readdirSync('.mbtest/3000');516 assert.ok(imposterDir.includes('requests') === false);517 });518 });519 });520 });...

Full Screen

Full Screen

imposterControllerTest.js

Source:imposterControllerTest.js Github

copy

Full Screen

...23 first = { port: 1, toJSON: mock().returns(Promise.resolve('firstJSON')) },24 second = { port: 2, toJSON: mock().returns(Promise.resolve('secondJSON')) },25 repo = ImpostersRepo.create(),26 controller = Controller.create({}, repo);27 await repo.add(imposterize(first));28 await repo.add(imposterize(second));29 await controller.get(Request.to('/imposters/2', { id: 2 }), response);30 assert.strictEqual(response.body, 'secondJSON');31 });32 it('should return replayable JSON for imposter at given id if replayable querystring set', async function () {33 const response = FakeResponse.create(),34 firstImposter = { port: 1, toJSON: mock().returns(Promise.resolve('firstJSON')) },35 second = { port: 2, toJSON: mock().returns(Promise.resolve('secondJSON')) },36 repo = ImpostersRepo.create(),37 controller = Controller.create({}, repo);38 await repo.add(imposterize(firstImposter));39 await repo.add(imposterize(second));40 await controller.get(Request.to('/imposters/2?replayable=true', { id: 2 }), response);41 assert.strictEqual(response.body, 'secondJSON');42 assert.ok(second.toJSON.wasCalledWith({ replayable: true, removeProxies: false }), second.toJSON.message());43 });44 it('should return removeProxies JSON for imposter at given id if removeProxies querystring set', async function () {45 const response = FakeResponse.create(),46 first = { port: 1, toJSON: mock().returns(Promise.resolve('firstJSON')) },47 second = { port: 2, toJSON: mock().returns(Promise.resolve('secondJSON')) },48 repo = ImpostersRepo.create(),49 controller = Controller.create({}, repo);50 await repo.add(imposterize(first));51 await repo.add(imposterize(second));52 await controller.get(Request.to('/imposters/2?removeProxies=true', { id: 2 }), response);53 assert.strictEqual(response.body, 'secondJSON');54 assert.ok(second.toJSON.wasCalledWith({ replayable: false, removeProxies: true }), second.toJSON.message());55 });56 it('should return replayable and removeProxies JSON for imposter at given id if both querystring values set', async function () {57 const response = FakeResponse.create(),58 first = { port: 1, toJSON: mock().returns(Promise.resolve('firstJSON')) },59 second = { port: 2, toJSON: mock().returns(Promise.resolve('secondJSON')) },60 repo = ImpostersRepo.create(),61 controller = Controller.create({}, repo);62 await repo.add(imposterize(first));63 await repo.add(imposterize(second));64 await controller.get(Request.to('/imposters/2?removeProxies=true&replayable=true', { id: 2 }), response);65 assert.strictEqual(response.body, 'secondJSON');66 assert.ok(second.toJSON.wasCalledWith({ replayable: true, removeProxies: true }), second.toJSON.message());67 });68 it('should return normal JSON for imposter at given id if both replayable and removeProxies querystrings are false', async function () {69 const response = FakeResponse.create(),70 first = { port: 1, toJSON: mock().returns(Promise.resolve('firstJSON')) },71 second = { port: 2, toJSON: mock().returns(Promise.resolve('secondJSON')) },72 repo = ImpostersRepo.create(),73 controller = Controller.create({}, repo);74 await repo.add(imposterize(first));75 await repo.add(imposterize(second));76 await controller.get(Request.to('/imposters/2?replayable=false&removeProxies=false', { id: 2 }), response);77 assert.strictEqual(response.body, 'secondJSON');78 assert.ok(second.toJSON.wasCalledWith({ replayable: false, removeProxies: false }), second.toJSON.message());79 });80 });81 describe('#del', function () {82 it('should stop the imposter', async function () {83 const response = FakeResponse.create(),84 imposter = {85 port: 1,86 stop: mock().returns(Promise.resolve(true)),87 toJSON: mock().returns(Promise.resolve('JSON'))88 },89 repo = ImpostersRepo.create(),90 controller = Controller.create({}, repo);91 await repo.add(imposterize(imposter));92 await controller.del(Request.to('/imposters/1', { id: 1 }), response);93 assert.ok(imposter.stop.wasCalled());94 });95 it('should remove the imposter from the list', async function () {96 const response = FakeResponse.create(),97 imposter = {98 port: 1,99 stop: mock().returns(Promise.resolve(true)),100 toJSON: mock().returns(Promise.resolve('JSON'))101 },102 repo = ImpostersRepo.create(),103 controller = Controller.create({}, repo);104 await repo.add(imposterize(imposter));105 await controller.del(Request.to('/imposters/1', { id: 1 }), response);106 const all = await repo.all();107 assert.deepEqual(all, []);108 });109 it('should send request even if no imposter exists', async function () {110 const response = FakeResponse.create(),111 repo = ImpostersRepo.create(),112 controller = Controller.create({}, repo);113 await controller.del(Request.to('/imposters/1', { id: 1 }), response);114 assert.deepEqual(response.body, {});115 });116 it('should return replayable JSON for imposter at given id if replayable querystring set', async function () {117 const response = FakeResponse.create(),118 imposter = {119 port: 1,120 stop: mock().returns(Promise.resolve(true)),121 toJSON: mock().returns(Promise.resolve('JSON'))122 },123 repo = ImpostersRepo.create(),124 controller = Controller.create({}, repo);125 await repo.add(imposterize(imposter));126 await controller.del(Request.to('/imposters/1?replayable=true', { id: 1 }), response);127 assert.ok(imposter.toJSON.wasCalledWith({ replayable: true, removeProxies: false }), imposter.toJSON.message());128 });129 it('should return removeProxies JSON for imposter at given id if removeProxies querystring set', async function () {130 const response = FakeResponse.create(),131 imposter = {132 port: 1,133 stop: mock().returns(Promise.resolve(true)),134 toJSON: mock().returns(Promise.resolve('JSON'))135 },136 repo = ImpostersRepo.create(),137 controller = Controller.create({}, repo);138 await repo.add(imposterize(imposter));139 await controller.del(Request.to('/imposters/1?removeProxies=true', { id: 1 }), response);140 assert.ok(imposter.toJSON.wasCalledWith({ replayable: false, removeProxies: true }), imposter.toJSON.message());141 });142 it('should return replayable and removeProxies JSON for imposter at given id if both querystring values set', async function () {143 const response = FakeResponse.create(),144 imposter = {145 port: 1,146 stop: mock().returns(Promise.resolve(true)),147 toJSON: mock().returns(Promise.resolve('JSON'))148 },149 repo = ImpostersRepo.create(),150 controller = Controller.create({}, repo);151 await repo.add(imposterize(imposter));152 await controller.del(Request.to('/imposters/1?removeProxies=true&replayable=true', { id: 1 }), response);153 assert.ok(imposter.toJSON.wasCalledWith({ replayable: true, removeProxies: true }), imposter.toJSON.message());154 });155 it('should send default JSON for the deleted the imposter if both replayable and removeProxies querystrings are missing', async function () {156 const response = FakeResponse.create(),157 imposter = {158 port: 1,159 stop: mock().returns(Promise.resolve(true)),160 toJSON: mock().returns(Promise.resolve('JSON'))161 },162 repo = ImpostersRepo.create(),163 controller = Controller.create({}, repo);164 await repo.add(imposterize(imposter));165 await controller.del(Request.to('/imposters/1', { id: 1 }), response);166 assert.ok(imposter.toJSON.wasCalledWith({ replayable: false, removeProxies: false }), imposter.toJSON.message());167 });168 });169 describe('#putStubs', function () {170 it('should return a 400 if no stubs element', async function () {171 const response = FakeResponse.create(),172 imposter = {173 port: 1,174 toJSON: mock().returns(Promise.resolve({})),175 overwriteStubs: mock()176 },177 logger = require('../fakes/fakeLogger').create(),178 repo = ImpostersRepo.create(),179 controller = Controller.create({}, repo, logger, false);180 await repo.add(imposterize(imposter));181 await controller.putStubs({ params: { id: 1 }, body: {} }, response);182 assert.strictEqual(response.statusCode, 400);183 assert.strictEqual(response.body.errors.length, 1);184 assert.strictEqual(response.body.errors[0].code, 'bad data');185 });186 it('should return a 400 if no stubs is not an array', async function () {187 const response = FakeResponse.create(),188 imposter = {189 port: 1,190 toJSON: mock().returns(Promise.resolve({})),191 overwriteStubs: mock()192 },193 repo = ImpostersRepo.create(),194 logger = require('../fakes/fakeLogger').create(),195 controller = Controller.create({}, repo, logger, false),196 request = {197 params: { id: 1 },198 body: { stubs: 1 }199 };200 await repo.add(imposterize(imposter));201 await controller.putStubs(request, response);202 assert.strictEqual(response.statusCode, 400);203 assert.strictEqual(response.body.errors.length, 1);204 assert.strictEqual(response.body.errors[0].code, 'bad data');205 });206 it('should return a 400 if no stub fails dry run validation', async function () {207 const response = FakeResponse.create(),208 imposter = {209 port: 1,210 protocol: 'test',211 creationRequest: { port: 1, protocol: 'test', stubs: [{}] },212 toJSON: mock().returns(Promise.resolve({ port: 1, protocol: 'test', stubs: [{}] }))213 },214 repo = ImpostersRepo.create(),215 Protocol = { testRequest: {} },216 logger = require('../fakes/fakeLogger').create(),217 controller = Controller.create({ test: Protocol }, repo, logger, false),218 request = {219 params: { id: 1 },220 body: { stubs: [{ responses: [{ invalid: 1 }] }] }221 };222 await repo.add(imposterize(imposter));223 await controller.putStubs(request, response);224 assert.strictEqual(response.statusCode, 400);225 assert.strictEqual(response.body.errors.length, 1);226 assert.strictEqual(response.body.errors[0].code, 'bad data');227 });228 it('should return a 400 if trying to add injection without --allowInjection set', async function () {229 const response = FakeResponse.create(),230 imposter = {231 port: 1,232 protocol: 'test',233 toJSON: mock().returns(Promise.resolve({ protocol: 'test' }))234 },235 repo = ImpostersRepo.create(),236 Protocol = { testRequest: {} },237 logger = require('../fakes/fakeLogger').create(),238 controller = Controller.create({ test: Protocol }, repo, logger, false),239 request = {240 params: { id: 1 },241 body: { stubs: [{ responses: [{ inject: '() => {}' }] }] }242 };243 await repo.add(imposterize(imposter));244 await controller.putStubs(request, response);245 assert.strictEqual(response.statusCode, 400);246 assert.strictEqual(response.body.errors.length, 1);247 assert.strictEqual(response.body.errors[0].code, 'invalid injection');248 });249 });250 describe('#putStub', function () {251 it('should return a 404 if stubIndex is not an integer', async function () {252 const response = FakeResponse.create(),253 imposter = {254 port: 1,255 protocol: 'test',256 stubsJSON: mock().returns(Promise.resolve([]))257 },258 repo = ImpostersRepo.create(),259 Protocol = { testRequest: {} },260 logger = require('../fakes/fakeLogger').create(),261 controller = Controller.create({ test: Protocol }, repo, logger, false),262 request = {263 params: { id: 1, stubIndex: 'test' },264 body: { stubs: [{ responses: [{ is: 'response' }] }] }265 };266 await repo.add(imposterize(imposter));267 await controller.putStub(request, response);268 assert.strictEqual(response.statusCode, 404);269 assert.strictEqual(response.body.errors.length, 1);270 assert.deepEqual(response.body.errors[0], {271 code: 'bad data',272 message: "'stubIndex' must be a valid integer, representing the array index position of the stub to replace"273 });274 });275 it('should return a 404 if stubIndex is less than 0', async function () {276 const response = FakeResponse.create(),277 imposter = {278 port: 1,279 protocol: 'test',280 stubsJSON: mock().returns(Promise.resolve([]))281 },282 repo = ImpostersRepo.create(),283 Protocol = { testRequest: {} },284 logger = require('../fakes/fakeLogger').create(),285 controller = Controller.create({ test: Protocol }, repo, logger, false),286 request = {287 params: { id: 1, stubIndex: -1 },288 body: { stubs: [{ responses: [{ is: 'response' }] }] }289 };290 await repo.add(imposterize(imposter));291 await controller.putStub(request, response);292 assert.strictEqual(response.statusCode, 404);293 assert.strictEqual(response.body.errors.length, 1);294 assert.deepEqual(response.body.errors[0], {295 code: 'bad data',296 message: "'stubIndex' must be a valid integer, representing the array index position of the stub to replace"297 });298 });299 it('should return a 404 if stubIndex is greater then highest index of stubs array', async function () {300 const response = FakeResponse.create(),301 imposter = {302 port: 1,303 protocol: 'test',304 stubsJSON: mock().returns(Promise.resolve([0, 1, 2]))305 },306 repo = ImpostersRepo.create(),307 Protocol = { testRequest: {} },308 logger = require('../fakes/fakeLogger').create(),309 controller = Controller.create({ test: Protocol }, repo, logger, false),310 request = {311 params: { id: 1, stubIndex: 3 },312 body: { stubs: [{ responses: [{ is: 'response' }] }] }313 };314 await repo.add(imposterize(imposter));315 await controller.putStub(request, response);316 assert.strictEqual(response.statusCode, 404);317 assert.strictEqual(response.body.errors.length, 1);318 assert.deepEqual(response.body.errors[0], {319 code: 'bad data',320 message: "'stubIndex' must be a valid integer, representing the array index position of the stub to replace"321 });322 });323 it('should return a 400 if no stub fails dry run validation', async function () {324 const response = FakeResponse.create(),325 imposter = {326 port: 1,327 protocol: 'test',328 toJSON: mock().returns(Promise.resolve({ protocol: 'test' })),329 creationRequest: { port: 1, protocol: 'test', stubs: [{}] }330 },331 repo = ImpostersRepo.create(),332 Protocol = { testRequest: {} },333 logger = require('../fakes/fakeLogger').create(),334 controller = Controller.create({ test: Protocol }, repo, logger, false),335 request = {336 params: { id: 1, stubIndex: 0 },337 body: { responses: [{ INVALID: 'response' }] }338 };339 await repo.add(imposter);340 await controller.putStub(request, response);341 assert.strictEqual(response.statusCode, 400);342 assert.strictEqual(response.body.errors.length, 1);343 assert.deepEqual(response.body.errors[0], {344 code: 'bad data',345 message: 'unrecognized response type',346 source: { INVALID: 'response' }347 });348 });349 it('should return a 400 if no adding inject without --allowInjection', async function () {350 const response = FakeResponse.create(),351 imposter = {352 port: 1,353 protocol: 'test',354 toJSON: mock().returns(Promise.resolve({ protocol: 'test' })),355 creationRequest: { port: 1, protocol: 'test', stubs: [{}] }356 },357 repo = ImpostersRepo.create(),358 Protocol = { testRequest: {} },359 logger = require('../fakes/fakeLogger').create(),360 controller = Controller.create({ test: Protocol }, repo, logger, false),361 request = {362 params: { id: 1, stubIndex: 0 },363 body: { responses: [{ inject: '() => {}' }] }364 };365 await repo.add(imposter);366 await controller.putStub(request, response);367 assert.strictEqual(response.statusCode, 400);368 assert.strictEqual(response.body.errors.length, 1);369 assert.deepEqual(response.body.errors[0], {370 code: 'invalid injection',371 message: 'JavaScript injection is not allowed unless mb is run with the --allowInjection flag',372 source: { responses: [{ inject: '() => {}' }] }373 });374 });375 });376 describe('#deleteStub', function () {377 it('should return a 404 if stubIndex is greater then highest index of stubs array', async function () {378 const response = FakeResponse.create(),379 imposter = {380 port: 1,381 protocol: 'test',382 stubsJSON: mock().returns(Promise.resolve([0, 1, 2]))383 },384 repo = ImpostersRepo.create(),385 Protocol = { testRequest: {} },386 logger = require('../fakes/fakeLogger').create(),387 controller = Controller.create({ test: Protocol }, repo, logger, false),388 request = {389 params: { id: 1, stubIndex: 3 },390 body: { stubs: [{ responses: [{ is: 'response' }] }] }391 };392 await repo.add(imposterize(imposter));393 await controller.deleteStub(request, response);394 assert.strictEqual(response.statusCode, 404);395 assert.strictEqual(response.body.errors.length, 1);396 assert.deepEqual(response.body.errors[0], {397 code: 'bad data',398 message: "'stubIndex' must be a valid integer, representing the array index position of the stub to replace"399 });400 });401 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var imposter = mb.create({3 {4 {5 is: {6 }7 }8 }9});10imposter.then(function (imposter) {11 console.log('The imposter is running at ' + imposter.url);12});13var mb = require('mountebank');14var imposter = mb.imposterize({15 {16 {17 is: {18 }19 }20 }21});22imposter.then(function (imposter) {23 console.log('The imposter is running at ' + imposter.url);24});25var mb = require('mountebank');26var imposter = mb.imposterize({27 {28 {29 is: {30 }31 }32 }33});34imposter.then(function (imposter) {35 console.log('The imposter is running at ' + imposter.url);36});

Full Screen

Using AI Code Generation

copy

Full Screen

1const imposterize = require('imposterize');2const imposter = imposterize({3 {4 {5 equals: {6 }7 }8 {9 is: {10 headers: {11 },12 }13 }14 }15});16imposter.start().then(() => {17 console.log('imposter started');18});19const request = require('superagent');20 .end((err, res) => {21 console.log(res.text);22 });23const assert = require('chai').assert;24describe('Test', () => {25 it('should return Hello World', () => {26 assert.equal('Hello World', 'Hello World');27 });28});291 passing (20ms)

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2var imposterize = mb.imposterize;3var imposter = imposterize({port: 3000});4imposter.post('/test', function (req, res) {5 res.send({hello: 'world'});6});7imposter.start();8var mb = require('mountebank');9var imposterize = mb.imposterize;10var imposter = imposterize({port: 3000});11imposter.get('/test', function (req, res) {12 res.send({hello: 'world'});13});14imposter.start();15var mb = require('mountebank');16var imposterize = mb.imposterize;17var imposter = imposterize({port: 3000});18imposter.get('/test', function (req, res) {19 res.send({hello: 'world'});20});21imposter.start();22var mb = require('mountebank');23var imposterize = mb.imposterize;24var imposter = imposterize({port: 3000});25imposter.get('/test', function (req, res) {26 res.send({hello: 'world'});27});28imposter.start();29var mb = require('mountebank');30var imposterize = mb.imposterize;31var imposter = imposterize({port: 3000});32imposter.get('/test', function (req, res) {33 res.send({hello: 'world'});34});35imposter.start();36var mb = require('mountebank');37var imposterize = mb.imposterize;38var imposter = imposterize({port: 3000});39imposter.get('/test', function (req, res) {40 res.send({hello: 'world'});41});42imposter.start();43var mb = require('mountebank');

Full Screen

Using AI Code Generation

copy

Full Screen

1var imposterize = require('imposterize');2var request = {3 {4 {5 "is": {6 "headers": {7 },8 "body": {9 }10 }11 }12 }13};14imposter.create(request).then(function (response) {15 console.log(response);16}).catch(function (err) {17 console.log(err);18});19imposter.delete(3000).then(function (response) {20 console.log(response);21}).catch(function (err) {22 console.log(err);23});24imposter.get(3000).then(function (response) {25 console.log(response);26}).catch(function (err) {27 console.log(err);28});29imposter.getAll().then(function (response) {30 console.log(response);31}).catch(function (err) {32 console.log(err);33});34imposter.update(3000, request).then(function (response) {35 console.log(response);36}).catch(function (err) {37 console.log(err);38});39imposter.addStub(3000, {40 {41 "is": {42 "headers": {43 },44 "body": {45 }46 }47 }48}).then(function (response) {49 console.log(response);50}).catch(function (err) {51 console.log(err);52});53imposter.deleteStub(3000, 0).then(function (response) {54 console.log(response);55}).catch(function (err) {56 console.log(err);57});58imposter.updateStub(3000, 0, {59 {60 "is": {61 "headers": {62 },63 "body": {64 }65 }66 }67}).then(function (response) {68 console.log(response);69}).catch(function (err) {

Full Screen

Using AI Code Generation

copy

Full Screen

1var mb = require('mountebank');2mb.create({3 stubs: [{4 predicates: [{5 equals: {6 }7 }],8 responses: [{9 is: {10 headers: {11 },12 }13 }]14 }]15}, function (error, imposter) {16 if (error) {17 console.error('Failed to create imposter', error);18 process.exit(1);19 }20});21var mb = require('mountebank');22mb.create({23 stubs: [{24 predicates: [{25 equals: {26 }27 }],28 responses: [{29 is: {30 headers: {31 },32 }33 }]34 }]35}, function (error, imposter) {36 if (error) {37 console.error('Failed to create imposter', error);38 process.exit(1);39 }40});

Full Screen

Using AI Code Generation

copy

Full Screen

1var imposterize = require('imposterize');2var server = imposterize.create({3});4server.get('/hello-world', function (req, res) {5 res.send('Hello world!');6});7server.listen();8var imposterize = require('imposterize');9var server = imposterize.create({10});11server.get('/hello-world', function (req, res) {12 res.send('Hello world!');13});14server.listen();15var imposterize = require('imposterize');16var server = imposterize.create({17});18server.get('/hello-world', function (req, res) {19 res.send('Hello world!');20});21server.listen();22var imposterize = require('imposterize');23var server = imposterize.create({24});25server.get('/hello-world', function (req, res) {26 res.send('Hello world!');27});28server.listen();29var imposterize = require('imposterize');30var server = imposterize.create({31});32server.get('/hello-world', function (req, res) {33 res.send('Hello world!');34});35server.listen();36var imposterize = require('imposterize');37var server = imposterize.create({38});39server.get('/hello-world', function (req, res) {40 res.send('Hello world!');41});42server.listen();43var imposterize = require('imposterize');44var server = imposterize.create({45});46server.get('/hello-world', function (req

Full Screen

Using AI Code Generation

copy

Full Screen

1var imposterize = require('imposterize');2var imposterize = require('imposterize');3var imposter = imposterize.createImposter(3000);4imposter.addRoute({5 'response': {6 }7});8imposter.start();9var imposterize = require('imposterize');10var imposter = imposterize.createImposter(3000);11imposter.addRoute({12 'response': {13 }14});15imposter.start();16var imposterize = require('imposterize');17var imposter = imposterize.createImposter(3000);18imposter.addRoute({19 'response': {20 }21});22imposter.start();23var imposterize = require('imposterize');24var imposter = imposterize.createImposter(3000);25imposter.addRoute({26 'response': {27 }28});29imposter.start();30var imposterize = require('imposterize');31var imposter = imposterize.createImposter(3000);32imposter.addRoute({33 'response': {34 }35});36imposter.start();37var imposterize = require('imposterize');38var imposter = imposterize.createImposter(3000);39imposter.addRoute({40 'response': {41 }42});

Full Screen

Using AI Code Generation

copy

Full Screen

1var imposterize = require('imposterize');2var stub = new imposterize.Stub();3stub.addPredicate("equals", {method: "POST", path: "/api/v1/endpoint"});4stub.addResponse("is", {statusCode: 200, headers: { "Content-Type": "application/json" }, body: {"message": "Hello World"}});5var imposter = new imposterize.Imposter(2525, "http");6imposter.addStub(stub);7var server = new imposterize.Server();8server.addImposter(imposter);9server.start(function (err) {10 if (err) {11 console.log(err);12 } else {13 console.log("Server started");14 }15});16server.stop(function (err) {17 if (err) {18 console.log(err);19 } else {20 console.log("Server stopped");21 }22});23imposter.delete(function (err) {24 if (err) {25 console.log(err);26 } else {27 console.log("Imposter deleted");28 }29});30var client = new imposterize.Client(2525);31client.post("/api/v1/endpoint", function (err, response) {32 if (err) {33 console.log(err);34 } else {35 console.log(response.body);36 }37});38var client = new imposterize.Client(2525, "localhost");39client.post("/api/v1/endpoint", function (err, response) {40 if (err) {41 console.log(err);42 } else {43 console.log(response.body);44 }45});46var client = new imposterize.Client(2525, "localhost", "https");47client.post("/api/v1/endpoint", function (err, response) {48 if (err) {49 console.log(err);50 } else {51 console.log(response.body);52 }53});54var client = new imposterize.Client(2525, "localhost", "https");55client.post("/api/v1/endpoint", function (err,

Full Screen

Using AI Code Generation

copy

Full Screen

1var imposterize = require('imposterize');2imposterize({3 {4 {5 equals: {6 }7 }8 {9 is: {10 }11 }12 }13});14var mb = require('mountebank-client')({port: 2525});15mb.post('/imposters', {16})17 .then(function (response) {18 console.log('Imposter created');19 })20 .catch(function (error) {21 console.log(error);22 });23var request = require('supertest');24var app = require('../app');25describe('GET /test', function() {26 it('responds with Hello World', function(done) {27 request(app)28 .get('/test')29 .expect(200, 'Hello World', done);30 });31});32var request = require('supertest-as-promised');33var app = require('../app');34describe('GET /test', function() {35 it('responds with Hello World', function() {36 return request(app)37 .get('/test')38 .expect(200, 'Hello World');39 });40});41var request = require('supertest-as-promised');42var app = require('../app');43var mb = require('mountebank-client')

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