-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathhttp_util.rb
More file actions
105 lines (87 loc) · 2.13 KB
/
http_util.rb
File metadata and controls
105 lines (87 loc) · 2.13 KB
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
require "webrick"
require "webrick/httpproxy"
require "webrick/https"
require "stringio"
require "zlib"
class StubHTTPServer
attr_reader :requests, :port
def initialize(enable_compression: false)
@enable_compression = enable_compression
base_opts = {
BindAddress: '127.0.0.1',
Port: 0, # Let OS assign an available port
AccessLog: [],
Logger: NullLogger.new,
RequestCallback: method(:record_request),
}
@server = create_server(base_opts)
@requests = []
@requests_queue = Queue.new
end
def create_server(base_opts)
server = WEBrick::HTTPServer.new(base_opts)
# Get the actual port assigned by the OS
@port = server.config[:Port]
server
end
def start
Thread.new { @server.start }
end
def stop
@server.shutdown
end
def base_uri
URI("http://127.0.0.1:#{@port}")
end
def setup_response(uri_path, &action)
@server.mount_proc(uri_path, action)
end
def setup_status_response(uri_path, status, headers={})
setup_response(uri_path) do |req, res|
res.status = status
headers.each { |n, v| res[n] = v }
end
end
def setup_ok_response(uri_path, body, content_type=nil, headers={})
setup_response(uri_path) do |req, res|
res.status = 200
res.content_type = content_type unless content_type.nil?
res.body = body
headers.each { |n, v| res[n] = v }
end
end
def record_request(req, res)
@requests.push(req)
@requests_queue << [req, req.body]
end
def await_request_with_body
r = @requests_queue.pop
request = r[0]
body = r[1]
return [request, body.to_s] unless @enable_compression
gz = Zlib::GzipReader.new(StringIO.new(body.to_s))
[request, gz.read]
end
end
class NullLogger
def method_missing(*)
self
end
end
def with_server(enable_compression: false)
server = StubHTTPServer.new(enable_compression: enable_compression)
begin
server.start
yield server
ensure
server.stop
end
end
class SocketFactoryFromHash
def initialize(ports = {})
@ports = ports
end
def open(uri, timeout)
TCPSocket.new '127.0.0.1', @ports[uri]
end
end