Code coverage report for nock/lib/request_overrider.js

Statements: 92.08% (244 / 265)      Branches: 88.51% (154 / 174)      Functions: 97.14% (34 / 35)      Lines: 92.42% (244 / 264)      Ignored: none     

All files » nock/lib/ » request_overrider.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 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    1                       1 383 116     267   267     1 456 456   456 456 456   456 456   456 4 4 4         1 867 867           1   373 373 373 24             373 373 4     4       369 140   140 136     140           1   358                             358   358   358   106   106 106   106 280   280         358 8         358 358     358 180     358   358 14     358   358 3585 3585 3422 23   3422   3585       3585 3585     3585     358 189 189 180 180 180 180   189         358 2 2 2     2 2 2   2               358   361 38 38 38     361 361     358 7 7       358 180 180 180                 180 180 180 3   177           180 180   199   199     180   5 3   5 3 3                 5 5 5 5     175   175   175 1 1 1 1   174 174     174 174 174   174   20 4     16               154   2         2 2             2 13         152       152   2 2           2   1           170     1 174 1 1             174 146   146       3 3     146 132 131   1       146 3 3     146 12 12 12 12   12 12   12     134 1 1               174 174   174   174 38     174 4 4 4         174 32 32 32 1   32     174 174 5 5     5 3 3   2                   174       174         174 155 153 33 33 7   26     153 141 141 141         19 13 13 13 13         174 162 160 160       1 532             532 532 206 206     326 326     326       174   174 174 174   174         174 1     173     174 12 12     174     174 2     174 5   169           358     1  
'use strict';
 
var EventEmitter     = require('events').EventEmitter,
    http             = require('http'),
    propagate        = require('propagate'),
    DelayedBody      = require('./delayed_body'),
    OutgoingMessage  = http.OutgoingMessage,
    ClientRequest    = http.ClientRequest,
    common           = require('./common'),
    Socket           = require('./socket'),
    _                = require('lodash'),
    debug            = require('debug')('nock.request_overrider'),
    timers           = require('timers');
 
function getHeader(request, name) {
  if (!request._headers) {
    return;
  }
 
  var key = name.toLowerCase();
 
  return request._headers[key];
}
 
function setHeader(request, name, value) {
  debug('setHeader', name, value);
  var key = name.toLowerCase();
 
  request._headers = request._headers || {};
  request._headerNames = request._headerNames || {};
  request._removedHeader = request._removedHeader || {};
 
  request._headers[key] = value;
  request._headerNames[key] = name;
 
  if (name == 'expect' && value == '100-continue') {
    timers.setImmediate(function() {
      debug('continue');
      request.emit('continue');
    });
  }
}
 
function isStream(obj) {
  var is = obj && (typeof obj !== 'string') && (!Buffer.isBuffer(obj)) && (typeof obj.setEncoding === 'function');
  return is;
}
 
//  Sets request headers of the given request. This is needed during both matching phase
//  (in case header filters were specified) and mocking phase (to correctly pass mocked
//  request headers).
function setRequestHeaders(req, options, interceptor) {
  //  We mock request headers if these were specified.
  Eif (interceptor.reqheaders) {
    var reqheaders = interceptor.reqheaders;
    _(interceptor.reqheaders).keys().each(function(key) {
      setHeader(req, key, reqheaders[key]);
    });
  }
 
  //  If a filtered scope is being used we have to use scope's host
  //  in the header, otherwise 'host' header won't match.
  //  NOTE: We use lower-case header field names throught Nock.
  var HOST_HEADER = 'host';
  if(interceptor.__nock_filteredScope && interceptor.__nock_scopeHost) {
    Iif(options && options.headers) {
      options.headers[HOST_HEADER] = interceptor.__nock_scopeHost;
    }
    setHeader(req, HOST_HEADER, interceptor.__nock_scopeHost);
  } else {
    //  For all other cases, we always add host header equal to the
    //  requested host unless it was already defined.
    if (options.host && !getHeader(req, HOST_HEADER)) {
      var hostHeader = options.host;
 
      if (options.port === 80 || options.port === 443) {
        hostHeader = hostHeader.split(':')[0];
      }
 
      setHeader(req, HOST_HEADER, hostHeader);
    }
  }
 
}
 
function RequestOverrider(req, options, interceptors, remove, cb) {
 
  var response = new OutgoingMessage(new EventEmitter()),
      requestBodyBuffers = [],
      originalInterceptors = interceptors,
      aborted,
      emitError,
      end,
      ended,
      headers,
      keys,
      key,
      i,
      l;
 
  //  We may be changing the options object and we don't want those
  //  changes affecting the user so we use a clone of the object.
  options = _.clone(options) || {};
 
  response.req = req;
 
  if (options.headers) {
    //  We use lower-case header field names throught Nock.
    options.headers = common.headersFieldNamesToLowerCase(options.headers);
 
    headers = options.headers;
    keys = Object.keys(headers);
 
    for (i = 0, l = keys.length; i < l; i++) {
      key = keys[i];
 
      setHeader(req, key, headers[key]);
    }
  }
 
  /// options.auth
  if (options.auth && (! options.headers || ! options.headers.authorization)) {
    setHeader(req, 'Authorization', 'Basic ' + (new Buffer(options.auth)).toString('base64'));
  }
 
  // Mock response.connection and request.connection
  // Fixes: https://github.com/flatiron/nock/issues/74
  Eif (! response.connection) {
    response.connection = new EventEmitter();
  }
 
  if (! req.connection) {
    req.connection = new EventEmitter();
  }
 
  req.path = options.path;
 
  options.getHeader = function(name) {
    return getHeader(req, name);
  };
 
  req.socket = Socket();
 
  req.write = function(buffer, encoding) {
    debug('write', arguments);
    if (buffer && !aborted) {
      if (! Buffer.isBuffer(buffer)) {
        buffer = new Buffer(buffer, encoding);
      }
      requestBodyBuffers.push(buffer);
    }
    Iif (aborted) {
      emitError(new Error('Request aborted'));
    }
 
    timers.setImmediate(function() {
      req.emit('drain');
    });
 
    return false;
  };
 
  req.end = function(buffer, encoding) {
    debug('req.end');
    if (!aborted && !ended) {
      req.write(buffer, encoding);
      end(cb);
      req.emit('finish');
      req.emit('end');
    }
    Iif (aborted) {
      emitError(new Error('Request aborted'));
    }
  };
 
  req.abort = function() {
    debug('req.abort');
    aborted = true;
    Iif (!ended) {
      end();
    }
    var err = new Error();
    err.code = 'aborted';
    response.emit('close', err);
 
    req.socket.destroy();
  };
 
  // restify listens for a 'socket' event to
  // be emitted before calling end(), which causes
  // nock to hang with restify. The following logic
  // fakes the socket behavior for restify,
  // Fixes: https://github.com/pgte/nock/issues/79
  req.once = req.on = function(event, listener) {
    // emit a fake socket.
    if (event == 'socket') {
      listener(req.socket);
      req.socket.emit('connect', req.socket);
      req.socket.emit('secureConnect', req.socket);
    }
 
    EventEmitter.prototype.on.call(this, event, listener);
    return this;
  };
 
  emitError = function(error) {
    process.nextTick(function () {
      req.emit('error', error);
    });
  };
 
  end = function(cb) {
    debug('ending');
    ended = true;
    var encoding,
        requestBody,
        responseBody,
        responseBuffers,
        interceptor,
        paused,
        mockEmits = [];
 
    //  When request body is a binary buffer we internally use in its hexadecimal representation.
    var requestBodyBuffer = common.mergeChunks(requestBodyBuffers);
    var isBinaryRequestBodyBuffer = common.isBinaryBuffer(requestBodyBuffer);
    if(isBinaryRequestBodyBuffer) {
      requestBody = requestBodyBuffer.toString('hex');
    } else {
      requestBody = requestBodyBuffer.toString('utf8');
    }
 
    /// put back the path into options
    /// because bad behaving agents like superagent
    /// like to change request.path in mid-flight.
    options.path = req.path;
    interceptors = interceptors.filter(function(interceptor) {
      //  For correct matching we need to have correct request headers - if these were specified.
      setRequestHeaders(req, options, interceptor);
 
      return interceptor.match(options, requestBody);
    });
 
    if (interceptors.length < 1) {
      // Try to find a hostname match
      interceptors = originalInterceptors.filter(function(interceptor) {
        return interceptor.match(options, requestBody, true);
      });
      if (interceptors.length && req instanceof ClientRequest) {
        interceptor = interceptors[0];
        Iif (interceptor.options.allowUnmocked) {
          var newReq = new ClientRequest(options, cb);
          propagate(newReq, req);
          //  We send the raw buffer as we received it, not as we interpreted it.
          newReq.end(requestBodyBuffer);
          return;
        }
      }
 
      var err = new Error("Nock: No match for request " + common.stringifyRequest(options, requestBody));
      err.statusCode = err.status = 404;
      emitError(err);
      return;
    }
 
    debug('interceptor identified, starting mocking');
 
    interceptor = interceptors.shift();
 
    if (typeof interceptor.errorMessage !== 'undefined') {
      remove(interceptor);
      interceptor.discard();
      emitError(new Error(interceptor.errorMessage));
      return;
    }
    response.statusCode = Number(interceptor.statusCode) || 200;
    response.headers = interceptor.headers || {};
 
    //  We again set request headers, now for our matched interceptor.
    setRequestHeaders(req, options, interceptor);
    interceptor.req = req;
    req.headers = req._headers;
 
    if (typeof interceptor.body === 'function') {
      // In case we are waiting for a callback
      if (interceptor.body.length === 3) {
        return interceptor.body(options.path, requestBody || '', continueWithResponseBody);
      }
 
      responseBody = interceptor.body(options.path, requestBody) || '';
 
    } else {
 
      //  If the content is encoded we know that the response body *must* be an array
      //  of response buffers which should be mocked one by one.
      //  (otherwise decompressions after the first one fails as unzip expects to receive
      //  buffer by buffer and not one single merged buffer)
      if(common.isContentEncoded(response.headers) && ! isStream(interceptor.body)) {
 
        Iif (interceptor.delayInMs) {
          emitError(new Error('Response delay is currently not supported with content-encoded responses.'));
          return;
        }
 
        var buffers = interceptor.body;
        Iif(!_.isArray(buffers)) {
          emitError(
            new Error(
              'content-encoded response must be an array of binary buffers and not ' + typeof(buffers)));
          return;
        }
 
        responseBuffers = _.map(buffers, function(buffer) {
          return new Buffer(buffer, 'hex');
        });
 
      } else {
 
        responseBody = interceptor.body;
 
        //  If the request was binary then we assume that the response will be binary as well.
        //  In that case we send the response as a Buffer object as that's what the client will expect.
        if(isBinaryRequestBodyBuffer && typeof(responseBody) === 'string') {
          //  Try to create the buffer from the interceptor's body response as hex.
          try {
            responseBody = new Buffer(responseBody, 'hex');
          } catch(err) {
            debug('exception during Buffer construction from hex data:', responseBody, '-', err);
          }
 
          // Creating buffers does not necessarily throw errors, check for difference in size
          if (!responseBody || (interceptor.body.length > 0 && responseBody.length === 0)) {
            //  We fallback on constructing buffer from utf8 representation of the body.
            responseBody = new Buffer(interceptor.body, 'utf8');
          }
        }
 
      }
    }
    return continueWithResponseBody(null, responseBody);
 
 
    function continueWithResponseBody(err, responseBody) {
      if (err) {
        response.statusCode = 500;
        responseBody = err.stack;
 
      }
 
      //  Transform the response body if it exists (it may not exist
      //  if we have `responseBuffers` instead)
 
      if (responseBody) {
        debug('transform the response body');
 
        if (Array.isArray(responseBody) &&
            responseBody.length == 2 &&
            typeof responseBody[0] == 'number')
        {
          response.statusCode = Number(responseBody[0]);
          responseBody = responseBody[1];
        }
 
        if (!Buffer.isBuffer(responseBody) && !isStream(responseBody)) {
          if (typeof responseBody === 'string') {
            responseBody = new Buffer(responseBody);
          } else {
            responseBody = JSON.stringify(responseBody);
          }
        }
 
        if (interceptor.delayInMs) {
          debug('delaying the response for', interceptor.delayInMs, 'milliseconds');
          responseBody = new DelayedBody(interceptor.delayInMs, responseBody);
        }
 
        if (isStream(responseBody)) {
          debug('response body is a stream');
          responseBody.pause();
          responseBody.on('data', function(d) {
            response.emit('data', d);
          });
          responseBody.on('end', function() {
            response.emit('end');
          });
          responseBody.on('error', function(err) {
            response.emit('error', err);
          });
        } else if (responseBody && !Buffer.isBuffer(responseBody)) {
          Eif (typeof responseBody === 'string') {
            responseBody = new Buffer(responseBody);
          } else {
            responseBody = JSON.stringify(responseBody);
            response.headers['content-type'] = 'application/json';
          }
        }
      }
 
      remove(interceptor);
      interceptor.discard();
 
      Iif (aborted) { return; }
 
      response.setEncoding = function(newEncoding) {
        encoding = newEncoding;
      };
 
      response.pause = function() {
        debug('pausing mocking');
        paused = true;
        Iif (isStream(responseBody)) {
          responseBody.pause();
        }
      };
 
      response.resume = function() {
        debug('resuming mocking');
        paused = false;
        if (isStream(responseBody)) {
          responseBody.resume();
        }
        mockNextEmit();
      };
 
      var read = false;
      response.read = function() {
        debug('reading response body');
        Iif (isStream(responseBody) && responseBody.read) {
          return responseBody.read();
        } else {
          if (! read) {
            read = true;
            return responseBody;
          } else {
            return null;
          }
        }
      };
 
      //  HACK: Flag our response object as readable so that it can be automatically
      //    resumed by Node when drain happens. This enables working with some agents
      //    that behave differently than built-in agent (e.g. needle, superagent).
      //    The correct way to implement this would be to use IncomingMessage instead
      //    of OutgoingMessage class to mock responses.
      response.readable = true;
 
      /// response.client.authorized = true
      /// fixes https://github.com/pgte/nock/issues/158
      response.client = _.extend(response.client || {}, {
        authorized: true
      });
 
      //  `mockEmits` is an array of emits to be performed during mocking.
      if (typeof responseBody !== "undefined") {
        mockEmits.push(function() {
          if (encoding) {
            debug('transforming body per its encoding');
            if (isStream(responseBody)) {
              responseBody.setEncoding(encoding);
            } else {
              responseBody = responseBody.toString(encoding);
            }
          }
          if (! isStream(responseBody)) {
            debug('emitting response body');
            response.emit('data', responseBody);
            response.emit('readable');
          }
        });
      } else {
        //  We will emit response buffers one by one.
        _.each(responseBuffers, function(buffer) {
          mockEmits.push(function() {
            debug('emitting response buffer');
            response.emit('data', buffer);
            response.emit('readable');
          });
        });
      }
 
      if (!isStream(responseBody)) {
        mockEmits.push(function() {
          debug('emitting end');
          response.emit('end');
        });
      }
 
      function mockNextEmit() {
        debug('mocking next emit');
 
        //  We don't use `process.nextTick` because we *want* (very much so!)
        //  for I/O to happen before the next `emit` since we are precisely mocking I/O.
        //  Otherwise the writing to output pipe may stall invoking pause()
        //  without ever calling resume() (the observed was behavior on superagent
        //  with Node v0.10.26)
        timers.setImmediate(function() {
          if (paused || mockEmits.length === 0 || aborted) {
            debug('mocking paused, aborted or finished');
            return;
          }
 
          var nextMockEmit = mockEmits.shift();
          nextMockEmit();
 
          //  Recursively invoke to mock the next emit after the last one was handled.
          mockNextEmit();
        });
      }
 
      debug('mocking', mockEmits.length, 'emits');
 
      process.nextTick(function() {
        var respond = function() {
          debug('emitting response');
 
          Iif (typeof cb === 'function') {
            debug('callback with response');
            cb(response);
          }
 
          if (aborted) {
            emitError(new Error('Request aborted'));
          }
          else {
            req.emit('response', response);
          }
 
          if (isStream(responseBody)) {
            debug('resuming response stream');
            responseBody.resume();
          }
 
          mockNextEmit();
        };
 
        if (interceptor.socketDelayInMs && interceptor.socketDelayInMs > 0) {
          req.socket._checkTimeout(interceptor.socketDelayInMs);
        }
 
        if (interceptor.delayConnectionInMs && interceptor.delayConnectionInMs > 0) {
          setTimeout(respond, interceptor.delayConnectionInMs);
        } else {
          respond();
        }
      });
    }
  };
 
  return req;
}
 
module.exports = RequestOverrider;