Code coverage report for nock/lib/intercept.js

Statements: 95.14% (176 / 185)      Branches: 83.87% (78 / 93)      Functions: 96.43% (27 / 28)      Lines: 95.03% (172 / 181)      Ignored: none     

All files » nock/lib/ » intercept.js
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            1                                             1 8   8 8   8     1   1                                 1 29 1 28 1   27       1 24   24 24 24                   1 21     1 607     1 635     1 230 119   230     230 230   230 230   230     1 212 4     208 208 7     201           201 195 205 205 195 195             1 28     1 486     486   486   486   486     486 5519 1616       1616 4       4 4   4       5519 455   455         5064     486     1 2   2   2 2   2 1 1 1   1 1 1 1             1     1       1   1 8 8 8       1 1     1 31   31             1 227     227   227 227     227 227 14755 7264                                 31 31             31 31   31     1 91     91 61   30 30   30       1       8       1 2 2 1         1 2 2 1     2       1   32 1     31       31   259     259 49   259   259   259 231     231 268 268     231 6 4 4 4 4   2   6 6         225   225 225 140   225   28 28 20   8 8             1   1 1 1 1 1 1 1 1 1 1 1 1  
'use strict';
 
/**
 * @module nock/intercepts
 */
 
var RequestOverrider = require('./request_overrider'),
    common           = require('./common'),
    url              = require('url'),
    inherits         = require('util').inherits,
    http             = require('http'),
    parse            = require('url').parse,
    _                = require('lodash'),
    debug            = require('debug')('nock.intercept'),
    timers           = require('timers'),
    EventEmitter     = require('events').EventEmitter,
    globalEmitter    = require('./global_emitter');
 
 
/**
 * @name NetConnectNotAllowedError
 * @private
 * @desc Error trying to make a connection when disabled external access.
 * @class
 * @example
 * nock.disableNetConnect();
 * http.get('http://zombo.com');
 * // throw NetConnectNotAllowedError
 */
function NetConnectNotAllowedError(host, path) {
  Error.call(this);
 
  this.name    = 'NetConnectNotAllowedError';
  this.message = 'Nock: Not allow net connect for "' + host + path + '"';
 
  Error.captureStackTrace(this, this.constructor);
}
 
inherits(NetConnectNotAllowedError, Error);
 
var allInterceptors = {},
    allowNetConnect;
 
/**
 * Enabled real request.
 * @public
 * @param {String|RegExp} matcher=RegExp.new('.*') Expression to match
 * @example
 * // Enables all real requests
 * nock.enableNetConnect();
 * @example
 * // Enables real requests for url that matches google
 * nock.enableNetConnect('google');
 * @example
 * // Enables real requests for url that matches google and amazon
 * nock.enableNetConnect(/(google|amazon)/);
 */
function enableNetConnect(matcher) {
  if (_.isString(matcher)) {
    allowNetConnect = new RegExp(matcher);
  } else if (_.isObject(matcher) && _.isFunction(matcher.test)) {
    allowNetConnect = matcher;
  } else {
    allowNetConnect = /.*/;
  }
}
 
function isEnabledForNetConnect(options) {
  common.normalizeRequestOptions(options);
 
  var enabled = allowNetConnect && allowNetConnect.test(options.host);
  debug('Net connect', enabled ? '' : 'not', 'enabled for', options.host);
  return enabled;
}
 
/**
 * Disable all real requests.
 * @public
 * @param {String|RegExp} matcher=RegExp.new('.*') Expression to match
 * @example
 * nock.disableNetConnect();
*/
function disableNetConnect() {
  allowNetConnect = undefined;
}
 
function isOn() {
  return !isOff();
}
 
function isOff() {
  return process.env.NOCK_OFF === 'true';
}
 
function add(key, interceptor, scope, scopeOptions, host) {
  if (! allInterceptors.hasOwnProperty(key)) {
    allInterceptors[key] = { key: key, scopes: [] };
  }
  interceptor.__nock_scope = scope;
 
  //  We need scope's key and scope options for scope filtering function (if defined)
  interceptor.__nock_scopeKey = key;
  interceptor.__nock_scopeOptions = scopeOptions;
  //  We need scope's host for setting correct request headers for filtered scopes.
  interceptor.__nock_scopeHost = host;
  interceptor.interceptionCounter = 0;
 
  allInterceptors[key].scopes.push(interceptor);
}
 
function remove(interceptor) {
  if (interceptor.__nock_scope.shouldPersist()) {
    return;
  }
 
  interceptor.counter -= 1;
  if (interceptor.counter > 0) {
    return;
  }
 
  var key          = interceptor._key.split(' '),
      u            = url.parse(key[1]),
      hostKey      = u.protocol + '//' + u.host,
      interceptors = allInterceptors[hostKey] && allInterceptors[hostKey].scopes,
      thisInterceptor;
 
  if (interceptors) {
    for(var i = 0; i < interceptors.length; i++) {
      thisInterceptor = interceptors[i];
      if (thisInterceptor === interceptor) {
        interceptors.splice(i, 1);
        break;
      }
    }
 
  }
}
 
function removeAll() {
  allInterceptors = {};
}
 
function interceptorsFor(options) {
  var basePath,
      matchingInterceptor;
 
  common.normalizeRequestOptions(options);
 
  debug('interceptors for %j', options.host);
 
  basePath = options.proto + '://' + options.host;
 
  debug('filtering interceptors for basepath', basePath);
 
  //  First try to use filteringScope if any of the interceptors has it defined.
  _.each(allInterceptors, function(interceptor, k) {
    _.each(interceptor.scopes, function(scope) {
      var filteringScope = scope.__nock_scopeOptions.filteringScope;
 
      //  If scope filtering function is defined and returns a truthy value
      //  then we have to treat this as a match.
      if(filteringScope && filteringScope(basePath)) {
        debug('found matching scope interceptor');
 
        //  Keep the filtered scope (its key) to signal the rest of the module
        //  that this wasn't an exact but filtered match.
        scope.__nock_filteredScope = scope.__nock_scopeKey;
        matchingInterceptor = interceptor.scopes;
        //  Break out of _.each for scopes.
        return false;
      }
    });
 
    if (!matchingInterceptor && common.matchStringOrRegexp(basePath, interceptor.key)) {
      matchingInterceptor = interceptor.scopes;
      // false to short circuit the .each
      return false;
    }
 
    //  Returning falsy value here (which will happen if we have found our matching interceptor)
    //  will break out of _.each for all interceptors.
    return !matchingInterceptor;
  });
 
  return matchingInterceptor;
}
 
function removeInterceptor(options) {
  var baseUrl, key, method, proto;
 
  proto = options.proto ? options.proto : 'http';
 
  common.normalizeRequestOptions(options);
  baseUrl = proto + '://' + options.host;
 
  if (allInterceptors[baseUrl] && allInterceptors[baseUrl].scopes.length > 0) {
    Eif (options.path) {
      method = options.method && options.method.toUpperCase() || 'GET';
      key = method + ' ' + baseUrl + (options.path || '/');
 
      for (var i = 0; i < allInterceptors[baseUrl].scopes.length; i++) {
        Eif (allInterceptors[baseUrl].scopes[i]._key === key) {
          allInterceptors[baseUrl].scopes.splice(i, 1);
          break;
        }
      }
    } else {
      allInterceptors[baseUrl].scopes.length = 0;
    }
 
    return true;
  }
 
  return false;
}
//  Variable where we keep the ClientRequest we have overridden
//  (which might or might not be node's original http.ClientRequest)
var originalClientRequest;
 
function ErroringClientRequest(error) {
  Eif (http.OutgoingMessage) http.OutgoingMessage.call(this);
  process.nextTick(function() {
    this.emit('error', error);
  }.bind(this));
}
 
Eif (http.ClientRequest) {
  inherits(ErroringClientRequest, http.ClientRequest);
}
 
function overrideClientRequest() {
  debug('Overriding ClientRequest');
 
  Iif(originalClientRequest) {
    throw new Error('Nock already overrode http.ClientRequest');
  }
 
  // ----- Extending http.ClientRequest
 
  //  Define the overriding client request that nock uses internally.
  function OverriddenClientRequest(options, cb) {
    Eif (http.OutgoingMessage) http.OutgoingMessage.call(this);
 
    //  Filter the interceptors per request options.
    var interceptors = interceptorsFor(options)
 
    Eif (isOn() && interceptors) {
      debug('using', interceptors.length, 'interceptors');
 
      //  Use filtered interceptors to intercept requests.
      var overrider = RequestOverrider(this, options, interceptors, remove, cb);
      for(var propName in overrider) {
        if (overrider.hasOwnProperty(propName)) {
          this[propName] = overrider[propName];
        }
      }
    } else {
      debug('falling back to original ClientRequest');
 
      //  Fallback to original ClientRequest if nock is off or the net connection is enabled.
      if(isOff() || isEnabledForNetConnect(options)) {
        originalClientRequest.apply(this, arguments);
      } else {
        timers.setImmediate(function () {
          var error = new NetConnectNotAllowedError(options.host, options.path);
          this.emit('error', error);
        }.bind(this));
      }
    }
  }
  Eif (http.ClientRequest) {
    inherits(OverriddenClientRequest, http.ClientRequest);
  } else {
    inherits(OverriddenClientRequest, EventEmitter);
  }
 
  //  Override the http module's request but keep the original so that we can use it and later restore it.
  //  NOTE: We only override http.ClientRequest as https module also uses it.
  originalClientRequest = http.ClientRequest;
  http.ClientRequest = OverriddenClientRequest;
 
  debug('ClientRequest overridden');
}
 
function restoreOverriddenClientRequest() {
  debug('restoring overriden ClientRequest');
 
  //  Restore the ClientRequest we have overridden.
  if(!originalClientRequest) {
    debug('- ClientRequest was not overridden');
  } else {
    http.ClientRequest = originalClientRequest;
    originalClientRequest = undefined;
 
    debug('- ClientRequest restored');
  }
}
 
function isActive() {
 
  //  If ClientRequest has been overwritten by Nock then originalClientRequest is not undefined.
  //  This means that Nock has been activated.
  return !_.isUndefined(originalClientRequest);
 
}
 
function isDone() {
  return _.every(allInterceptors, function(interceptors) {
    return _.every(interceptors.scopes, function(interceptor) {
      return interceptor.__nock_scope.isDone();
    });
  });
}
 
function pendingMocks() {
  return _.reduce(allInterceptors, function(result, interceptors) {
    for (var interceptor in interceptors.scopes) {
      result = result.concat(interceptors.scopes[interceptor].__nock_scope.pendingMocks());
    }
 
    return result;
  }, []);
}
 
function activate() {
 
  if(originalClientRequest) {
    throw new Error('Nock already active');
  }
 
  overrideClientRequest();
 
  // ----- Overriding http.request and https.request:
 
  common.overrideRequests(function(proto, overriddenRequest, options, callback) {
    //  NOTE: overriddenRequest is already bound to its module.
    var req,
        res;
 
    if (typeof options === 'string') {
      options = parse(options);
    }
    options.proto = proto;
 
    var interceptors = interceptorsFor(options)
 
    if (isOn() && interceptors) {
      var matches = false,
          allowUnmocked = false;
 
      interceptors.forEach(function(interceptor) {
        if (! allowUnmocked && interceptor.options.allowUnmocked) { allowUnmocked = true; }
        if (interceptor.matchIndependentOfBody(options)) { matches = true; }
      });
 
      if (! matches && allowUnmocked) {
        if (proto === 'https') {
          var ClientRequest = http.ClientRequest;
          http.ClientRequest = originalClientRequest;
          req = overriddenRequest(options, callback);
          http.ClientRequest = ClientRequest;
        } else {
          req = overriddenRequest(options, callback);
        }
        globalEmitter.emit('no match', req);
        return req;
      }
 
      //  NOTE: Since we already overrode the http.ClientRequest we are in fact constructing
      //    our own OverriddenClientRequest.
      req = new http.ClientRequest(options);
 
      res = RequestOverrider(req, options, interceptors, remove);
      if (callback) {
        res.on('response', callback);
      }
      return req;
    } else {
      globalEmitter.emit('no match', req);
      if (isOff() || isEnabledForNetConnect(options)) {
        return overriddenRequest(options, callback);
      } else {
        var error = new NetConnectNotAllowedError(options.host, options.path);
        return new ErroringClientRequest(error);
      }
    }
  });
 
}
 
activate();
 
module.exports = add;
module.exports.removeAll = removeAll;
module.exports.removeInterceptor = removeInterceptor;
module.exports.isOn = isOn;
module.exports.activate = activate;
module.exports.isActive = isActive;
module.exports.isDone = isDone;
module.exports.pendingMocks = pendingMocks;
module.exports.enableNetConnect = enableNetConnect;
module.exports.disableNetConnect = disableNetConnect;
module.exports.overrideClientRequest = overrideClientRequest;
module.exports.restoreOverriddenClientRequest = restoreOverriddenClientRequest;