eunit: How to test a simple process? - testing

I'm currently writing a test for a module that runs in a simple process started with spawn_link(?MODULE, init, [self()]).
In my eunit tests, I have a setup and teardown function defined and a set of test generators.
all_tests_test_() ->
{inorder, {
foreach,
fun setup/0,
fun teardown/1,
[
fun my_test/1
]}
}.
The setup fun creates the process-under-test:
setup() ->
{ok, Pid} = protocol:start_link(),
process_flag(trap_exit,true),
error_logger:info_msg("[~p] Setting up process ~p~n", [self(), Pid]),
Pid.
The test looks like this:
my_test(Pid) ->
[ fun() ->
error_logger:info_msg("[~p] Sending to ~p~n", [self(), Pid]),
Pid ! something,
receive
Msg -> ?assertMatch(expected_result, Msg)
after
500 -> ?assert(false)
end
end ].
Most of my modules are gen_server but for this I figured it'll be easier without all gen_server boilerplate code...
The output from the test looks like this:
=INFO REPORT==== 31-Mar-2014::21:20:12 ===
[<0.117.0>] Setting up process <0.122.0>
=INFO REPORT==== 31-Mar-2014::21:20:12 ===
[<0.124.0>] Sending to <0.122.0>
=INFO REPORT==== 31-Mar-2014::21:20:12 ===
[<0.122.0>] Sending expected_result to <0.117.0>
protocol_test: my_test...*failed*
in function protocol_test:'-my_test/1-fun-0-'/0 (test/protocol_test.erl, line 37)
**error:{assertion_failed,[{module,protocol_test},
{line,37},
{expression,"false"},
{expected,true},
{value,false}]}
From the Pids you can see that whatever process was running setup (117) was not the same that was running the test case (124). The process under test however is the same (122). This results in a failing test case because the receive never gets the message und runs into the timeout.
Is that the expected behaviour that a new process gets spawned by eunit to run the test case?
An generally, is there a better way to test a process or other asynchronous behaviour (like casts)? Or would you suggest to always use gen_server to have a synchronous interface?
Thanks!
[EDIT]
To clarify, how protocol knows about the process, this is the start_link/0 fun:
start_link() ->
Pid = spawn_link(?MODULE, init, [self()]),
{ok, Pid}.
The protocol ist tightly linked to the caller. If the either of them crashes I want the other one to die as well. I know I could use gen_server and supervisors and actually it did that in parts of the application, but for this module, I thought it was a bit over the top.

did you try:
all_tests_test_() ->
{inorder, {
foreach,
local,
fun setup/0,
fun teardown/1,
[
fun my_test/1
]}
}.
From the doc, it seems to be what you need.

simple solution
Just like in Pascal answer, adding the local flag to test description might solve some your problem, but it will probably cause you some additional problems in future, especially when you link yourself to created process.
testing processes
General practice in Erlang is that while process abstraction is crucial for writing (designing and thinking about) programs, it is not something that you would expose to user of your code (even if it is you). Instead expecting someone to send you message with proper data, you wrap it in function call
get_me_some_expected_result(Pid) ->
Pid ! something,
receive
Msg ->
Msg
after 500
timeouted
end
and then test this function rather than receiving something "by hand".
To distinguish real timeout from received timeouted atom, one can use some pattern matching, and let it fail in case of error
get_me_some_expected_result(Pid) ->
Pid ! something,
receive
Msg ->
{ok, Msg}
after 500
timeouted
end
in_my_test() ->
{ok, ValueToBeTested} = get_me_some_expected_result().
In addition, since your process could receive many different messages in meantime, you can make sure that you receive what you think you receive with little pattern-matching and local reference
get_me_some_expected_result(Pid) ->
Ref = make_ref(),
Pid ! {something, Ref},
receive
{Ref, Msg} ->
{ok, Msg}
after 500
timeouted
end
And now receive will ignore (leave for leter) all messages that will not have same Reg that you send to your process.
major concern
One thing that I do not really understand, is how does process you are testing know where to send back received message? Only logical solution would be getting pid of it's creator during initialization (call to self/0 inside protocol:start_link/0 function). But then our new process can communicate only with it's creator, which might not be something you expect, and which is not how tests are run.
So simplest solution would be sending "return address" with each call; which again could be done in our wrapping function.
get_me_some_expected_result(Pid) ->
Ref = make_ref(),
Pid ! {something, Ref, self()},
receive
{Ref, Msg} ->
{ok, Msg}
after 500
timeouted
end
Again, anyone who will use this get_me_some_expected_result/1 function will not have to worry about message passing, and testing such functions makes thing extremely easier.
Hope this helps at least a little.

Maybe it's simply because you are using the foreach EUnit fixture in place of the setup one.
There, try the setup fixture: the one that uses {setup, Setup, Cleanup, Tests} instead of {inorder, {foreach, …}}

Related

Pass Data between two Nodes erlang

I have recently started learning Erlang and I am trying to implement a server-client sample program. I have created a registered process and I would like to send data to it from another process. The code is as follows.
-module(mine).
-export([alice/0, bob/2, startAlice/0, startBob/1]).
alice() ->
receive
{message, BobNode} ->
io:fwrite("Alice got a message \n"),
BobNode ! message,
alice()
finished -> io:fwrite("Alice is finished\n")
end.
bob(0, AliceNode) ->
{alice, AliceNode} ! finished,
io:fwrite("Bob is finished\n");
bob(N, AliceNode) ->
{alice, AliceNode} ! {message, self()},
receive
message -> io:fwrite("Bob got a message ~w \n",[N])
end,
bob(N-1, AliceNode).
startAlice() ->
register(alice, spawn(mine, alice, [])).
startBob(AliceNode) ->
spawn(mine, bob, [30000, AliceNode]).
Here, I would like to send some value say N, from bob to alice. I tried sending the data as
{alice, AliceNode, Nvalue} ! {message, self(), N} in bob(N, AliceNode) function, but got the error variable 'Nvalue' is unbound erl. I am sure I am missing something trivial here. Any help would be appreciated. Thanks in advance.

TestKit for Erlang

Is there any kind of test framework for Erlang which is similar to TestKit in Akka?
The goal is to test processes in an integrated environment, for example, to send some messages to a group of processes on one end and assert the resulting messages coming out on the other end. The Akka Testkit makes these kinds of tests fairly straightforward, but I have not been able to find the equivalent in Erlang yet.
EDIT: as the simplest example of what I'm looking for, let's say that we have a process A that is expected to send a message to process B, and I would like to test this behaviour.
In Akka, I can instantiate an actor based on the TestKit class, which has a builtin method expectMsg. So my test looks like this:
instantiate a mock B actor
instantiate the A actor (which gets a reference to B somehow)
send B a message
call B.expectMsg to verify that it received the message (note that
this automatically makes sure that no other type of message is sent to B, and
you can optionally provide a timeout)
Is there a library that supports this kind of workflow in Erlang? As far as I know neither EUnit nor CT support this kind of testing.
To get an idea of the more complex assertions, please see this page: http://doc.akka.io/api/akka/2.0/akka/testkit/TestKit.html
Erlang itself makes these kinds of tests fairly straightforward. There is Lightweight Unit Testing Framework for Erlang eunit and there is Common Test framework for high scale integration testing.
Edit:
You don't need nothing more than Erlang for such simple things:
$ cat echo.erl
-module(echo).
-export([start/0, send/3]).
start() ->
spawn_link(fun() ->
receive
{To, Msg} -> To ! Msg
end
end).
send(Echo, To, Msg) ->
Echo ! {To, Msg}.
-include_lib("eunit/include/eunit.hrl").
echo_test_() ->
Msg = "Hello world!",
{timeout, 0.1, fun() ->
Echo = echo:start(),
echo:send(Echo, self(), Msg),
?assertEqual(Msg, receive X -> X end)
end}.
$ erlc echo.erl
$ erl
Erlang/OTP 18 [erts-7.0] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]
Eshell V7.0 (abort with ^G)
1> eunit:test(echo, [verbose]).
======================== EUnit ========================
echo: echo_test_ (module 'echo')...ok
=======================================================
Test passed.
ok
2>
Process A is started by echo:start/0 and process B is testing process itself. If you want mock existing modules there is meck. If you would like just watch messages between two processes without messing with receiver code, you can of course use tracing capabilities of Erlang VM itself.

How to print a message within a process when it gets the right from another process in erlang?

I'm all new to erlang, and i got this task:
Write a function "setalarm(T,Message)" what starts two processes at
the same time. After T miliseconds the first process sends a message
to the second process, and that message will be the Message arg.
It's forbidden to use function library, only primitives (send, receive, spawn)
Me as a novice useful to write more code, so I suggest such an option:
setalarm(T,Message)->
S = spawn(sotest,second,[]),
Pid = spawn(sotest,first,[S,T,Message]).
first(Pid,T,Message) ->
receive
after T -> Pid ! Message
end.
second() ->
receive
Message -> io:format("The message is ~p~n",[Message])
end.

erlang: ending a process without knowing PiD?

Simply put; how can I end a process if I accidentally forgot to equate a Pid variable when I started a process using this:
9> trivial_process:start().
<0.67.0>
10>
I know I should have written Pid = trivial_process:start(). Is there some way to take <0.67.0> and terminate the process?
-module(trivial_process).
-export([start/0]).
start() ->
spawn(fun() -> loop() end).
loop() ->
receive
Any ->
io:format("~nI got the message: ~p~n",[Any]),
loop()
end.
EDIT:Answer.
8> Pid = "<0.67.0>".
9> A2 = list_to_pid(Pid).
<0.67.0>
You can use the list_to_pid function. The docs are here. You shouldn't use this in deployed code, it's only useful for debugging. It doesn't work with remote pids, either.
Reference: Something maybe you don’t know about Erlang PIDs

How to flush the io buffer in Erlang?

How do you flush the io buffer in Erlang?
For instance:
> io:format("hello"),
> io:format(user, "hello").
This post seems to indicate that there is no clean solution.
Is there a better solution than in that post?
Sadly other than properly implementing a flush "command" in the io/kernel subsystems and making sure that the low level drivers that implement the actual io support such a command you really have to simply rely on the system quiescing before closing. A failing I think.
Have a look at io.erl/io_lib.erl in stdlib and file_io_server.erl/prim_file.erl in kernel for the gory details.
As an example, in file_io_server (which effectively takes the request from io/io_lib and routes it to the correct driver), the command types are:
{put_chars,Chars}
{get_until,...}
{get_chars,...}
{get_line,...}
{setopts, ...}
(i.e. no flush)!
As an alternative you could of course always close your output (which would force a flush) after every write. A logging module I have does something like this every time and it doesn't appear to be that slow (it's a gen_server with the logging received via cast messages):
case file:open(LogFile, [append]) of
{ok, IODevice} ->
io:fwrite(IODevice, "~n~2..0B ~2..0B ~4..0B, ~2..0B:~2..0B:~2..0B: ~-8s : ~-20s : ~12w : ",
[Day, Month, Year, Hour, Minute, Second, Priority, Module, Pid]),
io:fwrite(IODevice, Msg, Params),
io:fwrite(IODevice, "~c", [13]),
file:close(IODevice);
io:put_chars(<<>>)
at the end of the script works for me.
you could run
flush().
from the shell, or try
flush()->
receive
_ -> flush()
after 0 -> ok
end.
That works more or less like a C flush.