Module: WebMock::NetHTTPUtility

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

Class Method Summary collapse

Class Method Details

.check_right_http_connectionObject



365
366
367
# File 'lib/webmock/http_lib_adapters/net_http.rb', line 365

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

.puts_warning_for_right_http_if_neededObject



369
370
371
372
373
# File 'lib/webmock/http_lib_adapters/net_http.rb', line 369

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



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

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



346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
# File 'lib/webmock/http_lib_adapters/net_http.rb', line 346

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