class Excon::Connection

def invoke_stub(params)

def invoke_stub(params)
  # convert File/Tempfile body to string before matching:
  unless params[:body].nil? || params[:body].is_a?(String)
   if params[:body].respond_to?(:binmode)
     params[:body].binmode
   end
   if params[:body].respond_to?(:rewind)
     params[:body].rewind
   end
   params[:body] = params[:body].read
  end
  params[:captures] = {:headers => {}} # setup data to hold captures
  Excon.stubs.each do |stub, response|
    headers_match = !stub.has_key?(:headers) || stub[:headers].keys.all? do |key|
      case value = stub[:headers][key]
      when Regexp
        if match = value.match(params[:headers][key])
          params[:captures][:headers][key] = match.captures
        end
        match
      else
        value == params[:headers][key]
      end
    end
    non_headers_match = (stub.keys - [:headers]).all? do |key|
      case value = stub[key]
      when Regexp
        if match = value.match(params[key])
          params[:captures][key] = match.captures
        end
        match
      else
        value == params[key]
      end
    end
    if headers_match && non_headers_match
      response_attributes = case response
      when Proc
        response.call(params)
      else
        response
      end
      if params[:expects] && ![*params[:expects]].include?(response_attributes[:status])
        # don't pass stuff into a block if there was an error
      elsif params.has_key?(:response_block) && response_attributes.has_key?(:body)
        body = response_attributes.delete(:body)
        content_length = remaining = body.bytesize
        i = 0
        while i < body.length
          params[:response_block].call(body[i, params[:chunk_size]], [remaining - params[:chunk_size], 0].max, content_length)
          remaining -= params[:chunk_size]
          i += params[:chunk_size]
        end
      end
      return Excon::Response.new(response_attributes)
    end
  end
  # if we reach here no stubs matched
  raise(Excon::Errors::StubNotFound.new('no stubs matched ' << params.inspect))
end