Erlang eunit test skipped (no code changed!) - erlang

I had a failing test. I made some changes, undid them, run my test again. Instead of failing, I get this.
All of my .beam files are present. My git status shows no changes.
=====================================================
Failed: 0. Skipped: 0. Passed: 0.
One or more tests were cancelled.
error
60> room:test().
=ERROR REPORT==== 14-Feb-2017::19:36:57 ===
** Generic server <0.1375.0> terminating
** Last message in was {join,#{auth => "auth",name => "Blandline"}}
** When Server state == {<0.1376.0>,<0.1379.0>,<0.1380.0>}
** Reason for termination ==
** {function_clause,
[{table,terminate,
[{{case_clause,{ok,#{x => "Blandline"}}},
[{table,handle_call,3,[{file,"table.erl"},{line,15}]},
{gen_server,try_handle_call,4,
[{file,"gen_server.erl"},{line,615}]},
{gen_server,handle_msg,5,[{file,"gen_server.erl"},{line,647}]},
{proc_lib,init_p_do_apply,3,
[{file,"proc_lib.erl"},{line,247}]}]},
{<0.1376.0>,<0.1379.0>,<0.1380.0>}],
[{file,"table.erl"},{line,47}]},
{gen_server,try_terminate,3,[{file,"gen_server.erl"},{line,629}]},
{gen_server,terminate,7,[{file,"gen_server.erl"},{line,795}]},
{proc_lib,init_p_do_apply,3,[{file,"proc_lib.erl"},{line,247}]}]}
room: firstMove_test...*skipped*
undefined
*unexpected termination of test process*
::{function_clause,[{table,terminate,
[{{case_clause,{ok,#{x => "Blandline"}}},
[{table,handle_call,3,[...]},
{gen_server,try_handle_call,4,...},
{gen_server,handle_msg,...},
{proc_lib,...}]},
{<0.1376.0>,<0.1379.0>,<0.1380.0>}],
[{file,"table.erl"},{line,47}]},
{gen_server,try_terminate,3,
[{file,"gen_server.erl"},{line,629}]},
{gen_server,terminate,7,
[{file,"gen_server.erl"},{line,795}]},
{proc_lib,init_p_do_apply,3,
[{file,"proc_lib.erl"},{line,247}]}]}
=======================================================
Failed: 0. Skipped: 0. Passed: 0.
One or more tests were cancelled.
error
s:s is just a shortcut for gen_server:call. I'm testing other modules from this module.
-module(room).
-behaviour(gen_server).
-compile(export_all).
-include_lib("eunit/include/eunit.hrl").
testRoom() ->
{ok, R} = room:go(),
{ok, T, _} = s:s(R, {join, #{name => "Blandline", auth => "auth"}}),
{ok, T, _} = s:s(R, {join, #{name => "Kreutzer", auth => "auth"}}),
{R, T}.
firstMove_test() ->
{R, T} = testRoom(),
{ok, #{actions := _, board := _, clock := _}} = s:s(R, {play, T, {take, x, {1,2}}, {"Blandline", "auth"}}).
badMove_test() ->
{R, T} = testRoom(),
{error, invalid_input} = s:s(R, {play, T, {take, x, {1,2,3}}, {"Blandline", "auth"}}).
badAuth_test() ->
{R, T} = testRoom(),
{error, invalid_auth} = s:s(R, {play, T, {take, x, {1,2}}, {"Blandline", "badauth"}}).
badTable_test() ->
{R, _} = testRoom(),
{error, bad_table} = s:s(R, {play, self(), {take, x, {1,2}}, {"Blandline", "badauth"}}).

As the error report is telling you:
[{{case_clause,{ok,#{x => "Blandline"}}},
[{table,handle_call,3,[{file,"table.erl"},{line,15}]},
You have, in file table.erl line 15 a case clause that doesn't match :-)
I think that the reason why the test started failing although you undid your changes is because you are running the tests from the Erlang shell and you have something (like a gen_server) still running that fails for some reasons.
Said in another way, your tests are not repeatable because either they don't teardown properly all the dependencies or because they require external dependencies like this gen_server to be started by hand in the Erlang shell before running the tests.
I strongly suggest to forget the Erlang shell to run tests. Use rebar3 to build and run the tests from a terminal. This will force you to take care of all the dependencies and to have robust tests. The time taken to make this work will be well spent :-)

Related

[Cowboy-Erlang]: Error when pin-pointing to localhost:8080 using provided cowboy example web_server

I am trying out a cowboy example provided by this github repository:
https://github.com/ninenines/cowboy/tree/master/examples/web_server
I build the release successfully using erlang.mk and run the following command, which opens the Erlang shell in my linux terminal:
$ ./_rel/web_server_example/bin/web_server_example console
But when I then open http://localhost:8080 in my web-browser, I get the following error report:
=ERROR REPORT==== 26-Nov-2014::14:33:48 === Error in process <0.166.0> on node 'web_server_example#127.0.0.1' with exit value:
{function_clause,[{cowboy_req,ensure_response,[{ok,{http_req,#Port<0.454>,ranch_tcp,keepalive,<0.166.0>,<<3
bytes>>,'HTTP/1.1',{{127,0,0,1},57150},<<9 bytes>>,undefined,8080,<<1
byte>>,undefined,<<0 bytes>>,undefined,undefined,[{<<4 bytes>>,<<14
bytes>>},{<<10 bytes>>,<<10 bytes>>},{<<13 bytes>>,<<9 bytes>>},{<<6
bytes>>,<<74 bytes>>},{<<10 bytes>>,<<104 bytes>>},{<<15 bytes>>,<<19
bytes>>},{<<15 bytes>>,<<35 bytes>>}],[{<<10 bytes>>,[<<10
bytes>>]}],undefined,[],waiting,<<0 bytes>>,undefined...
=ERROR REPORT==== 26-Nov-2014::14:33:48 === Ranch listener http had connection process started with cowboy_protocol:start_link/4 at
<0.166.0> exit with reason:
{function_clause,[{cowboy_req,ensure_response,[{ok,{http_req,#Port<0.454>,ranch_tcp,keepalive,<0.166.0>,<<"GET">>,'HTTP/1.1',{{127,0,0,1},57150},<<"localhost">>,undefined,8080,<<"/">>,undefined,<<>>,undefined,undefined,[{<<"host">>,<<"localhost:8080">>},{<<"connection">>,<<"keep-alive">>},{<<"cache-control">>,<<"max-age=0">>},{<<"accept">>,<<"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8">>},{<<"user-agent">>,<<"Mozilla/5.0
(X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/39.0.2171.65 Safari/537.36">>},{<<"accept-encoding">>,<<"gzip,
deflate,
sdch">>},{<<"accept-language">>,<<"sv-SE,sv;q=0.8,en-US;q=0.6,en;q=0.4">>}],[{<<"connection">>,[<<"keep-alive">>]}],undefined,[],waiting,<<>>,undefined,false,done,[],<<>>,undefined}},204],[{file,"src/cowboy_req.erl"},{line,1009}]},{cowboy_protocol,next_request,3,[{file,"src/cowboy_protocol.erl"},{line,454}]}]}
This is "src/cowboy_protocol.erl" around line 454:
-spec next_request(cowboy_req:req(), #state{}, any()) -> ok.
next_request(Req, State=#state{req_keepalive=Keepalive, timeout=Timeout},
HandlerRes) ->
cowboy_req:ensure_response(Req, 204),
%% If we are going to close the connection,
%% we do not want to attempt to skip the body.
case cowboy_req:get(connection, Req) of
close ->
terminate(State);
_ ->
%% Skip the body if it is reasonably sized. Close otherwise.
Buffer = case cowboy_req:body(Req) of
{ok, _, Req2} -> cowboy_req:get(buffer, Req2);
_ -> close
end,
%% Flush the resp_sent message before moving on.
if HandlerRes =:= ok, Buffer =/= close ->
receive {cowboy_req, resp_sent} -> ok after 0 -> ok end,
?MODULE:parse_request(Buffer,
State#state{req_keepalive=Keepalive + 1,
until=until(Timeout)}, 0);
true ->
terminate(State)
end
end.
And the webb_server_app.erl file:
%% Feel free to use, reuse and abuse the code in this file.
%% #private
-module(web_server_app).
-behaviour(application).
%% API.
-export([start/2]).
-export([stop/1]).
%% API.
start(_Type, _Args) ->
Dispatch = cowboy_router:compile([
{'_', [
{"/[...]", cowboy_static, {priv_dir, web_server, "", [
{mimetypes, cow_mimetypes, all},
{dir_handler, directory_handler}
]}}
]}
]),
{ok, _} = cowboy:start_http(http, 100, [{port, 8080}], [
{env, [{dispatch, Dispatch}]},
{middlewares, [cowboy_router, directory_lister, cowboy_handler]}
]),
web_server_sup:start_link().
stop(_State) ->
ok.
Does anyone have any suggestion as to what is exactly causing this problem, and how to solve it? Thanks.
EDIT:
I can confirm that the fault was in the Erlang OTP version R16B02 in my case. Changing to the latest Erlang release (17.3), as well as resolving missing file dependencies that arose during the configuration stage (with the solutions in the following link):
https://sites.google.com/site/comptekkia/erlang/how-to-install-erlang-on-ubuntu-10-10
Solved the problem(s). The web_server example runs without error now.
The error says function clause, so the arguments to cowboy_req:ensure_response/2 must be wrong. And indeed they are, because first argument is {ok, Request} instead of Request. You have to trace back, which function called next_request/3 with bad argument, because it clearly should be called without ok.
Probably somewhere at the end, you will find something like:
Req = some_function(...)
And you will need to change it to:
{ok, Req} = some_function(...)
Good luck and happy bug hunting :D
UPDATE: I just cloned the repo and it works fine for me. I got the directory listing, so it is not bug in cowboy, but somewhere in user code.

External function call Erlang

I'm trying to call a function (from an external module) in erlang. both beam files are located in the same directory.
-module(drop2).
-export([fall_velocity/1]).
fall_velocity(Distance) -> math:sqrt(2 * 9.8 * Distance).
Then I'm calling
-module(ask).
-export([term/0]).
term() ->
Input = io:read("Enter {x,distance} ? >>"),
Term = element(2,Input),
drop2:fall_velocity(Term).
it gives the following error.I tested individual modules for errors. it is compiling with out any errors or warning.
Eshell V5.10.2 (abort with ^G)
1> ask:term().
Enter {x,distance} ? >>{test,10}.
** exception error: an error occurred when evaluating an arithmetic expression
in function drop2:fall_velocity/1 (drop2.erl, line 3)
Not sure why it is throwing arithmetic expression error .
You could read the documentation to figure out that the result is {ok, Term}. You could try the io:read/1 function in the console, then you'd see following:
1> io:read("Enter > ").
Enter > {test, 42}.
{ok,{test,42}}
2>
That means that you need to deconstruct the result of io:read/1 differently, for example like this:
-module(ask).
-export([term/0]).
term() ->
{ok, {_, Distance}} = io:read("Enter {x, distance} > "),
drop2:fall_velocity(Distance).

Erlang: misunderstanding of an error that is connected with ranch

I am trying to make this application FIX protocol
I start the Erlang shell using erl -pa ./ebin -pa ebin ./deps/*/ebin.
And run the application like this: application:start(fix).
After that I invoke "start_listener" function like this: fix:start_listener().
As a result this mistake appears:
exception error: no match of right hand side value
{error,
{{shutdown,
{failed_to_start_child,ranch_acceptors_sup,
badarg}},
{child,undefined,
{ranch_listener_sup,fix_listener},
{ranch_listener_sup,start_link,
[fix_listener,10,ranch_tcp,
[{port,[8501]}],
fix_server,[]]},
permanent,5000,supervisor,
[ranch_listener_sup]}}}
in function fix:start_listener/0 (src/fix.erl, line 21)
What does it all mean? And how to fix this mistake?
My code is:
`-module(fix).
-author('Max Lapshin <max#maxidoors.ru>').
-include("log.hrl").
% -include("../include/admin.hrl").
-include("../include/business.hrl").
-compile(export_all).
%% #doc Start acceptor with `ranch' on port, specified in application environment under fix_port%%
-spec start_listener() -> {ok, pid()}.
start_listener() ->
application:start(ranch),
Spec = ranch:child_spec(fix_listener, 10,
ranch_tcp, [{port, fix:get_value(fix_port)}],
fix_server, []
),
{ok, Pid} = supervisor:start_child(fix_sup, Spec),
error_logger:info_msg("Starting FIX server on port ~p~n",[fix:get_value(fix_port)]),
{ok, Pid}.
`
This is a piece of code that shows a mistake.
This is incorrect:
[{port,[8501]}]
Port value must be an integer.
Your fix:get_value function returns list [8501] instead 8501 and you get this badarg error.

Meck behaving strangely for multiple mocked modules

I have following module
-module(bhavcopy_downloader).
-export([download/2]).
download(From, SaveTo) ->
{ok, {{Status, _}, _, Body}} = lhttpc:request(From, "GET", [], infinity),
case Status of
200 -> file:write(SaveTo, Body),
true;
_ -> false
end.
And following tests for the above code
file_download_test_() ->
{foreach,
fun() ->
meck:new(lhttpc)
meck:new(file, [unstick])
end,
fun(_) ->
meck:unload(file),
meck:unload(lhttpc)
end,
{"saves the file at specified location",
fun() ->
meck:expect(lhttpc, request, 4, {ok, {{200, "OK"}, [], <<"response">>}}),
meck:expect(file, write_file, fun(Path, Data) ->
?assertEqual(Path, "~/Downloads/data-downloader/test.html"),
?assertEqual(Data, <<"response">>)
end),
?assertEqual(true, bhavcopy_downloader:download("http://google.com", "~/Downloads/data-downloader/test.html")),
?assert(meck:validate(file))
end}]
}.
When I run the tests I get following error (only part of the error pasted below for brevity). Looking at the error below, I am kind of feeling that file module is not being mocked (or the mock of file module being overridden when I set the other mock using meck:new(lhttpc). What could be going wrong here?
=ERROR REPORT==== 16-Feb-2013::20:17:24 ===
** Generic server file_meck terminating
** Last message in was {'EXIT',<0.110.0>,
{compile_forms,
{error,
[{[],
[{none,compile,
{crash,beam_asm,
{undef,
[{file,get_cwd,[],[]},
{filename,absname,1,
[{file,"filename.erl"},{line,67}]},
{compile,beam_asm,1,
[{file,"compile.erl"},{line,1245}]},
{compile,'-internal_comp/4-anonymous-1-',2,
[{file,"compile.erl"},{line,273}]},
{compile,fold_comp,3,
[{file,"compile.erl"},{line,291}]},
{compile,internal_comp,4,
[{file,"compile.erl"},{line,275}]},
{compile,'-do_compile/2-anonymous-0-',2,
[{file,"compile.erl"},{line,152}]}]}}}]}],
[{"src/lhttpc_types.hrl",
[{31,erl_lint,{new_builtin_type,{boolean,0}}},
{31,erl_lint,{renamed_type,bool,boolean}}]}]}}}
This is a catch 22 in Meck, caused by the fact that Meck uses the Erlang compiler, which in turns uses the file module. When Meck tries recompile the file module it needs the file module (through the compiler) and thus crashes.
As of this moment, Meck doesn't handle mocking the file module. Your best alternative is to wrap the file module calls in another module and mock this module instead.
(It is theoretically possible to fix this in Meck by using the internals of the compiler and the code server instead, for example erlang:load_module/2, however this is quite tricky and needs to be designed and tested well)

Erlang runtime error

I'm working on an erlang program and getting a strange runtime error. Any idea why? Thanks!
The errors are (after compiling the program successfully):
8> PID = spawn(planner,start,[]).
** exception error: no match of right hand side value <0.65.0>
9>
This is the program:
-module(planner).
-export([start/0]).
start() ->
loop([],[]).
loop(ContactsList,EventsList) ->
receive
{contact, Last, First, Number} ->
loop([{Last,First,Number}|ContactsList],EventsList);
{event, Date, Time, What} ->
loop([{Date,Time,What}|ContactsList],EventsList);
print_contacts ->
NewList=lists:sort(ContactsList),
lists:foreach(fun(Elem)->io:format("~p~n", [Elem]) end, NewList),
loop(ContactsList,EventsList);
print_events ->
NewList=lists:sort(EventsList),
lists:foreach(fun(Elem)->io:format("~p~n", [Elem]) end, NewList),
loop(ContactsList,EventsList);
exit ->
io:format("Exiting.~n");
_ ->
io:format("Dude, I don't even know what you're talking about.~n"),
loop(ContactsList,EventsList)
end.
The variable PID is probably set to something else but <0.65.0> from an earlier line you entered in the shell:
5> PID = spawn(...).
<0.42.0>
8> PID = spawn(...).
** exception error: no match of right hand side value <0.65.0>
This effectively makes the line which generates the error something like
8> <0.42.0> = <0.65.0>.
which will result in a "no match" error.
More obvious illustration of the issue:
1> X = 1.
1
2> X = 2.
** exception error: no match of right hand side value 2
As to solving your issue: You probably want to run f(PID) to have the shell forget just the PID variable, or even f() to have the shell forget ALL variables.

Resources