/
client.cr
348 lines (307 loc) · 11.9 KB
/
client.cr
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
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
345
346
347
348
module Marten
module Spec
# A test client allowing to issue requests to the server and obtain the associated responses.
#
# By leveraging this test client, developers can easily forge various requests and obtain the corresponding
# responses returned by the server. In the process, the test client ensures that all the configured middlewares are
# used and applied.
#
# It should be noted that a test client is stateful: cookies and session data will be retained for the lifetime of
# a specific client instance.
#
# Moreover, the test client disables CSRF checks by default in order to ease the process of testing unsafe request
# methods. If you trully need to have these checks applied when running specs, you can initialize a test client by
# setting `disable_request_forgery_protection` to `false`.
class Client
@server_handler : ::HTTP::Handler?
@session : HTTP::Session::Store::Base?
# Returns a `Marten::HTTP::Headers` object that can be leveraged to set headers that should bet for each request.
getter headers
def initialize(@content_type : String? = nil, @disable_request_forgery_protection = true)
@headers = HTTP::Headers.new
end
# Returns a `Marten::HTTP::Cookies` object that can be leveraged to set cookies that should be used by the client.
#
# Cookies that are defined via this hash-like object will automatically be used for every request issued by the
# test client.
def cookies
@cookies ||= Marten::HTTP::Cookies.new
end
# Allows to issue a DELETE request to the server.
def delete(
path : String,
data : Hash | NamedTuple | Nil | String = nil,
query_params : Hash | NamedTuple | Nil = nil,
content_type : String? = nil,
headers : Hash | NamedTuple | Nil = nil,
secure = false
) : Marten::HTTP::Response
perform_request(
method: "DELETE",
path: path,
data: data,
query_params: query_params,
content_type: content_type,
headers: headers,
secure: secure
)
end
# Allows to issue a GET request to the server.
def get(
path : String,
query_params : Hash | NamedTuple | Nil = nil,
content_type : String? = nil,
headers : Hash | NamedTuple | Nil = nil,
secure = false
) : Marten::HTTP::Response
perform_request(
method: "GET",
path: path,
query_params: query_params,
content_type: content_type,
headers: headers,
secure: secure
)
end
# Allows to issue a HEAD request to the server.
def head(
path : String,
query_params : Hash | NamedTuple | Nil = nil,
content_type : String? = nil,
headers : Hash | NamedTuple | Nil = nil,
secure = false
)
perform_request(
method: "HEAD",
path: path,
query_params: query_params,
content_type: content_type,
headers: headers,
secure: secure
)
end
# Allows to issue an OPTIONS request to the server.
def options(
path : String,
query_params : Hash | NamedTuple | Nil = nil,
content_type : String? = nil,
headers : Hash | NamedTuple | Nil = nil,
secure = false
)
perform_request(
method: "OPTIONS",
path: path,
query_params: query_params,
content_type: content_type,
headers: headers,
secure: secure
)
end
# Allows to issue a PATCH request to the server.
def patch(
path : String,
data : Hash | NamedTuple | Nil | String = nil,
query_params : Hash | NamedTuple | Nil = nil,
content_type : String? = nil,
headers : Hash | NamedTuple | Nil = nil,
secure = false
) : Marten::HTTP::Response
perform_request(
method: "PATCH",
path: path,
data: data,
query_params: query_params,
content_type: content_type,
headers: headers,
secure: secure
)
end
# Allows to issue a POST request to the server.
def post(
path : String,
data : Hash | NamedTuple | Nil | String = nil,
query_params : Hash | NamedTuple | Nil = nil,
content_type : String? = nil,
headers : Hash | NamedTuple | Nil = nil,
secure = false
) : Marten::HTTP::Response
perform_request(
method: "POST",
path: path,
data: data,
query_params: query_params,
content_type: content_type,
headers: headers,
secure: secure
)
end
# Allows to issue a PUT request to the server.
def put(
path : String,
data : Hash | NamedTuple | Nil | String = nil,
query_params : Hash | NamedTuple | Nil = nil,
content_type : String? = nil,
headers : Hash | NamedTuple | Nil = nil,
secure = false
) : Marten::HTTP::Response
perform_request(
method: "PUT",
path: path,
data: data,
query_params: query_params,
content_type: content_type,
headers: headers,
secure: secure
)
end
# Returns a session store object for the client.
#
# This method returns a session store object, initialized using the currently configured session store. The test
# client will ensure that this session store is automatically saved and that the session key is persisted in the
# cookies before issuing requests.
def session
@session ||= get_session
end
# Allows to issue a TRACE request to the server.
def trace(
path : String,
data : Hash | NamedTuple | Nil | String = nil,
query_params : Hash | NamedTuple | Nil = nil,
content_type : String? = nil,
headers : Hash | NamedTuple | Nil = nil,
secure = false
) : Marten::HTTP::Response
perform_request(
method: "TRACE",
path: path,
data: data,
query_params: query_params,
content_type: content_type,
headers: headers,
secure: secure
)
end
private DEFAULT_CONTENT_TYPE_PER_METHOD = {
"DELETE" => "application/octet-stream",
"GET" => "application/octet-stream",
"OPTIONS" => "application/octet-stream",
"PATCH" => "application/octet-stream",
"POST" => "#{MULTIPART_CONTENT_TYPE_PREFIX} boundary=#{MULTIPART_BOUNDARY}",
"PUT" => "application/octet-stream",
}
private MULTIPART_BOUNDARY = "B0UnDaRyUnIqU3"
private MULTIPART_CONTENT_TYPE_PREFIX = "multipart/form-data;"
private MULTIPART_CONTENT_TYPE = "#{MULTIPART_CONTENT_TYPE_PREFIX} boundary=#{MULTIPART_BOUNDARY}"
private SERVER_HANDLER_CHAIN = [
Server::Handlers::Middleware,
Server::Handlers::Routing,
]
private URL_ENCODED_FORM_CONTENT_TYPE = "application/x-www-form-urlencoded"
private getter? disable_request_forgery_protection
private def build_multipart_body(data)
io = IO::Memory.new
::HTTP::FormData.build(io, MULTIPART_BOUNDARY) do |builder|
data.each do |key, value|
case (object = value)
when Enumerable, Iterable
object.each { |v| builder.field(key.to_s, v.to_s) }
when DB::Field::File::File
builder.file(key.to_s, object.open, ::HTTP::FormData::FileMetadata.new(filename: object.name.to_s))
when IO
builder.file(key.to_s, object, ::HTTP::FormData::FileMetadata.new(filename: "file"))
else
builder.field(key.to_s, value.to_s)
end
end
end
io.to_s
end
private def build_query_params(raw_query_params)
query_params = URI::Params.new
raw_query_params.each do |key, value|
query_params[key.to_s] = case (object = value)
when Enumerable, Iterable
object.map(&.to_s)
else
[object.to_s]
end
end
query_params
end
private def default_content_type
@content_type
end
private def get_session : HTTP::Session::Store::Base
session_store_klass = HTTP::Session::Store.get(Marten.settings.sessions.store)
session_cookie = cookies[Marten.settings.sessions.cookie_name]?
return session_store_klass.new(session_cookie) if !session_cookie.nil? && !session_cookie.try(&.empty?)
session_store = session_store_klass.new(nil)
session_store.save
cookies[Marten.settings.sessions.cookie_name] = session_store.session_key
session_store
end
private def perform_request(
method : String,
path : String,
data : Hash | NamedTuple | Nil | String = nil,
query_params : Hash | NamedTuple | Nil = nil,
content_type : String? = nil,
headers : Hash | NamedTuple | Nil = nil,
secure = false
)
request_content_type = content_type || default_content_type || DEFAULT_CONTENT_TYPE_PER_METHOD[method]?
request_headers = Marten::HTTP::Headers{"Host" => "127.0.0.1"}
request_headers["Content-Type"] = request_content_type if request_content_type
@headers.try(&.each { |k, v| request_headers[k.to_s] = v.first.to_s })
headers.try(&.each { |k, v| request_headers[k.to_s] = v.to_s })
request_full_path = if query_params.nil?
path
else
"#{path}?#{build_query_params(query_params)}"
end
request_body = case data
when Hash, NamedTuple
if request_content_type.try(&.starts_with?(MULTIPART_CONTENT_TYPE_PREFIX))
build_multipart_body(data)
elsif request_content_type == URL_ENCODED_FORM_CONTENT_TYPE
build_query_params(data).to_s
end
else
data
end
context = ::HTTP::Server::Context.new(
request: ::HTTP::Request.new(
method: method,
resource: request_full_path,
headers: request_headers.to_stdlib,
body: request_body
),
response: ::HTTP::Server::Response.new(io: IO::Memory.new)
)
# Saves the session store (just in case it might not have been saved before) and updates the session ID value in
# the cookies.
if session?
session.save
cookies[Marten.settings.sessions.cookie_name] = session.session_key
end
# Sets the cookies that might have been set on the client before performing the actual request.
cookies.to_stdlib.each { |c| context.request.cookies << c }
# Disables CSRF checks and sets the request to secure if applicable.
context.marten.request.disable_request_forgery_protection = true if disable_request_forgery_protection?
context.marten.request.scheme = "https" if secure
server_handler.call(context)
response = context.marten.response.not_nil!
# Updates the cookies store and resets the session store from the obtained response.
@cookies = HTTP::Cookies.new(context.response.cookies)
@session = nil
response
end
private def session?
!@session.nil?
end
private def server_handler
@server_handler ||= ::HTTP::Server.build_middleware(SERVER_HANDLER_CHAIN.map(&.new))
end
end
end
end