Permalink
Browse files

adding passthrough adapter functionality: forms a transparent wrapper…

… around a process and records any received messages (as for mock spy) then relays the messages to the wrapped process.
  • Loading branch information...
1 parent e4405e3 commit e89503674f27166a10536af49048b0b67a8382fb @nruth committed Dec 5, 2010
Showing with 26 additions and 10 deletions.
  1. +26 −10 nspy.erl
View
@@ -1,21 +1,29 @@
-module (nspy).
--export ([new/0, spy/1, assert_message_received/2]).
+-export ([new/1, wrapper/1, mock/0, spy/2, assert_message_received/2]).
-define (NODEBUG, true).
-include_lib("eunit/include/eunit.hrl").
+% a test double / mock process to use as a non-replying endpoint (null object) for messages
+mock() -> new([]).
-new() ->
- spawn(nspy, spy, [[]]).
+% a test spy to wrap another process, monitoring the messages sent to that process and relaying them to the intended receiver
+% doesn't consider node failures or message synchrony, but you probably shouldn't be relying on that anyway.
+wrapper(Target) -> new([Target]).
-spy (Messages) ->
+new(RelayMessagesTo) ->
+ spawn(nspy, spy, [[], RelayMessagesTo]).
+
+spy (Messages, RelayMessagesTo) ->
receive
{nspy_list_messages, ReplyTo} ->
ReplyTo ! {nspy_messages, Messages},
?debugFmt("Node ~p requested message received list, sending: ~p~n", [ReplyTo, Messages]),
- spy(Messages);
+ spy(Messages, RelayMessagesTo);
Message ->
?debugFmt("Spy ~p received message: ~p~n", [self(), Message]),
- spy([Message | Messages])
+ BroadcastMessage = fun(Receiver) -> Receiver ! Message end,
+ lists:map(BroadcastMessage, RelayMessagesTo),
+ spy([Message | Messages], RelayMessagesTo)
end.
assert_message_received(Spy, Expected) ->
@@ -27,16 +35,24 @@ assert_message_received(Spy, Expected) ->
?assert(MessageFound)
end.
-message_received_test() ->
- Spy = nspy:new(),
+mock_spy_message_received_test() ->
+ Spy = nspy:mock(),
Spy ! hi,
Spy ! ho,
timer:sleep(200),
assert_message_received(Spy, hi),
assert_message_received(Spy, ho).
-message_not_received_test() ->
- Spy = nspy:new(),
+mock_spy__message_not_received_test() ->
+ Spy = nspy:mock(),
Spy ! hi,
timer:sleep(200),
?assertError({assertion_failed, _}, assert_message_received(Spy, ho)).
+
+passthrough_spy_test() ->
+ StuntDouble = nspy:mock(),
+ PassthroughSpy = nspy:wrapper(StuntDouble),
+ PassthroughSpy ! hi,
+ assert_message_received(PassthroughSpy, hi),
+ assert_message_received(StuntDouble, hi).
+

0 comments on commit e895036

Please sign in to comment.