1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 | 1 1 27 1 170 170 1 183 178 183 183 1 164 164 164 164 164 1 183 183 1 1 1 1 1 1 1 182 3 3 182 182 182 182 31 31 182 1 1 182 1 1 182 30 30 146 146 182 179 21 21 21 17 21 19 21 1 182 182 182 1 7 7 7 7 183 13 2 11 1 202 3 199 199 3 199 199 5 199 14 2 12 199 1 1 1 15 3 12 12 11 1 1 198 198 1 197 197 2 195 195 197 197 197 197 183 183 1 197 1 203 203 3 203 13 203 12 191 191 1 1 175 2 2 175 164 1 7 7 1 1 1 1 1 1 1 1 5 5 5 1 1 1 1 1 1 1 4 4 1 5 5 1 2 2 183 183 1 126 1 33 1 4 1 1 1 1 1 1 1 94 1 112 111 111 98 13 13 13 13 14 14 2 13 1 13 1 90 1 8 8 6 8 8 8 2 2 1 3 3 3 1 5 5 5 1 3 3 1 1 1 1 1 2 2 1 175 1 1 1 1 1 1 170 170 1 26 26 1 4 4 1 1 18 1 1 1 17 17 1 18 1 1 1 17 1 10 10 9 1 11 11 18 18 18 18 18 6 12 18 18 18 18 18 2 18 18 11 1 1 1 1 1 1 1 1 1 1 | /* jshint strict:false */ /** * @module nock/scope */ var fs = require('fs') , globalIntercept = require('./intercept') , mixin = require('./mixin') , matchBody = require('./match_body') , common = require('./common') , assert = require('assert') , url = require('url') , _ = require('lodash') , debug = require('debug')('nock.scope'); function isStream(obj) { return (typeof obj !== 'undefined') && (typeof a !== 'string') && (! Buffer.isBuffer(obj)) && (typeof obj.setEncoding === 'function'); } function startScope(basePath, options) { var interceptors = {}, scope, transformPathFunction, transformRequestBodyFunction, matchHeaders = [], logger = debug, scopeOptions = options || {}, urlParts = url.parse(basePath), port = urlParts.port || ((urlParts.protocol === 'http:') ? 80 : 443), persist = false, contentLen = false, date = null, basePathname = urlParts.pathname.replace(/\/$/, ''); basePath = urlParts.protocol + '//' + urlParts.hostname + ':' + port; function add(key, interceptor, scope) { if (! interceptors.hasOwnProperty(key)) { interceptors[key] = []; } interceptors[key].push(interceptor); globalIntercept(basePath, interceptor, scope, scopeOptions, urlParts.hostname); } function remove(key, interceptor) { Iif (persist) { return; } var arr = interceptors[key]; Eif (arr) { arr.splice(arr.indexOf(interceptor), 1); if (arr.length === 0) { delete interceptors[key]; } } } function intercept(uri, method, requestBody, interceptorOptions) { var interceptorMatchHeaders = []; var key = method.toUpperCase() + ' ' + basePath + basePathname + uri; function replyWithError(errorMessage){ this.errorMessage = errorMessage; this.options = interceptorOptions || {}; for(var opt in scopeOptions) { if(typeof this.options[opt] === 'undefined') { this.options[opt] = scopeOptions[opt]; } } add(key, this, scope, scopeOptions); return scope; } function reply(statusCode, body, headers) { if (arguments.length <= 2 && typeof statusCode === 'function') { body = statusCode; statusCode = 200; } this.statusCode = statusCode; // We use lower-case headers throught Nock. headers = common.headersFieldNamesToLowerCase(headers); this.options = interceptorOptions || {}; for(var opt in scopeOptions) { Eif(typeof this.options[opt] === 'undefined') { this.options[opt] = scopeOptions[opt]; } } if (scope._defaultReplyHeaders) { headers = headers || {}; headers = mixin(scope._defaultReplyHeaders, headers); } if (date) { headers = headers || {}; headers['date'] = date.toUTCString(); } if (headers !== undefined) { this.headers = {}; // makes sure all keys in headers are in lower case for (var key2 in headers) { Eif (headers.hasOwnProperty(key2)) { this.headers[key2.toLowerCase()] = headers[key2]; } } } // If the content is not encoded we may need to transform the response body. // Otherwise we leave it as it is. if(!common.isContentEncoded(headers)) { if (body && typeof(body) !== 'string' && typeof(body) !== 'function' && !Buffer.isBuffer(body) && !isStream(body)) { try { body = JSON.stringify(body); if (!this.headers) { this.headers = {}; } if (!this.headers['content-type']) { this.headers['content-type'] = 'application/json'; } if (contentLen) { this.headers['content-length'] = body.length; } } catch(err) { throw new Error('Error encoding response body into JSON'); } } } this.body = body; add(key, this, scope, scopeOptions); return scope; } function replyWithFile(statusCode, filePath, headers) { var readStream = fs.createReadStream(filePath); readStream.pause(); this.filePath = filePath; return reply.call(this, statusCode, readStream, headers); } var matchStringOrRegexp = function(target, pattern) { if (pattern instanceof RegExp) { return target.toString().match(pattern); } else { return target === pattern; } }; function match(options, body, hostNameOnly) { if (hostNameOnly) { return options.hostname === urlParts.hostname; } var method = options.method || 'GET' , path = options.path , matches , proto = options.proto; if (transformPathFunction) { path = transformPathFunction(path); } Iif (typeof(body) !== 'string') { body = body.toString(); } if (transformRequestBodyFunction) { body = transformRequestBodyFunction(body); } var checkHeaders = function(header) { if (typeof header.value === 'function') { return header.value(options.getHeader(header.name)); } return matchStringOrRegexp(options.getHeader(header.name), header.value); }; if (!matchHeaders.every(checkHeaders) || !interceptorMatchHeaders.every(checkHeaders)) { logger('headers don\'t match'); return false; } // Also match request headers // https://github.com/pgte/nock/issues/163 function reqheaderMatches(key) { // We don't try to match request headers if these weren't even specified in the request. if(! options.headers) { return true; } // We skip 'host' header comparison unless it's available in both mock and actual request. // This because 'host' may get inserted by Nock itself and then get recorder. // NOTE: We use lower-case header field names throught Nock. Iif(key === 'host' && (_.isUndefined(options.headers[key]) || _.isUndefined(this.reqheaders[key]))) { return true; } if(options.headers[key] === this.reqheaders[key]) { return true; } debug('request header field doesn\'t match:', key, options.headers[key], this.reqheaders[key]); return false; } var reqHeadersMatch = ! this.reqheaders || Object.keys(this.reqheaders).every(reqheaderMatches.bind(this)); if (!reqHeadersMatch) { return false; } var matchKey = method.toUpperCase() + ' '; // If we have a filtered scope then we use it instead reconstructing // the scope from the request options (proto, host and port) as these // two won't necessarily match and we have to remove the scope that was // matched (vs. that was defined). if(this.__nock_filteredScope) { matchKey += this.__nock_filteredScope; } else { matchKey += proto + '://' + options.host; Iif ( options.port && options.host.indexOf(':') < 0 && (options.port !== 80 || options.proto !== 'http') && (options.port !== 443 || options.proto !== 'https') ) { matchKey += ":" + options.port; } } matchKey += path; matches = matchKey === this._key; logger('matching ' + matchKey + ' to ' + this._key + ': ' + matches); if (matches) { matches = (matchBody.call(options, this._requestBody, body)); if(!matches) { logger('bodies don\'t match'); } } return matches; } function matchIndependentOfBody(options) { var method = options.method || 'GET' , path = options.path , proto = options.proto; if (transformPathFunction) { path = transformPathFunction(path); } var checkHeaders = function(header) { return options.getHeader && matchStringOrRegexp(options.getHeader(header.name), header.value); }; if (!matchHeaders.every(checkHeaders) || !interceptorMatchHeaders.every(checkHeaders)) { return false; } var matchKey = method + ' ' + proto + '://' + options.host + path; return this._key === matchKey; } function filteringPath() { if (typeof arguments[0] === 'function') { this.transformFunction = arguments[0]; } return this; } function discard() { if ((persist || this.counter > 0) && this.filePath) { this.body = fs.createReadStream(this.filePath); this.body.pause(); } if (!persist && this.counter < 1) { remove(this._key, this); } } function matchHeader(name, value) { interceptorMatchHeaders.push({ name: name, value: value }); return this; } function basicAuth(options) { var username = options['user']; var password = options['pass']; var name = 'authorization'; var value = 'Basic ' + new Buffer(username + ':' + password).toString('base64'); interceptorMatchHeaders.push({ name: name, value: value }); return this; } /** * Set number of times will repeat the interceptor * @name times * @param Integer Number of times to repeat (should be > 0) * @public * @example * // Will repeat mock 5 times for same king of request * nock('http://zombo.com).get('/').times(5).reply(200, 'Ok'); */ function times(newCounter) { Iif (newCounter < 1) { return this; } this.counter = newCounter; return this; } /** * An sugar sintaxe for times(1) * @name once * @see {@link times} * @public * @example * nock('http://zombo.com).get('/').once.reply(200, 'Ok'); */ function once() { return this.times(1); } /** * An sugar sintaxe for times(2) * @name twixe * @see {@link times} * @public * @example * nock('http://zombo.com).get('/').twice.reply(200, 'Ok'); */ function twice() { return this.times(2); } /** * An sugar sintaxe for times(3). * @name thrice * @see {@link times} * @public * @example * nock('http://zombo.com).get('/').thrice.reply(200, 'Ok'); */ function thrice() { return this.times(3); } /** * Delay the response by a certain number of ms. * * @param {integer} ms - Number of milliseconds to wait * @return {scope} - the current scope for chaining */ function delay(ms) { this.delayInMs = ms; return this; } /** * Delay the connection by a certain number of ms. * * @param {integer} ms - Number of milliseconds to wait * @return {scope} - the current scope for chaining */ function delayConnection(ms) { this.delayConnectionInMs = ms; return this; } /** * Make the socket idle for a certain number of ms (simulated). * * @param {integer} ms - Number of milliseconds to wait * @return {scope} - the current scope for chaining */ function socketDelay(ms) { this.socketDelayInMs = ms; return this; } var interceptor = { _key: key , counter: 1 , _requestBody: requestBody // We use lower-case header field names throught Nock. , reqheaders: common.headersFieldNamesToLowerCase((options && options.reqheaders) || {}) , reply: reply , replyWithError: replyWithError , replyWithFile: replyWithFile , discard: discard , match: match , matchIndependentOfBody: matchIndependentOfBody , filteringPath: filteringPath , matchHeader: matchHeader , basicAuth: basicAuth , times: times , once: once , twice: twice , thrice: thrice , delay: delay , delayConnection: delayConnection , socketDelay: socketDelay }; return interceptor; } function get(uri, requestBody, options) { return intercept(uri, 'GET', requestBody, options); } function post(uri, requestBody, options) { return intercept(uri, 'POST', requestBody, options); } function put(uri, requestBody, options) { return intercept(uri, 'PUT', requestBody, options); } function head(uri, requestBody, options) { return intercept(uri, 'HEAD', requestBody, options); } function patch(uri, requestBody, options) { return intercept(uri, 'PATCH', requestBody, options); } function merge(uri, requestBody, options) { return intercept(uri, 'MERGE', requestBody, options); } function _delete(uri, requestBody, options) { return intercept(uri, 'DELETE', requestBody, options); } function pendingMocks() { return Object.keys(interceptors); } function isDone() { // if nock is turned off, it always says it's done if (! globalIntercept.isOn()) { return true; } var keys = Object.keys(interceptors); if (keys.length === 0) { return true; } else { var doneHostCount = 0; keys.forEach(function(key) { var doneInterceptorCount = 0; interceptors[key].forEach(function(interceptor) { var isDefined = (typeof interceptor.options.requireDone !== 'undefined'); if (isDefined && interceptor.options.requireDone === false) { doneInterceptorCount += 1; } }); if( doneInterceptorCount === interceptors[key].length ) { doneHostCount += 1; } }); return (doneHostCount === keys.length); } } function done() { assert.ok(isDone(), "Mocks not yet satisfied:\n" + pendingMocks().join("\n")); } function buildFilter() { var filteringArguments = arguments; if (arguments[0] instanceof RegExp) { return function(path) { Eif (path) { path = path.replace(filteringArguments[0], filteringArguments[1]); } return path; }; } else Eif (typeof (arguments[0]) === 'function') { return arguments[0]; } } function filteringPath() { transformPathFunction = buildFilter.apply(undefined, arguments); Iif (!transformPathFunction) { throw new Error('Invalid arguments: filtering path should be a function or a regular expression'); } return this; } function filteringRequestBody() { transformRequestBodyFunction = buildFilter.apply(undefined, arguments); Iif (!transformRequestBodyFunction) { throw new Error('Invalid arguments: filtering request body should be a function or a regular expression'); } return this; } function matchHeader(name, value) { // We use lower-case header field names throught Nock. matchHeaders.push({ name: name.toLowerCase(), value: value }); return this; } function defaultReplyHeaders(headers) { this._defaultReplyHeaders = common.headersFieldNamesToLowerCase(headers); return this; } function log(newLogger) { logger = newLogger; return this; } function _persist() { persist = true; return this; } function shouldPersist() { return persist; } function replyContentLength() { contentLen = true; return this; } function replyDate(d) { date = d || new Date(); return this; } scope = { get: get , post: post , delete: _delete , put: put , merge: merge , patch: patch , head: head , intercept: intercept , done: done , isDone: isDone , filteringPath: filteringPath , filteringRequestBody: filteringRequestBody , matchHeader: matchHeader , defaultReplyHeaders: defaultReplyHeaders , log: log , persist: _persist , shouldPersist: shouldPersist , pendingMocks: pendingMocks , replyContentLength: replyContentLength , replyDate: replyDate }; return scope; } function cleanAll() { globalIntercept.removeAll(); return module.exports; } function loadDefs(path) { var contents = fs.readFileSync(path); return JSON.parse(contents); } function load(path) { return define(loadDefs(path)); } function getStatusFromDefinition(nockDef) { // Backward compatibility for when `status` was encoded as string in `reply`. if(!_.isUndefined(nockDef.reply)) { // Try parsing `reply` property. var parsedReply = parseInt(nockDef.reply, 10); Eif(_.isNumber(parsedReply)) { return parsedReply; } } var DEFAULT_STATUS_OK = 200; return nockDef.status || DEFAULT_STATUS_OK; } function getScopeFromDefinition(nockDef) { // Backward compatibility for when `port` was part of definition. if(!_.isUndefined(nockDef.port)) { // Include `port` into scope if it doesn't exist. var options = url.parse(nockDef.scope); Eif(_.isNull(options.port)) { return nockDef.scope + ':' + nockDef.port; } else { if(parseInt(options.port) !== parseInt(nockDef.port)) { throw new Error('Mismatched port numbers in scope and port properties of nock definition.'); } } } return nockDef.scope; } function tryJsonParse(string) { try { return JSON.parse(string); } catch(err) { return string; } } function define(nockDefs) { var nocks = []; nockDefs.forEach(function(nockDef) { var nscope = getScopeFromDefinition(nockDef) , npath = nockDef.path , method = nockDef.method.toLowerCase() || "get" , status = getStatusFromDefinition(nockDef) , headers = nockDef.headers || {} , reqheaders = nockDef.reqheaders || {} , body = nockDef.body || '' , options = nockDef.options || {}; // We use request headers for both filtering (see below) and mocking. // Here we are setting up mocked request headers but we don't want to // be changing the user's options object so we clone it first. options = _.clone(options) || {}; options.reqheaders = reqheaders; // Response is not always JSON as it could be a string or binary data or // even an array of binary buffers (e.g. when content is enconded) var response; if(!nockDef.response) { response = ''; } else { response = _.isString(nockDef.response) ? tryJsonParse(nockDef.response) : nockDef.response; } var nock; Iif(body==="*") { nock = startScope(nscope, options).filteringRequestBody(function() { return "*"; })[method](npath, "*").reply(status, response, headers); } else { nock = startScope(nscope, options); // If request headers were specified filter by them. Eif(reqheaders !== {}) { for (var k in reqheaders) { nock.matchHeader(k, reqheaders[k]); } } nock.intercept(npath, method, body).reply(status, response, headers); } nocks.push(nock); }); return nocks; } module.exports = startScope; module.exports.cleanAll = cleanAll; module.exports.activate = globalIntercept.activate; module.exports.isActive = globalIntercept.isActive; module.exports.removeInterceptor = globalIntercept.removeInterceptor; module.exports.disableNetConnect = globalIntercept.disableNetConnect; module.exports.enableNetConnect = globalIntercept.enableNetConnect; module.exports.load = load; module.exports.loadDefs = loadDefs; module.exports.define = define; |