examples_SUITE.erl 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. %% Copyright (c) 2016-2017, Loïc Hoguin <essen@ninenines.eu>
  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. -module(examples_SUITE).
  15. -compile(export_all).
  16. -import(ct_helper, [config/2]).
  17. -import(ct_helper, [doc/1]).
  18. -import(cowboy_test, [gun_open/1]).
  19. %% ct.
  20. all() ->
  21. ct_helper:all(?MODULE).
  22. %% Remove environment variables inherited from Erlang.mk.
  23. init_per_suite(Config) ->
  24. os:unsetenv("ERLANG_MK_TMP"),
  25. os:unsetenv("APPS_DIR"),
  26. os:unsetenv("DEPS_DIR"),
  27. os:unsetenv("ERL_LIBS"),
  28. Config.
  29. end_per_suite(_) ->
  30. ok.
  31. %% Find GNU Make.
  32. do_find_make_cmd() ->
  33. case os:getenv("MAKE") of
  34. false ->
  35. case os:find_executable("gmake") of
  36. false -> "make";
  37. Cmd -> Cmd
  38. end;
  39. Cmd ->
  40. Cmd
  41. end.
  42. %% Compile, start and stop releases.
  43. do_get_paths(Example0) ->
  44. Example = atom_to_list(Example0),
  45. {ok, CWD} = file:get_cwd(),
  46. Dir = CWD ++ "/../../examples/" ++ Example,
  47. Rel = Dir ++ "/_rel/" ++ Example ++ "_example/bin/" ++ Example ++ "_example",
  48. Log = Dir ++ "/_rel/" ++ Example ++ "_example/log/erlang.log.1",
  49. {Dir, Rel, Log}.
  50. do_compile_and_start(Example) ->
  51. Make = do_find_make_cmd(),
  52. {Dir, Rel, _} = do_get_paths(Example),
  53. %% TERM=dumb disables relx coloring.
  54. ct:log("~s~n", [os:cmd("cd " ++ Dir ++ " && " ++ Make ++ " distclean && " ++ Make ++ " all TERM=dumb")]),
  55. ct:log("~s~n", [os:cmd(Rel ++ " stop")]),
  56. ct:log("~s~n", [os:cmd(Rel ++ " start")]),
  57. timer:sleep(2000),
  58. ok.
  59. do_stop(Example) ->
  60. {_, Rel, Log} = do_get_paths(Example),
  61. ct:log("~s~n", [os:cmd(Rel ++ " stop")]),
  62. ct:log("~s~n", [element(2, file:read_file(Log))]),
  63. ok.
  64. %% Fetch a response.
  65. do_get(Transport, Protocol, Path, Config) ->
  66. do_get(Transport, Protocol, Path, [], Config).
  67. do_get(Transport, Protocol, Path, ReqHeaders, Config) ->
  68. Port = case Transport of
  69. tcp -> 8080;
  70. ssl -> 8443
  71. end,
  72. ConnPid = gun_open([{port, Port}, {type, Transport}, {protocol, Protocol}|Config]),
  73. Ref = gun:get(ConnPid, Path, ReqHeaders),
  74. case gun:await(ConnPid, Ref) of
  75. {response, nofin, Status, RespHeaders} ->
  76. {ok, Body} = gun:await_body(ConnPid, Ref),
  77. {Status, RespHeaders, Body};
  78. {response, fin, Status, RespHeaders} ->
  79. {Status, RespHeaders, <<>>}
  80. end.
  81. %% TCP and SSL Hello World.
  82. hello_world(Config) ->
  83. doc("Hello World example."),
  84. try
  85. do_compile_and_start(hello_world),
  86. do_hello_world(tcp, http, Config),
  87. do_hello_world(tcp, http2, Config)
  88. after
  89. do_stop(hello_world)
  90. end.
  91. ssl_hello_world(Config) ->
  92. doc("SSL Hello World example."),
  93. try
  94. do_compile_and_start(ssl_hello_world),
  95. do_hello_world(ssl, http, Config),
  96. do_hello_world(ssl, http2, Config)
  97. after
  98. do_stop(ssl_hello_world)
  99. end.
  100. do_hello_world(Transport, Protocol, Config) ->
  101. {200, _, <<"Hello world!">>} = do_get(Transport, Protocol, "/", Config),
  102. ok.
  103. %% Chunked Hello World.
  104. chunked_hello_world(Config) ->
  105. doc("Chunked Hello World example."),
  106. try
  107. do_compile_and_start(chunked_hello_world),
  108. do_chunked_hello_world(tcp, http, Config),
  109. do_chunked_hello_world(tcp, http2, Config)
  110. after
  111. do_stop(chunked_hello_world)
  112. end.
  113. do_chunked_hello_world(Transport, Protocol, Config) ->
  114. ConnPid = gun_open([{port, 8080}, {type, Transport}, {protocol, Protocol}|Config]),
  115. Ref = gun:get(ConnPid, "/"),
  116. {response, nofin, 200, _} = gun:await(ConnPid, Ref),
  117. %% We expect to receive a chunk every second, three total.
  118. {data, nofin, <<"Hello\r\n">>} = gun:await(ConnPid, Ref, 2000),
  119. {data, nofin, <<"World\r\n">>} = gun:await(ConnPid, Ref, 2000),
  120. {data, IsFin, <<"Chunked!\r\n">>} = gun:await(ConnPid, Ref, 2000),
  121. %% We may get an extra empty chunk (last chunk for HTTP/1.1,
  122. %% empty DATA frame with the FIN bit set for HTTP/2).
  123. case IsFin of
  124. fin -> ok;
  125. nofin ->
  126. {data, fin, <<>>} = gun:await(ConnPid, Ref, 500),
  127. ok
  128. end.
  129. %% Compressed responses.
  130. compress_response(Config) ->
  131. doc("Compressed response example."),
  132. try
  133. do_compile_and_start(compress_response),
  134. do_compress_response(tcp, http, Config),
  135. do_compress_response(tcp, http2, Config)
  136. after
  137. do_stop(compress_response)
  138. end.
  139. do_compress_response(Transport, Protocol, Config) ->
  140. {200, Headers, Body} = do_get(Transport, Protocol, "/",
  141. [{<<"accept-encoding">>, <<"gzip">>}], Config),
  142. {_, <<"gzip">>} = lists:keyfind(<<"content-encoding">>, 1, Headers),
  143. _ = zlib:gunzip(Body),
  144. ok.
  145. %% Cookie.
  146. cookie(Config) ->
  147. doc("Cookie example."),
  148. try
  149. do_compile_and_start(cookie),
  150. do_cookie(tcp, http, Config),
  151. do_cookie(tcp, http2, Config)
  152. after
  153. do_stop(cookie)
  154. end.
  155. do_cookie(Transport, Protocol, Config) ->
  156. {200, _, One} = do_get(Transport, Protocol, "/", Config),
  157. {200, _, Two} = do_get(Transport, Protocol, "/", [{<<"cookie">>, <<"server=abcdef">>}], Config),
  158. true = One =/= Two,
  159. ok.
  160. %% Echo GET.
  161. echo_get(Config) ->
  162. doc("GET parameter echo example."),
  163. try
  164. do_compile_and_start(echo_get),
  165. do_echo_get(tcp, http, Config),
  166. do_echo_get(tcp, http2, Config)
  167. after
  168. do_stop(echo_get)
  169. end.
  170. do_echo_get(Transport, Protocol, Config) ->
  171. {200, _, <<"this is fun">>} = do_get(Transport, Protocol, "/?echo=this+is+fun", Config),
  172. {400, _, _} = do_get(Transport, Protocol, "/", Config),
  173. ok.
  174. %% Echo POST.
  175. echo_post(Config) ->
  176. doc("POST parameter echo example."),
  177. try
  178. do_compile_and_start(echo_post),
  179. do_echo_post(tcp, http, Config),
  180. do_echo_post(tcp, http2, Config)
  181. after
  182. do_stop(echo_post)
  183. end.
  184. do_echo_post(Transport, Protocol, Config) ->
  185. ConnPid = gun_open([{port, 8080}, {type, Transport}, {protocol, Protocol}|Config]),
  186. Ref = gun:post(ConnPid, "/", [
  187. {<<"content-type">>, <<"application/octet-stream">>}
  188. ], <<"echo=this+is+fun">>),
  189. {response, nofin, 200, _} = gun:await(ConnPid, Ref),
  190. {ok, <<"this is fun">>} = gun:await_body(ConnPid, Ref),
  191. ok.
  192. %% Eventsource.
  193. eventsource(Config) ->
  194. doc("Eventsource example."),
  195. try
  196. do_compile_and_start(eventsource),
  197. do_eventsource(tcp, http, Config),
  198. do_eventsource(tcp, http2, Config)
  199. after
  200. do_stop(eventsource)
  201. end.
  202. do_eventsource(Transport, Protocol, Config) ->
  203. ConnPid = gun_open([{port, 8080}, {type, Transport}, {protocol, Protocol}|Config]),
  204. Ref = gun:get(ConnPid, "/eventsource"),
  205. {response, nofin, 200, Headers} = gun:await(ConnPid, Ref),
  206. {_, <<"text/event-stream">>} = lists:keyfind(<<"content-type">>, 1, Headers),
  207. %% Receive a few events.
  208. {data, nofin, << "id: ", _/bits >>} = gun:await(ConnPid, Ref, 2000),
  209. {data, nofin, << "id: ", _/bits >>} = gun:await(ConnPid, Ref, 2000),
  210. {data, nofin, << "id: ", _/bits >>} = gun:await(ConnPid, Ref, 2000),
  211. gun:close(ConnPid).
  212. %% REST Hello World.
  213. rest_hello_world(Config) ->
  214. doc("REST Hello World example."),
  215. try
  216. do_compile_and_start(rest_hello_world),
  217. do_rest_hello_world(tcp, http, Config),
  218. do_rest_hello_world(tcp, http2, Config)
  219. after
  220. do_stop(rest_hello_world)
  221. end.
  222. do_rest_hello_world(Transport, Protocol, Config) ->
  223. << "<html>", _/bits >> = do_rest_get(Transport, Protocol,
  224. "/", undefined, undefined, Config),
  225. << "REST Hello World as text!" >> = do_rest_get(Transport, Protocol,
  226. "/", <<"text/plain">>, undefined, Config),
  227. << "{\"rest\": \"Hello World!\"}" >> = do_rest_get(Transport, Protocol,
  228. "/", <<"application/json">>, undefined, Config),
  229. not_acceptable = do_rest_get(Transport, Protocol,
  230. "/", <<"text/css">>, undefined, Config),
  231. ok.
  232. do_rest_get(Transport, Protocol, Path, Accept, Auth, Config) ->
  233. ReqHeaders0 = case Accept of
  234. undefined -> [];
  235. _ -> [{<<"accept">>, Accept}]
  236. end,
  237. ReqHeaders = case Auth of
  238. undefined -> ReqHeaders0;
  239. _ -> [{<<"authorization">>, [<<"Basic ">>, base64:encode(Auth)]}|ReqHeaders0]
  240. end,
  241. case do_get(Transport, Protocol, Path, ReqHeaders, Config) of
  242. {200, RespHeaders, Body} ->
  243. Accept = case Accept of
  244. undefined -> undefined;
  245. _ ->
  246. {_, ContentType} = lists:keyfind(<<"content-type">>, 1, RespHeaders),
  247. ContentType
  248. end,
  249. Body;
  250. {401, _, _} ->
  251. unauthorized;
  252. {406, _, _} ->
  253. not_acceptable
  254. end.
  255. %% REST basic auth.
  256. rest_basic_auth(Config) ->
  257. doc("REST basic authorization example."),
  258. try
  259. do_compile_and_start(rest_basic_auth),
  260. do_rest_basic_auth(tcp, http, Config),
  261. do_rest_basic_auth(tcp, http2, Config)
  262. after
  263. do_stop(rest_basic_auth)
  264. end.
  265. do_rest_basic_auth(Transport, Protocol, Config) ->
  266. unauthorized = do_rest_get(Transport, Protocol, "/", undefined, undefined, Config),
  267. <<"Hello, Alladin!\n">> = do_rest_get(Transport, Protocol, "/", undefined, "Alladin:open sesame", Config),
  268. ok.
  269. %% REST pastebin.
  270. rest_pastebin(Config) ->
  271. doc("REST pastebin example."),
  272. try
  273. do_compile_and_start(rest_pastebin),
  274. do_rest_pastebin(tcp, http, Config),
  275. do_rest_pastebin(tcp, http2, Config)
  276. after
  277. do_stop(rest_pastebin)
  278. end.
  279. do_rest_pastebin(Transport, Protocol, Config) ->
  280. %% Existing files.
  281. _ = do_rest_get(Transport, Protocol, "/", <<"text/html">>, undefined, Config),
  282. _ = do_rest_get(Transport, Protocol, "/", <<"text/plain">>, undefined, Config),
  283. %% Use POST to upload a new file and download it back.
  284. ConnPid = gun_open([{port, 8080}, {type, Transport}, {protocol, Protocol}|Config]),
  285. Ref = gun:post(ConnPid, "/", [
  286. {<<"content-type">>, <<"application/x-www-form-urlencoded">>}
  287. ], <<"paste=this+is+fun">>),
  288. %% @todo Not too happy about 303 here,
  289. %% will need to revisit this example.
  290. {response, _, 303, Headers} = gun:await(ConnPid, Ref),
  291. {_, Location} = lists:keyfind(<<"location">>, 1, Headers),
  292. <<"this is fun">> = do_rest_get(Transport, Protocol, Location, <<"text/plain">>, undefined, Config),
  293. << "<!DOCTYPE html><html>", _/bits >>
  294. = do_rest_get(Transport, Protocol, Location, <<"text/html">>, undefined, Config),
  295. ok.
  296. %% File server.
  297. file_server(Config) ->
  298. doc("File server example with directory listing."),
  299. try
  300. do_compile_and_start(file_server),
  301. do_file_server(tcp, http, Config),
  302. do_file_server(tcp, http2, Config)
  303. after
  304. do_stop(file_server)
  305. end.
  306. do_file_server(Transport, Protocol, Config) ->
  307. %% Directory.
  308. {200, DirHeaders, <<"<!DOCTYPE html><html>", _/bits >>} = do_get(Transport, Protocol, "/", Config),
  309. {_, <<"text/html">>} = lists:keyfind(<<"content-type">>, 1, DirHeaders),
  310. _ = do_rest_get(Transport, Protocol, "/", <<"application/json">>, undefined, Config),
  311. %% Files.
  312. {200, _, _} = do_get(Transport, Protocol, "/small.mp4", Config),
  313. {200, _, _} = do_get(Transport, Protocol, "/small.ogv", Config),
  314. {200, _, _} = do_get(Transport, Protocol, "/test.txt", Config),
  315. {200, _, _} = do_get(Transport, Protocol, "/video.html", Config),
  316. ok.
  317. %% Markdown middleware.
  318. markdown_middleware(Config) ->
  319. doc("Markdown middleware example."),
  320. try
  321. do_compile_and_start(markdown_middleware),
  322. do_markdown_middleware(tcp, http, Config),
  323. do_markdown_middleware(tcp, http2, Config)
  324. after
  325. do_stop(markdown_middleware)
  326. end.
  327. do_markdown_middleware(Transport, Protocol, Config) ->
  328. {200, Headers, <<"<h1>", _/bits >>} = do_get(Transport, Protocol, "/video.html", Config),
  329. {_, <<"text/html">>} = lists:keyfind(<<"content-type">>, 1, Headers),
  330. ok.
  331. %% Upload.
  332. upload(Config) ->
  333. doc("Upload example."),
  334. try
  335. do_compile_and_start(upload),
  336. do_upload(tcp, http, Config),
  337. do_upload(tcp, http2, Config)
  338. after
  339. do_stop(upload)
  340. end.
  341. do_upload(Transport, Protocol, Config) ->
  342. {200, _, << "<html>", _/bits >>} = do_get(Transport, Protocol, "/", Config),
  343. %% Use POST to upload a file using multipart.
  344. ConnPid = gun_open([{port, 8080}, {type, Transport}, {protocol, Protocol}|Config]),
  345. Ref = gun:post(ConnPid, "/upload", [
  346. {<<"content-type">>, <<"multipart/form-data;boundary=deadbeef">>}
  347. ], <<
  348. "--deadbeef\r\n"
  349. "Content-Disposition: form-data; name=\"inputfile\"; filename=\"test.txt\"\r\n"
  350. "Content-Type: text/plain\r\n"
  351. "\r\n"
  352. "Cowboy upload example!\r\n"
  353. "--deadbeef--">>),
  354. {response, fin, 204, _} = gun:await(ConnPid, Ref),
  355. ok.
  356. %% Websocket.
  357. websocket(_) ->
  358. doc("Websocket example."),
  359. try
  360. do_compile_and_start(websocket),
  361. %% We can only initiate a Websocket connection from HTTP/1.1.
  362. {ok, Pid} = gun:open("127.0.0.1", 8080, #{protocols => [http], retry => 0}),
  363. {ok, http} = gun:await_up(Pid),
  364. _ = monitor(process, Pid),
  365. gun:ws_upgrade(Pid, "/websocket", [], #{compress => true}),
  366. receive
  367. {gun_ws_upgrade, Pid, ok, _} ->
  368. ok;
  369. Msg1 ->
  370. exit({connection_failed, Msg1})
  371. end,
  372. %% Check that we receive the message sent on timer on init.
  373. receive
  374. {gun_ws, Pid, {text, <<"Hello!">>}} ->
  375. ok
  376. after 2000 ->
  377. exit(timeout)
  378. end,
  379. %% Check that we receive subsequent messages sent on timer.
  380. receive
  381. {gun_ws, Pid, {text, <<"How' you doin'?">>}} ->
  382. ok
  383. after 2000 ->
  384. exit(timeout)
  385. end,
  386. %% Check that we receive the echoed message.
  387. gun:ws_send(Pid, {text, <<"hello">>}),
  388. receive
  389. {gun_ws, Pid, {text, <<"That's what she said! hello">>}} ->
  390. ok
  391. after 500 ->
  392. exit(timeout)
  393. end,
  394. gun:ws_send(Pid, close)
  395. after
  396. do_stop(websocket)
  397. end.