File: em_http_request_spec_helper.rb

package info (click to toggle)
ruby-webmock 3.25.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,172 kB
  • sloc: ruby: 12,829; makefile: 6
file content (80 lines) | stat: -rw-r--r-- 1,783 bytes parent folder | download
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
module EMHttpRequestSpecHelper

  def failed
    EventMachine.stop
    fail
  end

  def http_request(method, uri, options = {}, &block)
    @http = nil
    head = options[:headers] || {}
    if options[:basic_auth]
      head.merge!('authorization' => options[:basic_auth])
    end
    response = nil
    error = nil
    error_set = false
    uri = Addressable::URI.heuristic_parse(uri)
    EventMachine.run {
      request = EventMachine::HttpRequest.new("#{uri.normalize.to_s}", ssl: {verify_peer: true})
      http = request.send(method, {
        timeout: 30,
        body: options[:body],
        file: options[:file],
        query: options[:query],
        head: head,
        compressed: false
      }, &block)
      http.errback {
        error_set = true
        error = if http.respond_to?(:errors)
          http.errors
        else
          http.error
        end
        failed
      }
      http.callback {
        response = OpenStruct.new({
          body: http.response,
          headers: WebMock::Util::Headers.normalize_headers(extract_response_headers(http)),
          message: http.response_header.http_reason,
          status: http.response_header.status.to_s
        })
        EventMachine.stop
      }
      @http = http
    }
    raise error.to_s if error_set
    response
  end

  def client_timeout_exception_class
    RuntimeError # 'Errno::ETIMEDOUT'
  end

  def connection_refused_exception_class
    RuntimeError
  end

  def connection_error_class
  end

  def http_library
    :em_http_request
  end

  private

  def extract_response_headers(http)
    headers = {}
    if http.response_header
      http.response_header.each do |k,v|
        v = v.join(", ") if v.is_a?(Array)
        headers[k] = v
      end
    end
    headers
  end

end