examples_SUITE.erl 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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. %% Cookie.
  130. cookie(Config) ->
  131. doc("Cookie example."),
  132. try
  133. do_compile_and_start(cookie),
  134. do_cookie(tcp, http, Config),
  135. do_cookie(tcp, http2, Config)
  136. after
  137. do_stop(cookie)
  138. end.
  139. do_cookie(Transport, Protocol, Config) ->
  140. {200, _, One} = do_get(Transport, Protocol, "/", Config),
  141. {200, _, Two} = do_get(Transport, Protocol, "/", [{<<"cookie">>, <<"server=abcdef">>}], Config),
  142. true = One =/= Two,
  143. ok.
  144. %% Echo GET.
  145. echo_get(Config) ->
  146. doc("GET parameter echo example."),
  147. try
  148. do_compile_and_start(echo_get),
  149. do_echo_get(tcp, http, Config),
  150. do_echo_get(tcp, http2, Config)
  151. after
  152. do_stop(echo_get)
  153. end.
  154. do_echo_get(Transport, Protocol, Config) ->
  155. {200, _, <<"this is fun">>} = do_get(Transport, Protocol, "/?echo=this+is+fun", Config),
  156. {400, _, _} = do_get(Transport, Protocol, "/", Config),
  157. ok.
  158. %% Echo POST.
  159. echo_post(Config) ->
  160. doc("POST parameter echo example."),
  161. try
  162. do_compile_and_start(echo_post),
  163. do_echo_post(tcp, http, Config),
  164. do_echo_post(tcp, http2, Config)
  165. after
  166. do_stop(echo_post)
  167. end.
  168. do_echo_post(Transport, Protocol, Config) ->
  169. ConnPid = gun_open([{port, 8080}, {type, Transport}, {protocol, Protocol}|Config]),
  170. Ref = gun:post(ConnPid, "/", [
  171. {<<"content-type">>, <<"application/octet-stream">>}
  172. ], <<"echo=this+is+fun">>),
  173. {response, nofin, 200, _} = gun:await(ConnPid, Ref),
  174. {ok, <<"this is fun">>} = gun:await_body(ConnPid, Ref),
  175. ok.
  176. %% Eventsource.
  177. eventsource(Config) ->
  178. doc("Eventsource example."),
  179. try
  180. do_compile_and_start(eventsource),
  181. do_eventsource(tcp, http, Config),
  182. do_eventsource(tcp, http2, Config)
  183. after
  184. do_stop(eventsource)
  185. end.
  186. do_eventsource(Transport, Protocol, Config) ->
  187. ConnPid = gun_open([{port, 8080}, {type, Transport}, {protocol, Protocol}|Config]),
  188. Ref = gun:get(ConnPid, "/eventsource"),
  189. {response, nofin, 200, Headers} = gun:await(ConnPid, Ref),
  190. {_, <<"text/event-stream">>} = lists:keyfind(<<"content-type">>, 1, Headers),
  191. %% Receive a few events.
  192. {data, nofin, << "id: ", _/bits >>} = gun:await(ConnPid, Ref, 2000),
  193. {data, nofin, << "id: ", _/bits >>} = gun:await(ConnPid, Ref, 2000),
  194. {data, nofin, << "id: ", _/bits >>} = gun:await(ConnPid, Ref, 2000),
  195. gun:close(ConnPid).
  196. %% REST Hello World.
  197. rest_hello_world(Config) ->
  198. doc("REST Hello World example."),
  199. try
  200. do_compile_and_start(rest_hello_world),
  201. do_rest_hello_world(tcp, http, Config),
  202. do_rest_hello_world(tcp, http2, Config)
  203. after
  204. do_stop(rest_hello_world)
  205. end.
  206. do_rest_hello_world(Transport, Protocol, Config) ->
  207. << "<html>", _/bits >> = do_rest_get(Transport, Protocol,
  208. "/", undefined, undefined, Config),
  209. << "REST Hello World as text!" >> = do_rest_get(Transport, Protocol,
  210. "/", <<"text/plain">>, undefined, Config),
  211. << "{\"rest\": \"Hello World!\"}" >> = do_rest_get(Transport, Protocol,
  212. "/", <<"application/json">>, undefined, Config),
  213. not_acceptable = do_rest_get(Transport, Protocol,
  214. "/", <<"text/css">>, undefined, Config),
  215. ok.
  216. do_rest_get(Transport, Protocol, Path, Accept, Auth, Config) ->
  217. ReqHeaders0 = case Accept of
  218. undefined -> [];
  219. _ -> [{<<"accept">>, Accept}]
  220. end,
  221. ReqHeaders = case Auth of
  222. undefined -> ReqHeaders0;
  223. _ -> [{<<"authorization">>, [<<"Basic ">>, base64:encode(Auth)]}|ReqHeaders0]
  224. end,
  225. case do_get(Transport, Protocol, Path, ReqHeaders, Config) of
  226. {200, RespHeaders, Body} ->
  227. Accept = case Accept of
  228. undefined -> undefined;
  229. _ ->
  230. {_, ContentType} = lists:keyfind(<<"content-type">>, 1, RespHeaders),
  231. ContentType
  232. end,
  233. Body;
  234. {401, _, _} ->
  235. unauthorized;
  236. {406, _, _} ->
  237. not_acceptable
  238. end.
  239. %% REST basic auth.
  240. rest_basic_auth(Config) ->
  241. doc("REST basic authorization example."),
  242. try
  243. do_compile_and_start(rest_basic_auth),
  244. do_rest_basic_auth(tcp, http, Config),
  245. do_rest_basic_auth(tcp, http2, Config)
  246. after
  247. do_stop(rest_basic_auth)
  248. end.
  249. do_rest_basic_auth(Transport, Protocol, Config) ->
  250. unauthorized = do_rest_get(Transport, Protocol, "/", undefined, undefined, Config),
  251. <<"Hello, Alladin!\n">> = do_rest_get(Transport, Protocol, "/", undefined, "Alladin:open sesame", Config),
  252. ok.
  253. %% REST pastebin.
  254. rest_pastebin(Config) ->
  255. doc("REST pastebin example."),
  256. try
  257. do_compile_and_start(rest_pastebin),
  258. do_rest_pastebin(tcp, http, Config),
  259. do_rest_pastebin(tcp, http2, Config)
  260. after
  261. do_stop(rest_pastebin)
  262. end.
  263. do_rest_pastebin(Transport, Protocol, Config) ->
  264. %% Existing files.
  265. _ = do_rest_get(Transport, Protocol, "/", <<"text/html">>, undefined, Config),
  266. _ = do_rest_get(Transport, Protocol, "/", <<"text/plain">>, undefined, Config),
  267. %% Use POST to upload a new file and download it back.
  268. ConnPid = gun_open([{port, 8080}, {type, Transport}, {protocol, Protocol}|Config]),
  269. Ref = gun:post(ConnPid, "/", [
  270. {<<"content-type">>, <<"application/x-www-form-urlencoded">>}
  271. ], <<"paste=this+is+fun">>),
  272. %% @todo Not too happy about 303 here,
  273. %% will need to revisit this example.
  274. {response, _, 303, Headers} = gun:await(ConnPid, Ref),
  275. {_, Location} = lists:keyfind(<<"location">>, 1, Headers),
  276. <<"this is fun">> = do_rest_get(Transport, Protocol, Location, <<"text/plain">>, undefined, Config),
  277. << "<!DOCTYPE html><html>", _/bits >>
  278. = do_rest_get(Transport, Protocol, Location, <<"text/html">>, undefined, Config),
  279. ok.
  280. %% File server.
  281. file_server(Config) ->
  282. doc("File server example with directory listing."),
  283. try
  284. do_compile_and_start(file_server),
  285. do_file_server(tcp, http, Config),
  286. do_file_server(tcp, http2, Config)
  287. after
  288. do_stop(file_server)
  289. end.
  290. do_file_server(Transport, Protocol, Config) ->
  291. %% Directory.
  292. {200, DirHeaders, <<"<!DOCTYPE html><html>", _/bits >>} = do_get(Transport, Protocol, "/", Config),
  293. {_, <<"text/html">>} = lists:keyfind(<<"content-type">>, 1, DirHeaders),
  294. _ = do_rest_get(Transport, Protocol, "/", <<"application/json">>, undefined, Config),
  295. %% Files.
  296. {200, _, _} = do_get(Transport, Protocol, "/small.mp4", Config),
  297. {200, _, _} = do_get(Transport, Protocol, "/small.ogv", Config),
  298. {200, _, _} = do_get(Transport, Protocol, "/test.txt", Config),
  299. {200, _, _} = do_get(Transport, Protocol, "/video.html", Config),
  300. ok.
  301. %% Markdown middleware.
  302. markdown_middleware(Config) ->
  303. doc("Markdown middleware example."),
  304. try
  305. do_compile_and_start(markdown_middleware),
  306. do_markdown_middleware(tcp, http, Config),
  307. do_markdown_middleware(tcp, http2, Config)
  308. after
  309. do_stop(markdown_middleware)
  310. end.
  311. do_markdown_middleware(Transport, Protocol, Config) ->
  312. {200, Headers, <<"<h1>", _/bits >>} = do_get(Transport, Protocol, "/video.html", Config),
  313. {_, <<"text/html">>} = lists:keyfind(<<"content-type">>, 1, Headers),
  314. ok.
  315. %% Upload.
  316. upload(Config) ->
  317. doc("Upload example."),
  318. try
  319. do_compile_and_start(upload),
  320. do_upload(tcp, http, Config),
  321. do_upload(tcp, http2, Config)
  322. after
  323. do_stop(upload)
  324. end.
  325. do_upload(Transport, Protocol, Config) ->
  326. {200, _, << "<html>", _/bits >>} = do_get(Transport, Protocol, "/", Config),
  327. %% Use POST to upload a file using multipart.
  328. ConnPid = gun_open([{port, 8080}, {type, Transport}, {protocol, Protocol}|Config]),
  329. Ref = gun:post(ConnPid, "/upload", [
  330. {<<"content-type">>, <<"multipart/form-data;boundary=deadbeef">>}
  331. ], <<
  332. "--deadbeef\r\n"
  333. "Content-Disposition: form-data; name=\"inputfile\"; filename=\"test.txt\"\r\n"
  334. "Content-Type: text/plain\r\n"
  335. "\r\n"
  336. "Cowboy upload example!\r\n"
  337. "--deadbeef--">>),
  338. {response, fin, 204, _} = gun:await(ConnPid, Ref),
  339. ok.
  340. %% Websocket.
  341. websocket(_) ->
  342. doc("Websocket example."),
  343. try
  344. do_compile_and_start(websocket),
  345. %% We can only initiate a Websocket connection from HTTP/1.1.
  346. {ok, Pid} = gun:open("127.0.0.1", 8080, #{protocols => [http], retry => 0}),
  347. {ok, http} = gun:await_up(Pid),
  348. _ = monitor(process, Pid),
  349. gun:ws_upgrade(Pid, "/websocket", [], #{compress => true}),
  350. receive
  351. {gun_ws_upgrade, Pid, ok, _} ->
  352. ok;
  353. Msg1 ->
  354. exit({connection_failed, Msg1})
  355. end,
  356. %% Check that we receive the message sent on timer on init.
  357. receive
  358. {gun_ws, Pid, {text, <<"Hello!">>}} ->
  359. ok
  360. after 2000 ->
  361. exit(timeout)
  362. end,
  363. %% Check that we receive subsequent messages sent on timer.
  364. receive
  365. {gun_ws, Pid, {text, <<"How' you doin'?">>}} ->
  366. ok
  367. after 2000 ->
  368. exit(timeout)
  369. end,
  370. %% Check that we receive the echoed message.
  371. gun:ws_send(Pid, {text, <<"hello">>}),
  372. receive
  373. {gun_ws, Pid, {text, <<"That's what she said! hello">>}} ->
  374. ok
  375. after 500 ->
  376. exit(timeout)
  377. end,
  378. gun:ws_send(Pid, close)
  379. after
  380. do_stop(websocket)
  381. end.