Debian Codegraph @

test/examples_SUITE.erl

raw
1 %% Copyright (c) Loïc Hoguin <[email protected]>
2 %%
3 %% Permission to use, copy, modify, and/or distribute this software for any
4 %% purpose with or without fee is hereby granted, provided that the above
5 %% copyright notice and this permission notice appear in all copies.
6 %%
7 %% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
10 %% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 %% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
12 %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
13 %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14
15 -module(examples_SUITE).
16 -compile(export_all).
17 -compile(nowarn_export_all).
18
19 -import(ct_helper, [config/2]).
20 -import(ct_helper, [doc/1]).
21 -import(cowboy_test, [gun_open/1]).
22
23 %% ct.
24
25 all() ->
26 ct_helper:all(?MODULE).
27
28 init_per_suite(Config) ->
29 %% Remove environment variables inherited from Erlang.mk.
30 os:unsetenv("ERLANG_MK_TMP"),
31 os:unsetenv("APPS_DIR"),
32 os:unsetenv("DEPS_DIR"),
33 os:unsetenv("ERL_LIBS"),
34 %% Clone and build Cowboy, Cowlib and Ranch only once and
35 %% reuse the same build across all tests.
36 Make = do_find_make_cmd(),
37 CommonDir = config(priv_dir, Config),
38 ct:log("~ts~n", [os:cmd("git clone --depth 1 https://github.com/ninenines/cowboy "
39 ++ CommonDir ++ "cowboy")]),
40 ct:log("~ts~n", [os:cmd(Make ++ " -C " ++ CommonDir ++ "cowboy distclean")]),
41 ct:log("~ts~n", [os:cmd(Make ++ " -C " ++ CommonDir ++ "cowboy DEPS_DIR=" ++ CommonDir)]),
42 Config.
43
44 end_per_suite(_) ->
45 ok.
46
47 %% Find GNU Make.
48
49 do_find_make_cmd() ->
50 case os:getenv("MAKE") of
51 false ->
52 case os:find_executable("gmake") of
53 false -> "make";
54 Cmd -> Cmd
55 end;
56 Cmd ->
57 Cmd
58 end.
59
60 %% Compile, start and stop releases.
61
62 do_get_paths(Example0) ->
63 Example = atom_to_list(Example0),
64 {ok, CWD} = file:get_cwd(),
65 Dir = CWD ++ "/../../examples/" ++ Example,
66 Rel = Dir ++ "/_rel/" ++ Example ++ "_example/bin/" ++ Example ++ "_example",
67 Log = Dir ++ "/_rel/" ++ Example ++ "_example/log/erlang.log.1",
68 {Dir, Rel, Log}.
69
70 do_compile_and_start(Example, Config) ->
71 Make = do_find_make_cmd(),
72 {Dir, Rel, _} = do_get_paths(Example),
73 ct:log("~ts~n", [os:cmd(Make ++ " -C " ++ Dir ++ " distclean")]),
74 %% We use a common build for Cowboy, Cowlib and Ranch to speed things up.
75 CommonDir = config(priv_dir, Config),
76 ct:log("~ts~n", [os:cmd("mkdir " ++ Dir ++ "/deps")]),
77 ct:log("~ts~n", [os:cmd("ln -s " ++ CommonDir ++ "cowboy " ++ Dir ++ "/deps/cowboy")]),
78 ct:log("~ts~n", [os:cmd("ln -s " ++ CommonDir ++ "cowlib " ++ Dir ++ "/deps/cowlib")]),
79 ct:log("~ts~n", [os:cmd("ln -s " ++ CommonDir ++ "ranch " ++ Dir ++ "/deps/ranch")]),
80 %% TERM=dumb disables relx coloring.
81 ct:log("~ts~n", [os:cmd(Make ++ " -C " ++ Dir ++ " TERM=dumb")]),
82 ct:log("~ts~n", [os:cmd(Rel ++ " stop")]),
83 ct:log("~ts~n", [os:cmd(Rel ++ " daemon")]),
84 timer:sleep(2000),
85 ok.
86
87 do_stop(Example) ->
88 {_, Rel, Log} = do_get_paths(Example),
89 ct:log("~ts~n", [os:cmd(Rel ++ " stop")]),
90 ct:log("~ts~n", [element(2, file:read_file(Log))]),
91 ok.
92
93 %% Fetch a response.
94
95 do_get(Transport, Protocol, Path, Config) ->
96 do_get(Transport, Protocol, Path, [], Config).
97
98 do_get(Transport, Protocol, Path, ReqHeaders, Config) ->
99 Port = case Transport of
100 tcp -> 8080;
101 ssl -> 8443
102 end,
103 ConnPid = gun_open([{port, Port}, {type, Transport}, {protocol, Protocol}|Config]),
104 Ref = gun:get(ConnPid, Path, ReqHeaders),
105 case gun:await(ConnPid, Ref) of
106 {response, nofin, Status, RespHeaders} ->
107 {ok, Body} = gun:await_body(ConnPid, Ref),
108 {Status, RespHeaders, Body};
109 {response, fin, Status, RespHeaders} ->
110 {Status, RespHeaders, <<>>}
111 end.
112
113 %% TCP and SSL Hello World.
114
115 hello_world(Config) ->
116 doc("Hello World example."),
117 try
118 do_compile_and_start(hello_world, Config),
119 do_hello_world(tcp, http, Config),
120 do_hello_world(tcp, http2, Config)
121 after
122 do_stop(hello_world)
123 end.
124
125 ssl_hello_world(Config) ->
126 doc("SSL Hello World example."),
127 try
128 do_compile_and_start(ssl_hello_world, Config),
129 do_hello_world(ssl, http, Config),
130 do_hello_world(ssl, http2, Config)
131 after
132 do_stop(ssl_hello_world)
133 end.
134
135 do_hello_world(Transport, Protocol, Config) ->
136 {200, _, <<"Hello world!">>} = do_get(Transport, Protocol, "/", Config),
137 ok.
138
139 %% Chunked Hello World.
140
141 chunked_hello_world(Config) ->
142 doc("Chunked Hello World example."),
143 try
144 do_compile_and_start(chunked_hello_world, Config),
145 do_chunked_hello_world(tcp, http, Config),
146 do_chunked_hello_world(tcp, http2, Config)
147 after
148 do_stop(chunked_hello_world)
149 end.
150
151 do_chunked_hello_world(Transport, Protocol, Config) ->
152 ConnPid = gun_open([{port, 8080}, {type, Transport}, {protocol, Protocol}|Config]),
153 Ref = gun:get(ConnPid, "/"),
154 {response, nofin, 200, _} = gun:await(ConnPid, Ref),
155 %% We expect to receive a chunk every second, three total.
156 {data, nofin, <<"Hello\r\n">>} = gun:await(ConnPid, Ref, 2000),
157 {data, nofin, <<"World\r\n">>} = gun:await(ConnPid, Ref, 2000),
158 {data, IsFin, <<"Chunked!\r\n">>} = gun:await(ConnPid, Ref, 2000),
159 %% We may get an extra empty chunk (last chunk for HTTP/1.1,
160 %% empty DATA frame with the FIN bit set for HTTP/2).
161 case IsFin of
162 fin -> ok;
163 nofin ->
164 {data, fin, <<>>} = gun:await(ConnPid, Ref, 500),
165 ok
166 end.
167
168 %% Compressed responses.
169
170 compress_response(Config) ->
171 doc("Compressed response example."),
172 try
173 do_compile_and_start(compress_response, Config),
174 do_compress_response(tcp, http, Config),
175 do_compress_response(tcp, http2, Config)
176 after
177 do_stop(compress_response)
178 end.
179
180 do_compress_response(Transport, Protocol, Config) ->
181 {200, Headers, Body} = do_get(Transport, Protocol, "/",
182 [{<<"accept-encoding">>, <<"gzip">>}], Config),
183 {_, <<"gzip">>} = lists:keyfind(<<"content-encoding">>, 1, Headers),
184 _ = zlib:gunzip(Body),
185 ok.
186
187 %% Cookie.
188
189 cookie(Config) ->
190 doc("Cookie example."),
191 try
192 do_compile_and_start(cookie, Config),
193 do_cookie(tcp, http, Config),
194 do_cookie(tcp, http2, Config)
195 after
196 do_stop(cookie)
197 end.
198
199 do_cookie(Transport, Protocol, Config) ->
200 {200, _, One} = do_get(Transport, Protocol, "/", Config),
201 {200, _, Two} = do_get(Transport, Protocol, "/", [{<<"cookie">>, <<"server=abcdef">>}], Config),
202 true = One =/= Two,
203 ok.
204
205 %% Echo GET.
206
207 echo_get(Config) ->
208 doc("GET parameter echo example."),
209 try
210 do_compile_and_start(echo_get, Config),
211 do_echo_get(tcp, http, Config),
212 do_echo_get(tcp, http2, Config)
213 after
214 do_stop(echo_get)
215 end.
216
217 do_echo_get(Transport, Protocol, Config) ->
218 {200, _, <<"this is fun">>} = do_get(Transport, Protocol, "/?echo=this+is+fun", Config),
219 {400, _, _} = do_get(Transport, Protocol, "/", Config),
220 ok.
221
222 %% Echo POST.
223
224 echo_post(Config) ->
225 doc("POST parameter echo example."),
226 try
227 do_compile_and_start(echo_post, Config),
228 do_echo_post(tcp, http, Config),
229 do_echo_post(tcp, http2, Config)
230 after
231 do_stop(echo_post)
232 end.
233
234 do_echo_post(Transport, Protocol, Config) ->
235 ConnPid = gun_open([{port, 8080}, {type, Transport}, {protocol, Protocol}|Config]),
236 Ref = gun:post(ConnPid, "/", [
237 {<<"content-type">>, <<"application/octet-stream">>}
238 ], <<"echo=this+is+fun">>),
239 {response, nofin, 200, _} = gun:await(ConnPid, Ref),
240 {ok, <<"this is fun">>} = gun:await_body(ConnPid, Ref),
241 ok.
242
243 %% Eventsource.
244
245 eventsource(Config) ->
246 doc("Eventsource example."),
247 try
248 do_compile_and_start(eventsource, Config),
249 do_eventsource(tcp, http, Config),
250 do_eventsource(tcp, http2, Config)
251 after
252 do_stop(eventsource)
253 end.
254
255 do_eventsource(Transport, Protocol, Config) ->
256 ConnPid = gun_open([{port, 8080}, {type, Transport}, {protocol, Protocol}|Config]),
257 Ref = gun:get(ConnPid, "/eventsource"),
258 {response, nofin, 200, Headers} = gun:await(ConnPid, Ref),
259 {_, <<"text/event-stream">>} = lists:keyfind(<<"content-type">>, 1, Headers),
260 %% Receive a few events.
261 {data, nofin, << "id: ", _/bits >>} = gun:await(ConnPid, Ref, 2000),
262 {data, nofin, << "id: ", _/bits >>} = gun:await(ConnPid, Ref, 2000),
263 {data, nofin, << "id: ", _/bits >>} = gun:await(ConnPid, Ref, 2000),
264 gun:close(ConnPid).
265
266 %% REST Hello World.
267
268 rest_hello_world(Config) ->
269 doc("REST Hello World example."),
270 try
271 do_compile_and_start(rest_hello_world, Config),
272 do_rest_hello_world(tcp, http, Config),
273 do_rest_hello_world(tcp, http2, Config)
274 after
275 do_stop(rest_hello_world)
276 end.
277
278 do_rest_hello_world(Transport, Protocol, Config) ->
279 << "<html>", _/bits >> = do_rest_get(Transport, Protocol,
280 "/", undefined, undefined, Config),
281 << "REST Hello World as text!" >> = do_rest_get(Transport, Protocol,
282 "/", <<"text/plain">>, undefined, Config),
283 << "{\"rest\": \"Hello World!\"}" >> = do_rest_get(Transport, Protocol,
284 "/", <<"application/json">>, undefined, Config),
285 not_acceptable = do_rest_get(Transport, Protocol,
286 "/", <<"text/css">>, undefined, Config),
287 ok.
288
289 do_rest_get(Transport, Protocol, Path, Accept, Auth, Config) ->
290 ReqHeaders0 = case Accept of
291 undefined -> [];
292 _ -> [{<<"accept">>, Accept}]
293 end,
294 ReqHeaders = case Auth of
295 undefined -> ReqHeaders0;
296 _ -> [{<<"authorization">>, [<<"Basic ">>, base64:encode(Auth)]}|ReqHeaders0]
297 end,
298 case do_get(Transport, Protocol, Path, ReqHeaders, Config) of
299 {200, RespHeaders, Body} ->
300 Accept = case Accept of
301 undefined -> undefined;
302 _ ->
303 {_, ContentType} = lists:keyfind(<<"content-type">>, 1, RespHeaders),
304 ContentType
305 end,
306 Body;
307 {401, _, _} ->
308 unauthorized;
309 {406, _, _} ->
310 not_acceptable
311 end.
312
313 %% REST basic auth.
314
315 rest_basic_auth(Config) ->
316 doc("REST basic authorization example."),
317 try
318 do_compile_and_start(rest_basic_auth, Config),
319 do_rest_basic_auth(tcp, http, Config),
320 do_rest_basic_auth(tcp, http2, Config)
321 after
322 do_stop(rest_basic_auth)
323 end.
324
325 do_rest_basic_auth(Transport, Protocol, Config) ->
326 unauthorized = do_rest_get(Transport, Protocol, "/", undefined, undefined, Config),
327 <<"Hello, Alladin!\n">> = do_rest_get(Transport, Protocol, "/", undefined, "Alladin:open sesame", Config),
328 ok.
329
330 %% REST pastebin.
331
332 rest_pastebin(Config) ->
333 doc("REST pastebin example."),
334 try
335 do_compile_and_start(rest_pastebin, Config),
336 do_rest_pastebin(tcp, http, Config),
337 do_rest_pastebin(tcp, http2, Config)
338 after
339 do_stop(rest_pastebin)
340 end.
341
342 do_rest_pastebin(Transport, Protocol, Config) ->
343 %% Existing files.
344 _ = do_rest_get(Transport, Protocol, "/", <<"text/html">>, undefined, Config),
345 _ = do_rest_get(Transport, Protocol, "/", <<"text/plain">>, undefined, Config),
346 %% Use POST to upload a new file and download it back.
347 ConnPid = gun_open([{port, 8080}, {type, Transport}, {protocol, Protocol}|Config]),
348 Ref = gun:post(ConnPid, "/", [
349 {<<"content-type">>, <<"application/x-www-form-urlencoded">>}
350 ], <<"paste=this+is+fun">>),
351 %% @todo Not too happy about 303 here,
352 %% will need to revisit this example.
353 {response, _, 303, Headers} = gun:await(ConnPid, Ref),
354 {_, Location} = lists:keyfind(<<"location">>, 1, Headers),
355 <<"this is fun">> = do_rest_get(Transport, Protocol, Location, <<"text/plain">>, undefined, Config),
356 << "<!DOCTYPE html><html>", _/bits >>
357 = do_rest_get(Transport, Protocol, Location, <<"text/html">>, undefined, Config),
358 ok.
359
360 %% File server.
361
362 file_server(Config) ->
363 doc("File server example with directory listing."),
364 try
365 do_compile_and_start(file_server, Config),
366 do_file_server(tcp, http, Config),
367 do_file_server(tcp, http2, Config)
368 after
369 do_stop(file_server)
370 end.
371
372 do_file_server(Transport, Protocol, Config) ->
373 %% Directory.
374 {200, DirHeaders, <<"<!DOCTYPE html><html>", _/bits >>} = do_get(Transport, Protocol, "/", Config),
375 {_, <<"text/html; charset=utf-8">>} = lists:keyfind(<<"content-type">>, 1, DirHeaders),
376 _ = do_rest_get(Transport, Protocol, "/", <<"application/json">>, undefined, Config),
377 %% Files.
378 {200, _, _} = do_get(Transport, Protocol, "/small.mp4", Config),
379 {200, _, _} = do_get(Transport, Protocol, "/small.ogv", Config),
380 {200, _, _} = do_get(Transport, Protocol, "/test.txt", Config),
381 {200, _, _} = do_get(Transport, Protocol, "/video.html", Config),
382 {200, _, _} = do_get(Transport, Protocol,
383 ["/", cow_uri:urlencode(<<"中文"/utf8>>), "/", cow_uri:urlencode(<<"中文.html"/utf8>>)],
384 Config),
385 ok.
386
387 %% Markdown middleware.
388
389 markdown_middleware(Config) ->
390 doc("Markdown middleware example."),
391 try
392 do_compile_and_start(markdown_middleware, Config),
393 do_markdown_middleware(tcp, http, Config),
394 do_markdown_middleware(tcp, http2, Config)
395 after
396 do_stop(markdown_middleware)
397 end.
398
399 do_markdown_middleware(Transport, Protocol, Config) ->
400 {200, Headers, <<"<h1>", _/bits >>} = do_get(Transport, Protocol, "/video.html", Config),
401 {_, <<"text/html">>} = lists:keyfind(<<"content-type">>, 1, Headers),
402 ok.
403
404 %% Upload.
405
406 upload(Config) ->
407 doc("Upload example."),
408 try
409 do_compile_and_start(upload, Config),
410 do_upload(tcp, http, Config),
411 do_upload(tcp, http2, Config)
412 after
413 do_stop(upload)
414 end.
415
416 do_upload(Transport, Protocol, Config) ->
417 {200, _, << "<html>", _/bits >>} = do_get(Transport, Protocol, "/", Config),
418 %% Use POST to upload a file using multipart.
419 ConnPid = gun_open([{port, 8080}, {type, Transport}, {protocol, Protocol}|Config]),
420 Ref = gun:post(ConnPid, "/upload", [
421 {<<"content-type">>, <<"multipart/form-data;boundary=deadbeef">>}
422 ], <<
423 "--deadbeef\r\n"
424 "Content-Disposition: form-data; name=\"inputfile\"; filename=\"test.txt\"\r\n"
425 "Content-Type: text/plain\r\n"
426 "\r\n"
427 "Cowboy upload example!\r\n"
428 "--deadbeef--">>),
429 {response, fin, 204, _} = gun:await(ConnPid, Ref),
430 ok.
431
432 %% Websocket.
433
434 websocket(Config) ->
435 doc("Websocket example."),
436 try
437 do_compile_and_start(websocket, Config),
438 %% We can only initiate a Websocket connection from HTTP/1.1.
439 {ok, Pid} = gun:open("127.0.0.1", 8080, #{protocols => [http], retry => 0}),
440 {ok, http} = gun:await_up(Pid),
441 _ = monitor(process, Pid),
442 StreamRef = gun:ws_upgrade(Pid, "/websocket", [], #{compress => true}),
443 receive
444 {gun_upgrade, Pid, StreamRef, _, _} ->
445 ok;
446 Msg1 ->
447 exit({connection_failed, Msg1})
448 end,
449 %% Check that we receive the message sent on timer on init.
450 receive
451 {gun_ws, Pid, StreamRef, {text, <<"Hello!">>}} ->
452 ok
453 after 2000 ->
454 exit(timeout)
455 end,
456 %% Check that we receive subsequent messages sent on timer.
457 receive
458 {gun_ws, Pid, StreamRef, {text, <<"How' you doin'?">>}} ->
459 ok
460 after 2000 ->
461 exit(timeout)
462 end,
463 %% Check that we receive the echoed message.
464 gun:ws_send(Pid, StreamRef, {text, <<"hello">>}),
465 receive
466 {gun_ws, Pid, StreamRef, {text, <<"That's what she said! hello">>}} ->
467 ok
468 after 500 ->
469 exit(timeout)
470 end,
471 gun:ws_send(Pid, StreamRef, close)
472 after
473 do_stop(websocket)
474 end.