Skip to content

Commit

Permalink
Add tests for handling errors and unexpected msgs
Browse files Browse the repository at this point in the history
These new tests verify correct behavior even in the case that an
unexpected message arrives in the middle of handling a request. We also
verify that the socket is closed cleanly in the event of a protocol
error.
  • Loading branch information
nickelization committed Feb 23, 2016
1 parent fe6c09b commit 5a3d511
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions test/mochiweb_http_tests.erl
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,16 @@ has_acceptor_bug_test_() ->
fun mochiweb_http:stop/1,
fun has_acceptor_bug_tests/1}.

unexpected_msg_test_() ->
{setup,
fun start_server/0,
fun mochiweb_http:stop/1,
fun unexpected_msg_in_hdr_tests/1}.

start_server() ->
application:start(inets),
{ok, Pid} = mochiweb_http:start_link([{port, 0},
{acceptor_pool_size,1},
{loop, fun responder/1}]),
Pid.

Expand Down Expand Up @@ -43,3 +50,37 @@ has_bug(Port, Len) ->
{ok, {{"HTTP/1.1", 400, "Bad Request"}, _, []}} ->
false
end.

-define(IN_METHOD, 3). % The space after the get.
-define(IN_HEADER, 20). % The dash after user
get_req() ->
<<"GET / HTTP/1.1\r\n"
"User-Agent: mochiweb_http_tests/0.0\r\n"
"Accept: */*\r\n\r\n">>.

unexpected_msg(Server, MsgAt, Msg) ->
%% Set up with a single acceptor, dig out the pid - sensitive to change in mochiweb_socket_server
%% state record.
[Acceptor] = sets:to_list(element(14, sys:get_state(Server))),
Port = mochiweb_socket_server:get(Server, port),
<<Before:MsgAt/binary, After/binary>> = get_req(),
{ok, S} = gen_tcp:connect({127,0,0,1},Port,[binary,{active,false}]),
ok = gen_tcp:send(S, Before),
Acceptor ! Msg,
gen_tcp:send(S, After),
gen_tcp:recv(S, 0, 5000).


unexpected_msg_in_hdr_tests(Server) ->
[{"should ignore a message in the middle of the request line",
?_assertMatch({ok, <<"HTTP/1.1 200 OK", _Rest/binary>>},
unexpected_msg(Server, ?IN_METHOD, unexpected_msg_in_your_method))},
{"should ignore a message in the middle of a header",
?_assertMatch({ok, <<"HTTP/1.1 200 OK", _Rest/binary>>},
unexpected_msg(Server, ?IN_HEADER, unexpected_msg_in_your_header))},
{"should close on a TCP error on the request line",
?_assertMatch({error, closed},
unexpected_msg(Server, ?IN_METHOD, {tcp_error, your_port_you_dont_match_on, something_terrible}))},
{"should close on a TCP error in a header",
?_assertMatch({error, closed},
unexpected_msg(Server, ?IN_HEADER, {tcp_error, your_port_you_dont_match_on, something_terrible}))}].

0 comments on commit 5a3d511

Please sign in to comment.