Permalink
Browse files

initial commit, working nspy with exact message matching, a couple of…

… eunit tests, and provisional readme
  • Loading branch information...
nruth committed Dec 3, 2010
0 parents commit e4405e39568eaf0c1d51d59e3397df781edc2e41
Showing with 62 additions and 0 deletions.
  1. +20 −0 Readme.md
  2. +42 −0 nspy.erl
@@ -0,0 +1,20 @@
+What
+====
+
+Processes which record all messages they receive
+
+Why
+===
+
+For asserting a process under test called another process in a particular way, currently only exact message matches supported.
+
+How
+===
+
+ nspy:assert_message_received(Spy, Expected)
+
+is a helper (function) which will handle messaging the Spy process and receiving the list of messages, then scan the list of messages for the one you want to find.
+
+On failure eunit will print out your stdout, which contains the spy's expected message and actual received message list.
+
+Born of necessity (since there is no RSpec for Erlang), contributions and criticisms welcome.
@@ -0,0 +1,42 @@
+-module (nspy).
+-export ([new/0, spy/1, assert_message_received/2]).
+-define (NODEBUG, true).
+-include_lib("eunit/include/eunit.hrl").
+
+
+new() ->
+ spawn(nspy, spy, [[]]).
+
+spy (Messages) ->
+ receive
+ {nspy_list_messages, ReplyTo} ->
+ ReplyTo ! {nspy_messages, Messages},
+ ?debugFmt("Node ~p requested message received list, sending: ~p~n", [ReplyTo, Messages]),
+ spy(Messages);
+ Message ->
+ ?debugFmt("Spy ~p received message: ~p~n", [self(), Message]),
+ spy([Message | Messages])
+ end.
+
+assert_message_received(Spy, Expected) ->
+ Spy ! {nspy_list_messages, self()},
+ receive
+ {nspy_messages, Messages} ->
+ io:format("~n[SPY] expected ~p received ~p~n", [Expected, Messages]),
+ MessageFound = lists:any(fun(Elem) -> Elem =:= Expected end, Messages),
+ ?assert(MessageFound)
+ end.
+
+message_received_test() ->
+ Spy = nspy:new(),
+ Spy ! hi,
+ Spy ! ho,
+ timer:sleep(200),
+ assert_message_received(Spy, hi),
+ assert_message_received(Spy, ho).
+
+message_not_received_test() ->
+ Spy = nspy:new(),
+ Spy ! hi,
+ timer:sleep(200),
+ ?assertError({assertion_failed, _}, assert_message_received(Spy, ho)).

0 comments on commit e4405e3

Please sign in to comment.