Module: WebMock::NetHTTPUtility

Defined in:
lib/webmock/http_lib_adapters/net_http.rb

Class Method Summary collapse

Class Method Details

.check_right_http_connectionObject



317
318
319
# File 'lib/webmock/http_lib_adapters/net_http.rb', line 317

def self.check_right_http_connection
  @was_right_http_connection_loaded = defined?(RightHttpConnection)
end

.puts_warning_for_right_http_if_neededObject



321
322
323
324
325
# File 'lib/webmock/http_lib_adapters/net_http.rb', line 321

def self.puts_warning_for_right_http_if_needed
  if !@was_right_http_connection_loaded && defined?(RightHttpConnection)
    $stderr.puts "\nWarning: RightHttpConnection has to be required before WebMock is required !!!\n"
  end
end

.request_signature_from_request(net_http, request, body = nil) ⇒ Object



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
# File 'lib/webmock/http_lib_adapters/net_http.rb', line 267

def self.request_signature_from_request(net_http, request, body = nil)
  protocol = net_http.use_ssl? ? "https" : "http"

  path = request.path

  if path.respond_to?(:request_uri) #https://github.com/bblimke/webmock/issues/288
    path = path.request_uri
  end

  path = WebMock::Util::URI.heuristic_parse(path).request_uri if path =~ /^http/

  uri = "#{protocol}://#{net_http.address}:#{net_http.port}#{path}"
  method = request.method.downcase.to_sym

  headers = Hash[*request.to_hash.map {|k,v| [k, v]}.inject([]) {|r,x| r + x}]
  validate_headers(headers)

  if request.body_stream
    body = request.body_stream.read
    request.body_stream = nil
  end

  if body != nil && body.respond_to?(:read)
    request.set_body_internal body.read
  else
    request.set_body_internal body
  end

  WebMock::RequestSignature.new(method, uri, :body => request.body, :headers => headers)
end

.validate_headers(headers) ⇒ Object



298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/webmock/http_lib_adapters/net_http.rb', line 298

def self.validate_headers(headers)
  # For Ruby versions < 2.3.0, if you make a request with headers that are symbols
  # Net::HTTP raises a NoMethodError
  #
  # WebMock normalizes headers when creating a RequestSignature,
  # and will update all headers from symbols to strings.
  #
  # This could create a false positive in a test suite with WebMock.
  #
  # So before this point, WebMock raises an ArgumentError if any of the headers are symbols
  # instead of the cryptic NoMethodError "undefined method `split' ...` from Net::HTTP
  if Gem::Version.new(RUBY_VERSION.dup) < Gem::Version.new('2.3.0')
    header_as_symbol = headers.keys.find {|header| header.is_a? Symbol}
    if header_as_symbol
      raise ArgumentError.new("Net:HTTP does not accept headers as symbols")
    end
  end
end