25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

821 lines
30 KiB

13 년 전
11 년 전
14 년 전
14 년 전
14 년 전
14 년 전
14 년 전
14 년 전
14 년 전
14 년 전
14 년 전
14 년 전
14 년 전
14 년 전
14 년 전
13 년 전
13 년 전
13 년 전
11 년 전
  1. %%% File : ibrowse_test.erl
  2. %%% Author : Chandrashekhar Mullaparthi <chandrashekhar.mullaparthi@t-mobile.co.uk>
  3. %%% Description : Test ibrowse
  4. %%% Created : 14 Oct 2003 by Chandrashekhar Mullaparthi <chandrashekhar.mullaparthi@t-mobile.co.uk>
  5. -module(ibrowse_test).
  6. -export([
  7. load_test/3,
  8. send_reqs_1/3,
  9. do_send_req/2,
  10. local_unit_tests/0,
  11. unit_tests/0,
  12. unit_tests/2,
  13. unit_tests_1/3,
  14. ue_test/0,
  15. ue_test/1,
  16. verify_chunked_streaming/0,
  17. verify_chunked_streaming/1,
  18. test_chunked_streaming_once/0,
  19. i_do_async_req_list/4,
  20. test_stream_once/3,
  21. test_stream_once/4,
  22. test_20122010/0,
  23. test_20122010/1,
  24. test_pipeline_head_timeout/0,
  25. test_pipeline_head_timeout/1,
  26. do_test_pipeline_head_timeout/4,
  27. test_head_transfer_encoding/0,
  28. test_head_transfer_encoding/1,
  29. test_head_response_with_body/0,
  30. test_head_response_with_body/1,
  31. test_303_response_with_no_body/0,
  32. test_303_response_with_no_body/1,
  33. test_303_response_with_a_body/0,
  34. test_303_response_with_a_body/1,
  35. test_binary_headers/0,
  36. test_binary_headers/1,
  37. test_generate_body_0/0,
  38. test_retry_of_requests/0,
  39. test_retry_of_requests/1
  40. ]).
  41. -include("ibrowse.hrl").
  42. test_stream_once(Url, Method, Options) ->
  43. test_stream_once(Url, Method, Options, 5000).
  44. test_stream_once(Url, Method, Options, Timeout) ->
  45. case ibrowse:send_req(Url, [], Method, [], [{stream_to, {self(), once}} | Options], Timeout) of
  46. {ibrowse_req_id, Req_id} ->
  47. case ibrowse:stream_next(Req_id) of
  48. ok ->
  49. test_stream_once(Req_id);
  50. Err ->
  51. Err
  52. end;
  53. Err ->
  54. Err
  55. end.
  56. test_stream_once(Req_id) ->
  57. receive
  58. {ibrowse_async_headers, Req_id, StatCode, Headers} ->
  59. io:format("Recvd headers~n~p~n", [{ibrowse_async_headers, Req_id, StatCode, Headers}]),
  60. case ibrowse:stream_next(Req_id) of
  61. ok ->
  62. test_stream_once(Req_id);
  63. Err ->
  64. Err
  65. end;
  66. {ibrowse_async_response, Req_id, {error, Err}} ->
  67. io:format("Recvd error: ~p~n", [Err]);
  68. {ibrowse_async_response, Req_id, Body_1} ->
  69. io:format("Recvd body part: ~n~p~n", [{ibrowse_async_response, Req_id, Body_1}]),
  70. case ibrowse:stream_next(Req_id) of
  71. ok ->
  72. test_stream_once(Req_id);
  73. Err ->
  74. Err
  75. end;
  76. {ibrowse_async_response_end, Req_id} ->
  77. ok
  78. end.
  79. %% Use ibrowse:set_max_sessions/3 and ibrowse:set_max_pipeline_size/3 to
  80. %% tweak settings before running the load test. The defaults are 10 and 10.
  81. load_test(Url, NumWorkers, NumReqsPerWorker) when is_list(Url),
  82. is_integer(NumWorkers),
  83. is_integer(NumReqsPerWorker),
  84. NumWorkers > 0,
  85. NumReqsPerWorker > 0 ->
  86. proc_lib:spawn(?MODULE, send_reqs_1, [Url, NumWorkers, NumReqsPerWorker]).
  87. send_reqs_1(Url, NumWorkers, NumReqsPerWorker) ->
  88. Start_time = now(),
  89. ets:new(pid_table, [named_table, public]),
  90. ets:new(ibrowse_test_results, [named_table, public]),
  91. ets:new(ibrowse_errors, [named_table, public, ordered_set]),
  92. ets:new(ibrowse_counter, [named_table, public, ordered_set]),
  93. ets:insert(ibrowse_counter, {req_id, 1}),
  94. init_results(),
  95. process_flag(trap_exit, true),
  96. log_msg("Starting spawning of workers...~n", []),
  97. spawn_workers(Url, NumWorkers, NumReqsPerWorker),
  98. log_msg("Finished spawning workers...~n", []),
  99. do_wait(Url),
  100. End_time = now(),
  101. log_msg("All workers are done...~n", []),
  102. log_msg("ibrowse_test_results table: ~n~p~n", [ets:tab2list(ibrowse_test_results)]),
  103. log_msg("Start time: ~1000.p~n", [calendar:now_to_local_time(Start_time)]),
  104. log_msg("End time : ~1000.p~n", [calendar:now_to_local_time(End_time)]),
  105. Elapsed_time_secs = trunc(timer:now_diff(End_time, Start_time) / 1000000),
  106. log_msg("Elapsed : ~p~n", [Elapsed_time_secs]),
  107. log_msg("Reqs/sec : ~p~n", [round(trunc((NumWorkers*NumReqsPerWorker) / Elapsed_time_secs))]),
  108. dump_errors().
  109. init_results() ->
  110. ets:insert(ibrowse_test_results, {crash, 0}),
  111. ets:insert(ibrowse_test_results, {send_failed, 0}),
  112. ets:insert(ibrowse_test_results, {other_error, 0}),
  113. ets:insert(ibrowse_test_results, {success, 0}),
  114. ets:insert(ibrowse_test_results, {retry_later, 0}),
  115. ets:insert(ibrowse_test_results, {trid_mismatch, 0}),
  116. ets:insert(ibrowse_test_results, {success_no_trid, 0}),
  117. ets:insert(ibrowse_test_results, {failed, 0}),
  118. ets:insert(ibrowse_test_results, {timeout, 0}),
  119. ets:insert(ibrowse_test_results, {req_id, 0}).
  120. spawn_workers(_Url, 0, _) ->
  121. ok;
  122. spawn_workers(Url, NumWorkers, NumReqsPerWorker) ->
  123. Pid = proc_lib:spawn_link(?MODULE, do_send_req, [Url, NumReqsPerWorker]),
  124. ets:insert(pid_table, {Pid, []}),
  125. spawn_workers(Url, NumWorkers - 1, NumReqsPerWorker).
  126. do_wait(Url) ->
  127. receive
  128. {'EXIT', _, normal} ->
  129. catch ibrowse:show_dest_status(Url),
  130. catch ibrowse:show_dest_status(),
  131. do_wait(Url);
  132. {'EXIT', Pid, Reason} ->
  133. ets:delete(pid_table, Pid),
  134. ets:insert(ibrowse_errors, {Pid, Reason}),
  135. ets:update_counter(ibrowse_test_results, crash, 1),
  136. do_wait(Url);
  137. Msg ->
  138. io:format("Recvd unknown message...~p~n", [Msg]),
  139. do_wait(Url)
  140. after 1000 ->
  141. case ets:info(pid_table, size) of
  142. 0 ->
  143. done;
  144. _ ->
  145. catch ibrowse:show_dest_status(Url),
  146. catch ibrowse:show_dest_status(),
  147. do_wait(Url)
  148. end
  149. end.
  150. do_send_req(Url, NumReqs) ->
  151. do_send_req_1(Url, NumReqs).
  152. do_send_req_1(_Url, 0) ->
  153. ets:delete(pid_table, self());
  154. do_send_req_1(Url, NumReqs) ->
  155. Counter = integer_to_list(ets:update_counter(ibrowse_test_results, req_id, 1)),
  156. case ibrowse:send_req(Url, [{"ib_req_id", Counter}], get, [], [], 10000) of
  157. {ok, _Status, Headers, _Body} ->
  158. case lists:keysearch("ib_req_id", 1, Headers) of
  159. {value, {_, Counter}} ->
  160. ets:update_counter(ibrowse_test_results, success, 1);
  161. {value, _} ->
  162. ets:update_counter(ibrowse_test_results, trid_mismatch, 1);
  163. false ->
  164. ets:update_counter(ibrowse_test_results, success_no_trid, 1)
  165. end;
  166. {error, req_timedout} ->
  167. ets:update_counter(ibrowse_test_results, timeout, 1);
  168. {error, send_failed} ->
  169. ets:update_counter(ibrowse_test_results, send_failed, 1);
  170. {error, retry_later} ->
  171. ets:update_counter(ibrowse_test_results, retry_later, 1);
  172. Err ->
  173. ets:insert(ibrowse_errors, {now(), Err}),
  174. ets:update_counter(ibrowse_test_results, other_error, 1),
  175. ok
  176. end,
  177. do_send_req_1(Url, NumReqs-1).
  178. dump_errors() ->
  179. case ets:info(ibrowse_errors, size) of
  180. 0 ->
  181. ok;
  182. _ ->
  183. {A, B, C} = now(),
  184. Filename = lists:flatten(
  185. io_lib:format("ibrowse_errors_~p_~p_~p.txt" , [A, B, C])),
  186. case file:open(Filename, [write, delayed_write, raw]) of
  187. {ok, Iod} ->
  188. dump_errors(ets:first(ibrowse_errors), Iod);
  189. Err ->
  190. io:format("failed to create file ~s. Reason: ~p~n", [Filename, Err]),
  191. ok
  192. end
  193. end.
  194. dump_errors('$end_of_table', Iod) ->
  195. file:close(Iod);
  196. dump_errors(Key, Iod) ->
  197. [{_, Term}] = ets:lookup(ibrowse_errors, Key),
  198. file:write(Iod, io_lib:format("~p~n", [Term])),
  199. dump_errors(ets:next(ibrowse_errors, Key), Iod).
  200. %%------------------------------------------------------------------------------
  201. %% Unit Tests
  202. %%------------------------------------------------------------------------------
  203. -define(LOCAL_TESTS, [
  204. {local_test_fun, test_20122010, []},
  205. {local_test_fun, test_pipeline_head_timeout, []},
  206. {local_test_fun, test_head_transfer_encoding, []},
  207. {local_test_fun, test_head_response_with_body, []},
  208. {local_test_fun, test_303_response_with_a_body, []},
  209. {local_test_fun, test_binary_headers, []},
  210. {local_test_fun, test_retry_of_requests, []}
  211. ]).
  212. -define(TEST_LIST, [{"http://intranet/messenger", get},
  213. {"http://www.google.co.uk", get},
  214. {"http://www.google.com", get},
  215. {"http://www.google.com", options},
  216. {"https://mail.google.com", get},
  217. {"http://www.sun.com", get},
  218. {"http://www.oracle.com", get},
  219. {"http://www.bbc.co.uk", get},
  220. {"http://www.bbc.co.uk", trace},
  221. {"http://www.bbc.co.uk", options},
  222. {"http://yaws.hyber.org", get},
  223. {"http://jigsaw.w3.org/HTTP/ChunkedScript", get},
  224. {"http://jigsaw.w3.org/HTTP/TE/foo.txt", get},
  225. {"http://jigsaw.w3.org/HTTP/TE/bar.txt", get},
  226. {"http://jigsaw.w3.org/HTTP/connection.html", get},
  227. {"http://jigsaw.w3.org/HTTP/cc.html", get},
  228. {"http://jigsaw.w3.org/HTTP/cc-private.html", get},
  229. {"http://jigsaw.w3.org/HTTP/cc-proxy-revalidate.html", get},
  230. {"http://jigsaw.w3.org/HTTP/cc-nocache.html", get},
  231. {"http://jigsaw.w3.org/HTTP/h-content-md5.html", get},
  232. {"http://jigsaw.w3.org/HTTP/h-retry-after.html", get},
  233. {"http://jigsaw.w3.org/HTTP/h-retry-after-date.html", get},
  234. {"http://jigsaw.w3.org/HTTP/neg", get},
  235. {"http://jigsaw.w3.org/HTTP/negbad", get},
  236. {"http://jigsaw.w3.org/HTTP/400/toolong/", get},
  237. {"http://jigsaw.w3.org/HTTP/300/", get},
  238. {"http://jigsaw.w3.org/HTTP/Basic/", get, [{basic_auth, {"guest", "guest"}}]},
  239. {"http://jigsaw.w3.org/HTTP/CL/", get},
  240. {"http://www.httpwatch.com/httpgallery/chunked/", get},
  241. {"https://github.com", get, [{ssl_options, [{depth, 2}]}]}
  242. ] ++ ?LOCAL_TESTS).
  243. local_unit_tests() ->
  244. error_logger:tty(false),
  245. unit_tests([], ?LOCAL_TESTS),
  246. error_logger:tty(true).
  247. unit_tests() ->
  248. unit_tests([], ?TEST_LIST).
  249. unit_tests(Options, Test_list) ->
  250. application:start(crypto),
  251. application:start(public_key),
  252. application:start(ssl),
  253. (catch ibrowse_test_server:start_server(8181, tcp)),
  254. application:start(ibrowse),
  255. Options_1 = Options ++ [{connect_timeout, 5000}],
  256. Test_timeout = proplists:get_value(test_timeout, Options, 60000),
  257. {Pid, Ref} = erlang:spawn_monitor(?MODULE, unit_tests_1, [self(), Options_1, Test_list]),
  258. receive
  259. {done, Pid} ->
  260. ok;
  261. {'DOWN', Ref, _, _, Info} ->
  262. io:format("Test process crashed: ~p~n", [Info])
  263. after Test_timeout ->
  264. exit(Pid, kill),
  265. io:format("Timed out waiting for tests to complete~n", [])
  266. end,
  267. catch ibrowse_test_server:stop_server(8181),
  268. ok.
  269. unit_tests_1(Parent, Options, Test_list) ->
  270. lists:foreach(fun({local_test_fun, Fun_name, Args}) ->
  271. execute_req(local_test_fun, Fun_name, Args);
  272. ({Url, Method}) ->
  273. execute_req(Url, Method, Options);
  274. ({Url, Method, X_Opts}) ->
  275. execute_req(Url, Method, X_Opts ++ Options)
  276. end, Test_list),
  277. Parent ! {done, self()}.
  278. verify_chunked_streaming() ->
  279. verify_chunked_streaming([]).
  280. verify_chunked_streaming(Options) ->
  281. io:format("~nVerifying that chunked streaming is working...~n", []),
  282. Url = "http://www.httpwatch.com/httpgallery/chunked/",
  283. io:format(" URL: ~s~n", [Url]),
  284. io:format(" Fetching data without streaming...~n", []),
  285. Result_without_streaming = ibrowse:send_req(
  286. Url, [], get, [],
  287. [{response_format, binary} | Options]),
  288. io:format(" Fetching data with streaming as list...~n", []),
  289. Async_response_list = do_async_req_list(
  290. Url, get, [{response_format, list} | Options]),
  291. io:format(" Fetching data with streaming as binary...~n", []),
  292. Async_response_bin = do_async_req_list(
  293. Url, get, [{response_format, binary} | Options]),
  294. io:format(" Fetching data with streaming as binary, {active, once}...~n", []),
  295. Async_response_bin_once = do_async_req_list(
  296. Url, get, [once, {response_format, binary} | Options]),
  297. Res1 = compare_responses(Result_without_streaming, Async_response_list, Async_response_bin),
  298. Res2 = compare_responses(Result_without_streaming, Async_response_list, Async_response_bin_once),
  299. case {Res1, Res2} of
  300. {success, success} ->
  301. io:format(" Chunked streaming working~n", []);
  302. _ ->
  303. ok
  304. end.
  305. test_chunked_streaming_once() ->
  306. test_chunked_streaming_once([]).
  307. test_chunked_streaming_once(Options) ->
  308. io:format("~nTesting chunked streaming with the {stream_to, {Pid, once}} option...~n", []),
  309. Url = "http://www.httpwatch.com/httpgallery/chunked/",
  310. io:format(" URL: ~s~n", [Url]),
  311. io:format(" Fetching data with streaming as binary, {active, once}...~n", []),
  312. case do_async_req_list(Url, get, [once, {response_format, binary} | Options]) of
  313. {ok, _, _, _} ->
  314. io:format(" Success!~n", []);
  315. Err ->
  316. io:format(" Fail: ~p~n", [Err])
  317. end.
  318. compare_responses({ok, St_code, _, Body}, {ok, St_code, _, Body}, {ok, St_code, _, Body}) ->
  319. success;
  320. compare_responses({ok, St_code, _, Body_1}, {ok, St_code, _, Body_2}, {ok, St_code, _, Body_3}) ->
  321. case Body_1 of
  322. Body_2 ->
  323. io:format("Body_1 and Body_2 match~n", []);
  324. Body_3 ->
  325. io:format("Body_1 and Body_3 match~n", []);
  326. _ when Body_2 == Body_3 ->
  327. io:format("Body_2 and Body_3 match~n", []);
  328. _ ->
  329. io:format("All three bodies are different!~n", [])
  330. end,
  331. io:format("Body_1 -> ~p~n", [Body_1]),
  332. io:format("Body_2 -> ~p~n", [Body_2]),
  333. io:format("Body_3 -> ~p~n", [Body_3]),
  334. fail_bodies_mismatch;
  335. compare_responses(R1, R2, R3) ->
  336. io:format("R1 -> ~p~n", [R1]),
  337. io:format("R2 -> ~p~n", [R2]),
  338. io:format("R3 -> ~p~n", [R3]),
  339. fail.
  340. %% do_async_req_list(Url) ->
  341. %% do_async_req_list(Url, get).
  342. %% do_async_req_list(Url, Method) ->
  343. %% do_async_req_list(Url, Method, [{stream_to, self()},
  344. %% {stream_chunk_size, 1000}]).
  345. do_async_req_list(Url, Method, Options) ->
  346. {Pid,_} = erlang:spawn_monitor(?MODULE, i_do_async_req_list,
  347. [self(), Url, Method,
  348. Options ++ [{stream_chunk_size, 1000}]]),
  349. %% io:format("Spawned process ~p~n", [Pid]),
  350. wait_for_resp(Pid).
  351. wait_for_resp(Pid) ->
  352. receive
  353. {async_result, Pid, Res} ->
  354. Res;
  355. {async_result, Other_pid, _} ->
  356. io:format("~p: Waiting for result from ~p: got from ~p~n", [self(), Pid, Other_pid]),
  357. wait_for_resp(Pid);
  358. {'DOWN', _, _, Pid, Reason} ->
  359. {'EXIT', Reason};
  360. {'DOWN', _, _, _, _} ->
  361. wait_for_resp(Pid);
  362. Msg ->
  363. io:format("Recvd unknown message: ~p~n", [Msg]),
  364. wait_for_resp(Pid)
  365. after 100000 ->
  366. {error, timeout}
  367. end.
  368. i_do_async_req_list(Parent, Url, Method, Options) ->
  369. Options_1 = case lists:member(once, Options) of
  370. true ->
  371. [{stream_to, {self(), once}} | (Options -- [once])];
  372. false ->
  373. [{stream_to, self()} | Options]
  374. end,
  375. Res = ibrowse:send_req(Url, [], Method, [], Options_1),
  376. case Res of
  377. {ibrowse_req_id, Req_id} ->
  378. Result = wait_for_async_resp(Req_id, Options, undefined, undefined, []),
  379. Parent ! {async_result, self(), Result};
  380. Err ->
  381. Parent ! {async_result, self(), Err}
  382. end.
  383. wait_for_async_resp(Req_id, Options, Acc_Stat_code, Acc_Headers, Body) ->
  384. receive
  385. {ibrowse_async_headers, Req_id, StatCode, Headers} ->
  386. %% io:format("Recvd headers...~n", []),
  387. maybe_stream_next(Req_id, Options),
  388. wait_for_async_resp(Req_id, Options, StatCode, Headers, Body);
  389. {ibrowse_async_response_end, Req_id} ->
  390. %% io:format("Recvd end of response.~n", []),
  391. Body_1 = list_to_binary(lists:reverse(Body)),
  392. {ok, Acc_Stat_code, Acc_Headers, Body_1};
  393. {ibrowse_async_response, Req_id, Data} ->
  394. maybe_stream_next(Req_id, Options),
  395. %% io:format("Recvd data...~n", []),
  396. wait_for_async_resp(Req_id, Options, Acc_Stat_code, Acc_Headers, [Data | Body]);
  397. {ibrowse_async_response, Req_id, {error, _} = Err} ->
  398. {ok, Acc_Stat_code, Acc_Headers, Err};
  399. Err ->
  400. {ok, Acc_Stat_code, Acc_Headers, Err}
  401. after 10000 ->
  402. {timeout, Acc_Stat_code, Acc_Headers, Body}
  403. end.
  404. maybe_stream_next(Req_id, Options) ->
  405. case lists:member(once, Options) of
  406. true ->
  407. ibrowse:stream_next(Req_id);
  408. false ->
  409. ok
  410. end.
  411. execute_req(local_test_fun, Method, Args) ->
  412. reset_ibrowse(),
  413. io:format(" ~-54.54w: ", [Method]),
  414. Result = (catch apply(?MODULE, Method, Args)),
  415. io:format("~p~n", [Result]);
  416. execute_req(Url, Method, Options) ->
  417. io:format("~7.7w, ~50.50s: ", [Method, Url]),
  418. Result = (catch ibrowse:send_req(Url, [], Method, [], Options)),
  419. case Result of
  420. {ok, SCode, _H, _B} ->
  421. io:format("Status code: ~p~n", [SCode]);
  422. Err ->
  423. io:format("~p~n", [Err])
  424. end.
  425. ue_test() ->
  426. ue_test(lists:duplicate(1024, $?)).
  427. ue_test(Data) ->
  428. {Time, Res} = timer:tc(ibrowse_lib, url_encode, [Data]),
  429. io:format("Time -> ~p~n", [Time]),
  430. io:format("Data Length -> ~p~n", [length(Data)]),
  431. io:format("Res Length -> ~p~n", [length(Res)]).
  432. % io:format("Result -> ~s~n", [Res]).
  433. log_msg(Fmt, Args) ->
  434. io:format("~s -- " ++ Fmt,
  435. [ibrowse_lib:printable_date() | Args]).
  436. %%------------------------------------------------------------------------------
  437. %% Test what happens when the response to a HEAD request is a
  438. %% Chunked-Encoding response with a non-empty body. Issue #67 on
  439. %% Github
  440. %% ------------------------------------------------------------------------------
  441. test_head_transfer_encoding() ->
  442. clear_msg_q(),
  443. test_head_transfer_encoding("http://localhost:8181/ibrowse_head_test").
  444. test_head_transfer_encoding(Url) ->
  445. case ibrowse:send_req(Url, [], head) of
  446. {ok, "200", _, _} ->
  447. success;
  448. Res ->
  449. {test_failed, Res}
  450. end.
  451. %%------------------------------------------------------------------------------
  452. %% Test what happens when the response to a HEAD request is a
  453. %% Chunked-Encoding response with a non-empty body. Issue #67 on
  454. %% Github
  455. %% ------------------------------------------------------------------------------
  456. test_binary_headers() ->
  457. clear_msg_q(),
  458. test_binary_headers("http://localhost:8181/ibrowse_echo_header").
  459. test_binary_headers(Url) ->
  460. case ibrowse:send_req(Url, [{<<"x-binary">>, <<"x-header">>}], get) of
  461. {ok, "200", Headers, _} ->
  462. case proplists:get_value("x-binary", Headers) of
  463. "x-header" ->
  464. success;
  465. V ->
  466. {fail, V}
  467. end;
  468. Res ->
  469. {test_failed, Res}
  470. end.
  471. %%------------------------------------------------------------------------------
  472. %% Test what happens when the response to a HEAD request is a
  473. %% Chunked-Encoding response with a non-empty body. Issue #67 on
  474. %% Github
  475. %% ------------------------------------------------------------------------------
  476. test_head_response_with_body() ->
  477. clear_msg_q(),
  478. test_head_response_with_body("http://localhost:8181/ibrowse_head_transfer_enc").
  479. test_head_response_with_body(Url) ->
  480. case ibrowse:send_req(Url, [], head, [], [{workaround, head_response_with_body}]) of
  481. {ok, "400", _, _} ->
  482. success;
  483. Res ->
  484. {test_failed, Res}
  485. end.
  486. %%------------------------------------------------------------------------------
  487. %% Test what happens when a 303 response has no body
  488. %% Github issue #97
  489. %% ------------------------------------------------------------------------------
  490. test_303_response_with_no_body() ->
  491. clear_msg_q(),
  492. test_303_response_with_no_body("http://localhost:8181/ibrowse_303_no_body_test").
  493. test_303_response_with_no_body(Url) ->
  494. ibrowse:add_config([{allow_303_with_no_body, true}]),
  495. case ibrowse:send_req(Url, [], post) of
  496. {ok, "303", _, _} ->
  497. success;
  498. Res ->
  499. {test_failed, Res}
  500. end.
  501. %% Make sure we don't break requests that do have a body.
  502. test_303_response_with_a_body() ->
  503. clear_msg_q(),
  504. test_303_response_with_no_body("http://localhost:8181/ibrowse_303_with_body_test").
  505. test_303_response_with_a_body(Url) ->
  506. ibrowse:add_config([{allow_303_with_no_body, true}]),
  507. case ibrowse:send_req(Url, [], post) of
  508. {ok, "303", _, "abcde"} ->
  509. success;
  510. Res ->
  511. {test_failed, Res}
  512. end.
  513. %%------------------------------------------------------------------------------
  514. %% Test that retry of requests happens correctly, and that ibrowse doesn't retry
  515. %% if there is not enough time left
  516. %%------------------------------------------------------------------------------
  517. test_retry_of_requests() ->
  518. clear_msg_q(),
  519. test_retry_of_requests("http://localhost:8181/ibrowse_handle_one_request_only_with_delay").
  520. test_retry_of_requests(Url) ->
  521. Timeout_1 = 2050,
  522. Res_1 = test_retry_of_requests(Url, Timeout_1),
  523. case lists:filter(fun({_Pid, {ok, "200", _, _}}) ->
  524. true;
  525. (_) -> false
  526. end, Res_1) of
  527. [_|_] = X ->
  528. Res_1_1 = Res_1 -- X,
  529. case lists:all(
  530. fun({_Pid, {error, retry_later}}) ->
  531. true;
  532. (_) ->
  533. false
  534. end, Res_1_1) of
  535. true ->
  536. ok;
  537. false ->
  538. exit({failed, Timeout_1, Res_1})
  539. end;
  540. _ ->
  541. exit({failed, Timeout_1, Res_1})
  542. end,
  543. reset_ibrowse(),
  544. Timeout_2 = 2200,
  545. Res_2 = test_retry_of_requests(Url, Timeout_2),
  546. case lists:filter(fun({_Pid, {ok, "200", _, _}}) ->
  547. true;
  548. (_) -> false
  549. end, Res_2) of
  550. [_|_] = Res_2_X ->
  551. Res_2_1 = Res_2 -- Res_2_X,
  552. case lists:all(
  553. fun({_Pid, {error, X_err_2}}) ->
  554. (X_err_2 == retry_later) orelse (X_err_2 == req_timedout);
  555. (_) ->
  556. false
  557. end, Res_2_1) of
  558. true ->
  559. ok;
  560. false ->
  561. exit({failed, Timeout_2, Res_2})
  562. end;
  563. _ ->
  564. exit({failed, Timeout_2, Res_2})
  565. end,
  566. success.
  567. test_retry_of_requests(Url, Timeout) ->
  568. #url{host = Host, port = Port} = ibrowse_lib:parse_url(Url),
  569. ibrowse:set_max_sessions(Host, Port, 1),
  570. Parent = self(),
  571. Pids = lists:map(fun(_) ->
  572. spawn(fun() ->
  573. Res = (catch ibrowse:send_req(Url, [], get, [], [], Timeout)),
  574. Parent ! {self(), Res}
  575. end)
  576. end, lists:seq(1,10)),
  577. accumulate_worker_resp(Pids).
  578. %%------------------------------------------------------------------------------
  579. %% Test what happens when the request at the head of a pipeline times out
  580. %%------------------------------------------------------------------------------
  581. test_pipeline_head_timeout() ->
  582. clear_msg_q(),
  583. test_pipeline_head_timeout("http://localhost:8181/ibrowse_inac_timeout_test").
  584. test_pipeline_head_timeout(Url) ->
  585. {ok, Pid} = ibrowse:spawn_worker_process(Url),
  586. Fixed_timeout = 2000,
  587. Test_parent = self(),
  588. Fun = fun({fixed, Timeout}) ->
  589. X_pid = spawn(fun() ->
  590. do_test_pipeline_head_timeout(Url, Pid, Test_parent, Timeout)
  591. end),
  592. %% io:format("Pid ~p with a fixed timeout~n", [X_pid]),
  593. X_pid;
  594. (Timeout_mult) ->
  595. Timeout = Fixed_timeout + Timeout_mult*1000,
  596. X_pid = spawn(fun() ->
  597. do_test_pipeline_head_timeout(Url, Pid, Test_parent, Timeout)
  598. end),
  599. %% io:format("Pid ~p with a timeout of ~p~n", [X_pid, Timeout]),
  600. X_pid
  601. end,
  602. Pids = [Fun(X) || X <- [{fixed, Fixed_timeout} | lists:seq(1,10)]],
  603. Result = accumulate_worker_resp(Pids),
  604. case lists:all(fun({_, X_res}) ->
  605. (X_res == {error,req_timedout}) orelse (X_res == {error, connection_closed})
  606. end, Result) of
  607. true ->
  608. success;
  609. false ->
  610. {test_failed, Result}
  611. end.
  612. do_test_pipeline_head_timeout(Url, Pid, Test_parent, Req_timeout) ->
  613. Resp = ibrowse:send_req_direct(
  614. Pid,
  615. Url,
  616. [], get, [],
  617. [{socket_options,[{keepalive,true}]},
  618. {inactivity_timeout,180000},
  619. {connect_timeout,180000}], Req_timeout),
  620. Test_parent ! {self(), Resp}.
  621. accumulate_worker_resp(Pids) ->
  622. accumulate_worker_resp(Pids, []).
  623. accumulate_worker_resp([_ | _] = Pids, Acc) ->
  624. receive
  625. {Pid, Res} when is_pid(Pid) ->
  626. accumulate_worker_resp(Pids -- [Pid], [{Pid, Res} | Acc]);
  627. Err ->
  628. io:format("Received unexpected: ~p~n", [Err])
  629. end;
  630. accumulate_worker_resp([], Acc) ->
  631. lists:reverse(Acc).
  632. clear_msg_q() ->
  633. receive
  634. _ ->
  635. clear_msg_q()
  636. after 0 ->
  637. ok
  638. end.
  639. %%------------------------------------------------------------------------------
  640. %%
  641. %%------------------------------------------------------------------------------
  642. test_20122010() ->
  643. test_20122010("http://localhost:8181").
  644. test_20122010(Url) ->
  645. {ok, Pid} = ibrowse:spawn_worker_process(Url),
  646. Expected_resp = <<"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">>,
  647. Test_parent = self(),
  648. Fun = fun() ->
  649. do_test_20122010(Url, Pid, Expected_resp, Test_parent)
  650. end,
  651. Pids = [erlang:spawn_monitor(Fun) || _ <- lists:seq(1,10)],
  652. wait_for_workers(Pids).
  653. wait_for_workers([{Pid, _Ref} | Pids]) ->
  654. receive
  655. {Pid, success} ->
  656. wait_for_workers(Pids)
  657. after 60000 ->
  658. test_failed
  659. end;
  660. wait_for_workers([]) ->
  661. success.
  662. do_test_20122010(Url, Pid, Expected_resp, Test_parent) ->
  663. do_test_20122010(10, Url, Pid, Expected_resp, Test_parent).
  664. do_test_20122010(0, _Url, _Pid, _Expected_resp, Test_parent) ->
  665. Test_parent ! {self(), success};
  666. do_test_20122010(Rem_count, Url, Pid, Expected_resp, Test_parent) ->
  667. {ibrowse_req_id, Req_id} = ibrowse:send_req_direct(
  668. Pid,
  669. Url ++ "/ibrowse_stream_once_chunk_pipeline_test",
  670. [], get, [],
  671. [{stream_to, {self(), once}},
  672. {inactivity_timeout, 10000},
  673. {include_ibrowse_req_id, true}]),
  674. do_trace("~p -- sent request ~1000.p~n", [self(), Req_id]),
  675. Req_id_str = lists:flatten(io_lib:format("~1000.p",[Req_id])),
  676. receive
  677. {ibrowse_async_headers, Req_id, "200", Headers} ->
  678. case lists:keysearch("x-ibrowse-request-id", 1, Headers) of
  679. {value, {_, Req_id_str}} ->
  680. ok;
  681. {value, {_, Req_id_1}} ->
  682. do_trace("~p -- Sent req-id: ~1000.p. Recvd: ~1000.p~n",
  683. [self(), Req_id, Req_id_1]),
  684. exit(req_id_mismatch)
  685. end
  686. after 5000 ->
  687. do_trace("~p -- response headers not received~n", [self()]),
  688. exit({timeout, test_failed})
  689. end,
  690. do_trace("~p -- response headers received~n", [self()]),
  691. ok = ibrowse:stream_next(Req_id),
  692. case do_test_20122010_1(Expected_resp, Req_id, []) of
  693. true ->
  694. do_test_20122010(Rem_count - 1, Url, Pid, Expected_resp, Test_parent);
  695. false ->
  696. Test_parent ! {self(), failed}
  697. end.
  698. do_test_20122010_1(Expected_resp, Req_id, Acc) ->
  699. receive
  700. {ibrowse_async_response, Req_id, Body_part} ->
  701. ok = ibrowse:stream_next(Req_id),
  702. do_test_20122010_1(Expected_resp, Req_id, [Body_part | Acc]);
  703. {ibrowse_async_response_end, Req_id} ->
  704. Acc_1 = list_to_binary(lists:reverse(Acc)),
  705. Result = Acc_1 == Expected_resp,
  706. do_trace("~p -- End of response. Result: ~p~n", [self(), Result]),
  707. Result
  708. after 1000 ->
  709. exit({timeout, test_failed})
  710. end.
  711. %%------------------------------------------------------------------------------
  712. %% Test requests where body is generated using a Fun
  713. %%------------------------------------------------------------------------------
  714. test_generate_body_0() ->
  715. io:format("Testing that generation of body using fun works...~n", []),
  716. Tid = ets:new(ibrowse_test_state, [public]),
  717. try
  718. Body_1 = <<"Part 1 of the body">>,
  719. Body_2 = <<"Part 2 of the body\r\n\r\n">>,
  720. Size = size(Body_1) + size(Body_2),
  721. Body = list_to_binary([Body_1, Body_2]),
  722. Fun = fun() ->
  723. case ets:lookup(Tid, body_gen_state) of
  724. [] ->
  725. ets:insert(Tid, {body_gen_state, 1}),
  726. {ok, Body_1};
  727. [{_, 1}]->
  728. ets:insert(Tid, {body_gen_state, 2}),
  729. {ok, Body_2};
  730. [{_, 2}] ->
  731. eof
  732. end
  733. end,
  734. case ibrowse:send_req("http://localhost:8181/echo_body",
  735. [{"Content-Length", Size}],
  736. post,
  737. Fun,
  738. [{response_format, binary},
  739. {http_vsn, {1,0}}]) of
  740. {ok, "200", _, Body} ->
  741. io:format(" Success~n", []),
  742. success;
  743. Err ->
  744. io:format("Test failed : ~p~n", [Err]),
  745. {test_failed, Err}
  746. end
  747. after
  748. ets:delete(Tid)
  749. end.
  750. do_trace(Fmt, Args) ->
  751. do_trace(get(my_trace_flag), Fmt, Args).
  752. do_trace(true, Fmt, Args) ->
  753. io:format("~s -- " ++ Fmt, [ibrowse_lib:printable_date() | Args]);
  754. do_trace(_, _, _) ->
  755. ok.
  756. reset_ibrowse() ->
  757. application:stop(ibrowse),
  758. application:start(ibrowse).