examples_SUITE.erl 12 KB

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