github
Advanced Search
  • Home
  • Pricing and Signup
  • Explore GitHub
  • Blog
  • Login

cliffmoon / dynomite

  • Admin
  • Watch Unwatch
  • Fork
  • Your Fork
  • Pull Request
  • Download Source
    • 314
    • 17
  • Source
  • Commits
  • Network (17)
  • Issues (0)
  • Downloads (30)
  • Wiki (7)
  • Graphs
  • Tree: 62d5d52

click here to add a description

click here to add a homepage

  • Branches (4)
    • conc_clients
    • master
    • membership2
    • xhash
  • Tags (30)
    • v0.6.0
    • v0.4.1-1
    • v0.4.1
    • v0.4.0
    • v0.3.1
    • v0.3.0
    • v0.2.19
    • v0.2.18
    • v0.2.17
    • v0.2.16
    • v0.2.15
    • v0.2.13
    • v0.2.12
    • v0.2.11
    • v0.2.10-1
    • v0.2.10
    • v0.2.9
    • v0.2.8
    • v0.2.7
    • v0.2.6
    • v0.2.5
    • v0.2.4
    • v0.2.3
    • v0.2.2
    • v0.1.0
    • v0.0.3
    • v0.0.2
    • v0.0.1
    • v0.0.0
    • 0.5.0
Sending Request…
Enable Donations

Pledgie Donations

Once activated, we'll place the following badge in your repository's detail box:
Pledgie_example
This service is courtesy of Pledgie.

Open source dynamo clone written in Erlang. — Read more

  cancel

  cancel
  • Private
  • Read-Only
  • HTTP Read-Only

This URL has Read+Write access

i cannot believe i did not know about port locking.  thats how i assumed 
it all worked. 
cliffmoon (author)
Sun Feb 22 10:05:41 -0800 2009
commit  62d5d52cbc852784b50f1f3cee1dfa7e0a0669cf
tree    741ed75dccfda7a5f3e73d01763ea6f2a7ac9826
parent  949e4042ca0fbc8e5041ee56eee16420d50bd50f
dynomite / etest / mock.erl etest/mock.erl
100644 336 lines (277 sloc) 12.936 kb
edit raw blame history
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
%%%-------------------------------------------------------------------
%%% File: mock.erl
%%% @author Cliff Moon <> []
%%% @copyright 2009 Cliff Moon
%%% @doc
%%%
%%% @end
%%%
%%% @since 2009-01-04 by Cliff Moon
%%%-------------------------------------------------------------------
-module(mock).
-author('cliff@powerset.com').
 
%% API
-export([mock/1, proxy_call/2, proxy_call/3, expects/4, expects/5, verify_and_stop/1, verify/1, stub_proxy_call/3, stub_function/4, stop/1]).
 
-include("common.hrl").
-include_lib("eunit/include/eunit.hrl").
 
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
         terminate/2, code_change/3]).
 
-record(state, {old_code, module, expectations=[]}).
 
%%====================================================================
%% API
%%====================================================================
%%--------------------------------------------------------------------
%% @spec mock() -> {ok,#mock} | ignore | {error,Error}
%% @doc Starts the server
%% @end
%%--------------------------------------------------------------------
mock(Module) ->
  case gen_server:start_link({local, mod_to_name(Module)}, mock, Module, []) of
    {ok, Pid} -> {ok, Pid};
    {error, Reason} -> {error, Reason}
  end.
 
%% @spec proxy_call(Module::atom(), Function::atom()) -> term()
%% @doc Proxies a call to the mock server for Module without arguments
%% @end
proxy_call(Module, Function) ->
  gen_server:call(mod_to_name(Module), {proxy_call, Function, {}}).
  
%% @spec proxy_call(Module::atom(), Function::atom(), Args::tuple()) -> term()
%% @doc Proxies a call to the mock server for Module with arguments
%% @end
proxy_call(Module, Function, Args) ->
  gen_server:call(mod_to_name(Module), {proxy_call, Function, Args}).
  
stub_proxy_call(Module, Function, Args) ->
  RegName = list_to_atom(lists:concat([Module, "_", Function, "_stub"])),
  Ref = make_ref(),
  RegName ! {Ref, self(), Args},
  ?debugFmt("sending {~p,~p,~p}", [Ref, self(), Args]),
  receive
    {Ref, Answer} -> Answer
  end.
  
%% @spec expects(Module::atom(),
%% Function::atom(),
%% Args::fun/1,
%% Ret::fun/2 | term()
%% Times:: {at_least, integer()} | never | {no_more_than, integer()} | integer()) -> term()
%% @doc Sets the expectation that Function of Module will be called during a test with Args.
%% Args should be a fun predicate that will return true or false whether or not the argument
%% list matches. The argument list of the function is passed in as a tuple.
%%
%% Ret is either a value to return or a fun of arity 2 to be evaluated in response to a proxied
%% call. The first argument is the actual args from the call, the second is the call count starting
%% with 1.
expects(Module, Function, Args, Ret) ->
  gen_server:call(mod_to_name(Module), {expects, Function, Args, Ret, 1}).
 
expects(Module, Function, Args, Ret, Times) ->
  gen_server:call(mod_to_name(Module), {expects, Function, Args, Ret, Times}).
  
stub(Module, Function, Args, Ret) ->
  gen_server:call(mod_to_name(Module), {stub, Function, Args, Ret}).
  
verify_and_stop(Module) ->
  verify(Module),
  stop(Module).
  
verify(Module) ->
  ?assertEqual(ok, gen_server:call(mod_to_name(Module), verify)).
 
stop(Module) ->
  gen_server:cast(mod_to_name(Module), stop),
  timer:sleep(10).
  
stub_function(Module, Name, Arity, Ret) when is_function(Ret) ->
  {_, Bin, _} = code:get_object_code(Module),
  {ok, {Module,[{abstract_code,{raw_abstract_v1,Forms}}]}} = beam_lib:chunks(Bin, [abstract_code]),
  {Prefix, Functions} = lists:splitwith(fun(Form) -> element(1, Form) =/= function end, Forms),
  Function = {function,1,Name,Arity,[{clause,1,generate_variables(Arity), [], generate_expression(mock, stub_proxy_call, Module, Name, Arity)}]},
  RegName = list_to_atom(lists:concat([Module, "_", Name, "_stub"])),
  Pid = spawn_link(fun() ->
      stub_function_loop(Ret)
    end),
  register(RegName, Pid),
  Forms1 = Prefix ++ replace_function(Function, Functions),
  code:purge(Module),
  code:delete(Module),
  case compile:forms(Forms1, [binary]) of
    {ok, Module, Binary} -> code:load_binary(Module, atom_to_list(Module) ++ ".erl", Binary);
    Other -> Other
  end.
  
%%====================================================================
%% gen_server callbacks
%%====================================================================
 
%%--------------------------------------------------------------------
%% @spec init(Args) -> {ok, State} |
%% {ok, State, Timeout} |
%% ignore |
%% {stop, Reason}
%% @doc Initiates the server
%% @end
%%--------------------------------------------------------------------
init(Module) ->
  case code:get_object_code(Module) of
    {Module, Bin, Filename} ->
      case replace_code(Module) of
        ok -> {ok, #state{module=Module,old_code={Module, Bin, Filename}}};
        {error, Reason} -> {stop, Reason}
      end;
    error -> {stop, ?fmt("Could not get object code for module ~p", [Module])}
  end.
 
%%--------------------------------------------------------------------
%% @spec
%% handle_call(Request, From, State) -> {reply, Reply, State} |
%% {reply, Reply, State, Timeout} |
%% {noreply, State} |
%% {noreply, State, Timeout} |
%% {stop, Reason, Reply, State} |
%% {stop, Reason, State}
%% @doc Handling call messages
%% @end
%%--------------------------------------------------------------------
handle_call({proxy_call, Function, Args}, _From, State = #state{module=Mod,expectations=Expects}) ->
  case match_expectation(Function, Args, Expects) of
    {matched, ReturnTerm, NewExpects} -> {reply, ReturnTerm, State#state{expectations=NewExpects}};
    unmatched -> {stop, ?fmt("got unexpected call to ~p:~p", [Mod,Function])}
  end;
  
handle_call({expects, Function, Args, Ret, Times}, _From, State = #state{expectations=Expects}) ->
  {reply, ok, State#state{expectations=add_expectation(Function, Args, Ret, Times, Expects)}};
 
handle_call(verify, _From, State = #state{expectations=Expects,module=Mod}) ->
  ?infoFmt("verifying ~p~n", [Mod]),
  if
    length(Expects) > 0 -> {reply, {mismatch, format_missing_expectations(Expects, Mod)}, State};
    true -> {reply, ok, State}
  end.
 
%%--------------------------------------------------------------------
%% @spec handle_cast(Msg, State) -> {noreply, State} |
%% {noreply, State, Timeout} |
%% {stop, Reason, State}
%% @doc Handling cast messages
%% @end
%%--------------------------------------------------------------------
handle_cast(stop, State) ->
  {stop, shutdown, State}.
 
%%--------------------------------------------------------------------
%% @spec handle_info(Info, State) -> {noreply, State} |
%% {noreply, State, Timeout} |
%% {stop, Reason, State}
%% @doc Handling all non call/cast messages
%% @end
%%--------------------------------------------------------------------
handle_info(_Info, State) ->
    {noreply, State}.
 
%%--------------------------------------------------------------------
%% @spec terminate(Reason, State) -> void()
%% @doc This function is called by a gen_server when it is about to
%% terminate. It should be the opposite of Module:init/1 and do any necessary
%% cleaning up. When it returns, the gen_server terminates with Reason.
%% The return value is ignored.
%% @end
%%--------------------------------------------------------------------
terminate(_Reason, #state{old_code={Module, Binary, Filename}}) ->
  code:purge(Module),
  code:delete(Module),
  code:load_binary(Module, Filename, Binary).
 
%%--------------------------------------------------------------------
%% @spec code_change(OldVsn, State, Extra) -> {ok, NewState}
%% @doc Convert process state when code is changed
%% @end
%%--------------------------------------------------------------------
code_change(_OldVsn, State, _Extra) ->
    {ok, State}.
 
%%--------------------------------------------------------------------
%%% Internal functions
%%--------------------------------------------------------------------
format_missing_expectations(Expects, Mod) ->
  format_missing_expectations(Expects, Mod, []).
  
format_missing_expectations([], _, Msgs) ->
  lists:reverse(Msgs);
  
format_missing_expectations([{Function, Args, Ret, Times, Called}|Expects], Mod, Msgs) ->
  Msgs1 = [?fmt("expected ~p:~p to be called ~p times but was called ~p", [Mod,Function,Times,Called])|Msgs],
  format_missing_expectations(Expects, Mod, Msgs1).
 
add_expectation(Function, Args, Ret, Times, Expects) ->
  Expects ++ [{Function, Args, Ret, Times, 0}].
  
match_expectation(Function, Args, Expectations) ->
  match_expectation(Function, Args, Expectations, []).
  
match_expectation(_Function, _Args, [], _Rest) ->
  unmatched;
  
match_expectation(Function, Args, [{Function, Matcher, Ret, MaxTimes, Invoked}|Expects], Rest) ->
  case Matcher(Args) of
    true ->
      ReturnTerm = prepare_return(Args, Ret, Invoked+1),
      if
        Invoked + 1 >= MaxTimes -> {matched, ReturnTerm, lists:reverse(Rest) ++ Expects};
        true -> {matched, ReturnTerm, lists:reverse(Rest) ++ [{Function, Matcher, Ret, MaxTimes, Invoked+1}] ++ Expects}
      end;
    false -> match_expectation(Function, Args, Expects, [{Function,Matcher,Ret,MaxTimes,Invoked}|Rest])
  end;
  
match_expectation(Function, Args, [Expect|Expects], Rest) ->
  match_expectation(Function, Args, Expects, [Expect|Rest]).
  
prepare_return(Args, Ret, Invoked) when is_function(Ret) ->
  Ret(Args, Invoked);
  
prepare_return(Args, Ret, Invoked) ->
  Ret.
  
replace_code(Module) ->
  Info = Module:module_info(),
  Exports = get_exports(Info),
  unload_code(Module),
  NewFunctions = generate_functions(Module, Exports),
  Forms = [
    {attribute,1,module,Module},
    {attribute,2,export,Exports}
  ] ++ NewFunctions,
  case compile:forms(Forms, [binary]) of
    {ok, Module, Binary} -> case code:load_binary(Module, atom_to_list(Module) ++ ".erl", Binary) of
      {module, Module} -> ok;
      {error, Reason} -> {error, Reason}
    end;
    error -> {error, "An undefined error happened when compiling."};
    {error, Errors, Warnings} -> {error, Errors ++ Warnings}
  end.
 
unload_code(Module) ->
  code:purge(Module),
  code:delete(Module).
  
get_exports(Info) ->
  get_exports(Info, []).
  
get_exports(Info, Acc) ->
  case lists:keytake(exports, 1, Info) of
    {value, {exports, Exports}, ModInfo} ->
      get_exports(ModInfo, Acc ++ lists:filter(fun({module_info, _}) -> false; (_) -> true end, Exports));
    _ -> Acc
  end.
  
stub_function_loop(Fun) ->
  receive
    {Ref, Pid, Args} ->
      ?debugFmt("received {~p,~p,~p}", [Ref, Pid, Args]),
      Ret = (catch Fun(Args) ),
      ?debugFmt("sending {~p,~p}", [Ref,Ret]),
      Pid ! {Ref, Ret},
      stub_function_loop(Fun)
  end.
 
% Function -> {function, Lineno, Name, Arity, [Clauses]}
% Clause -> {clause, Lineno, [Variables], [Guards], [Expressions]}
% Variable -> {var, Line, Name}
%
generate_functions(Module, Exports) ->
  generate_functions(Module, Exports, []).
  
generate_functions(_Module, [], FunctionForms) ->
  lists:reverse(FunctionForms);
  
generate_functions(Module, [{Name,Arity}|Exports], FunctionForms) ->
  generate_functions(Module, Exports, [generate_function(Module, Name, Arity)|FunctionForms]).
  
generate_function(Module, Name, Arity) ->
  {function, 1, Name, Arity, [{clause, 1, generate_variables(Arity), [], generate_expression(mock, proxy_call, Module, Name, Arity)}]}.
  
generate_variables(0) -> [];
  
generate_variables(Arity) ->
  lists:map(fun(N) ->
      {var, 1, list_to_atom(lists:concat(['Arg', N]))}
    end, lists:seq(1, Arity)).
    
generate_expression(M, F, Module, Name, 0) ->
  [{call,1,{remote,1,{atom,1,M},{atom,1,F}}, [{atom,1,Module}, {atom,1,Name}]}];
    
generate_expression(M, F, Module, Name, Arity) ->
  [{call,1,{remote,1,{atom,1,M},{atom,1,F}}, [{atom,1,Module}, {atom,1,Name}, {tuple,1,lists:map(fun(N) ->
      {var, 1, list_to_atom(lists:concat(['Arg', N]))}
    end, lists:seq(1, Arity))}]}].
    
mod_to_name(Module) ->
  list_to_atom(lists:concat([mock_, Module])).
  
replace_function(FF, Forms) ->
  replace_function(FF, Forms, []).
  
replace_function(FF, [], Ret) ->
  [FF|lists:reverse(Ret)];
  
replace_function({function,_,Name,Arity,Clauses}, [{function,Line,Name,Arity,_}|Forms], Ret) ->
  lists:reverse(Ret) ++ [{function,Line,Name,Arity,Clauses}|Forms];
  
replace_function(FF, [FD|Forms], Ret) ->
  replace_function(FF, Forms, [FD|Ret]).
  
  
  
  
  
  
  
Blog | Support | Training | Contact | API | Status | Twitter | Help | Security
© 2010 GitHub Inc. All rights reserved. | Terms of Service | Privacy Policy
Powered by the Dedicated Servers and
Cloud Computing of Rackspace Hosting®
Dedicated Server