Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/honest mocks #75

Merged
merged 4 commits into from
Oct 11, 2012
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 71 additions & 36 deletions src/meck.erl
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@

%% Records
-record(state, {mod :: atom(),
can_expect :: any | [{atom(), non_neg_integer()}],
expects :: dict(),
valid = true :: boolean(),
history = [] :: history() | undefined,
Expand Down Expand Up @@ -148,6 +149,11 @@ new(Mod) when is_list(Mod) -> lists:foreach(fun new/1, Mod), ok.
%% </dd>
%% <dt>`no_history'</dt> <dd>Do not store history of meck calls.
%% </dd>
%% <dt>`non_strict'</dt><dd>A mock created with this option will allow setting
%% expectations on functions that are not exported
%% from the mocked module. With this option on it is
%% even possible to mock non existing modules.
%% </dd>
%% </dl>
-spec new(Mod:: atom() | [atom()], Options::[term()]) -> ok.
new(Mod, Options) when is_atom(Mod), is_list(Options) ->
Expand Down Expand Up @@ -187,11 +193,11 @@ expect(Mod, Func, StubFun)
when is_atom(Mod), is_atom(Func), is_function(StubFun) ->
{arity, Arity} = erlang:fun_info(StubFun, arity),
Clause = {arity_2_matcher(Arity), {meck_func, StubFun}},
call(Mod, {expect, {Func, Arity}, [Clause]});
check_expect_result(call(Mod, {expect, {Func, Arity}, [Clause]}));
expect(Mod, Func, ClauseSpecs)
when is_atom(Mod), is_atom(Func), is_list(ClauseSpecs) ->
{Arity, Clauses} = parse_clause_specs(Mod, Func, ClauseSpecs),
call(Mod, {expect, {Func, Arity}, Clauses});
{Arity, Clauses} = parse_clause_specs(ClauseSpecs),
check_expect_result(call(Mod, {expect, {Func, Arity}, Clauses}));
expect(Mod, Func, Expect) when is_list(Mod) ->
lists:foreach(fun(M) -> expect(M, Func, Expect) end, Mod),
ok.
Expand All @@ -211,13 +217,12 @@ expect(Mod, Func, Expect) when is_list(Mod) ->
RetSpec :: ret_spec().
expect(Mod, Func, Arity, RetSpec)
when is_atom(Mod), is_atom(Func), is_integer(Arity), Arity >= 0 ->
valid_expect(Mod, Func, Arity),
Clause = {arity_2_matcher(Arity), RetSpec},
call(Mod, {expect, {Func, Arity}, [Clause]});
check_expect_result(call(Mod, {expect, {Func, Arity}, [Clause]}));
expect(Mod, Func, ArgsPattern, RetSpec)
when is_atom(Mod), is_atom(Func), is_list(ArgsPattern) ->
{Arity, Clause} = parse_clause_spec(Mod, Func, {ArgsPattern, RetSpec}),
call(Mod, {expect, {Func, Arity}, [Clause]});
{Arity, Clause} = parse_clause_spec({ArgsPattern, RetSpec}),
check_expect_result(call(Mod, {expect, {Func, Arity}, [Clause]}));
expect(Mod, Func, ArgsSpec, RetSpec) when is_list(Mod) ->
lists:foreach(fun(M) -> expect(M, Func, ArgsSpec, RetSpec) end, Mod),
ok.
Expand All @@ -240,7 +245,7 @@ expect(Mod, Func, ArgsSpec, RetSpec) when is_list(Mod) ->
sequence(Mod, Func, Arity, Sequence)
when is_atom(Mod), is_atom(Func), is_integer(Arity), Arity >= 0 ->
Clause = {arity_2_matcher(Arity), seq(Sequence)},
call(Mod, {expect, {Func, Arity}, [Clause]});
check_expect_result(call(Mod, {expect, {Func, Arity}, [Clause]}));
sequence(Mod, Func, Arity, Sequence) when is_list(Mod) ->
lists:foreach(fun(M) -> sequence(M, Func, Arity, Sequence) end, Mod),
ok.
Expand All @@ -262,7 +267,7 @@ sequence(Mod, Func, Arity, Sequence) when is_list(Mod) ->
loop(Mod, Func, Arity, Loop)
when is_atom(Mod), is_atom(Func), is_integer(Arity), Arity >= 0 ->
Clause = {arity_2_matcher(Arity), loop(Loop)},
call(Mod, {expect, {Func, Arity}, [Clause]});
check_expect_result(call(Mod, {expect, {Func, Arity}, [Clause]}));
loop(Mod, Func, Arity, Loop) when is_list(Mod) ->
lists:foreach(fun(M) -> loop(M, Func, Arity, Loop) end, Mod),
ok.
Expand Down Expand Up @@ -466,7 +471,20 @@ raise(exit, Reason) -> {meck_raise, exit, Reason}.

%% @hidden
init([Mod, Options]) ->
WasSticky = case proplists:is_defined(unstick, Options) of
case proplists:get_bool(non_strict, Options) of
true ->
init([Mod, Options, any]);
_ ->
try
Exports = Mod:module_info(exports),
init([Mod, Options, Exports])
catch
error:undef ->
{stop, undefined_module}
end
end;
init([Mod, Options, CanExpect]) ->
WasSticky = case proplists:get_bool(unstick, Options) of
true -> {module, Mod} = code:ensure_loaded(Mod),
unstick_original(Mod);
_ -> false
Expand All @@ -479,8 +497,12 @@ init([Mod, Options]) ->
Expects = init_expects(Mod, Options),
try
_Bin = meck_mod:compile_and_load_forms(to_forms(Mod, Expects)),
{ok, #state{mod = Mod, expects = Expects, original = Original,
was_sticky = WasSticky, history=History}}
{ok, #state{mod = Mod,
can_expect = CanExpect,
expects = Expects,
original = Original,
was_sticky = WasSticky,
history = History}}
catch
exit:{error_loading_module, Mod, sticky_directory} ->
{stop, module_is_sticky}
Expand All @@ -491,15 +513,20 @@ handle_call({get_expect, FuncAri, Args}, _From, S) ->
{Expect, NewExpects} = get_expect(S#state.expects, S#state.mod, FuncAri,
Args),
{reply, Expect, S#state{expects = NewExpects}};
handle_call({expect, FuncAri, Clauses}, _From, S) ->
NewExpects = store_expect(S#state.mod, FuncAri,
Clauses,
S#state.expects),
{reply, ok, S#state{expects = NewExpects}};
handle_call({expect, FuncAri = {Func, Ari}, Clauses}, _From, S) ->
case validate_expect(S#state.mod, Func, Ari, S#state.can_expect) of
ok ->
NewExpects = store_expect(S#state.mod, FuncAri,
Clauses,
S#state.expects),
{reply, ok, S#state{expects = NewExpects}};
{error, Reason} ->
{reply, {error, Reason}, S}
end;
handle_call({delete, Func, Arity}, _From, S) ->
NewExpects = delete_expect(S#state.mod, {Func, Arity}, S#state.expects),
{reply, ok, S#state{expects = NewExpects}};
handle_call(history, _From, #state{history=undefined}=S) ->
handle_call(history, _From, S = #state{history = undefined}) ->
{reply, [], S};
handle_call(history, _From, S) ->
{reply, lists:reverse(S#state.history), S};
Expand All @@ -513,7 +540,7 @@ handle_call(stop, _From, S) ->
{stop, normal, ok, S}.

%% @hidden
handle_cast({add_history, _Item}, #state{history=undefined}=S) ->
handle_cast({add_history, _Item}, S = #state{history = undefined}) ->
{noreply, S};
handle_cast({add_history, Item}, S) ->
{noreply, S#state{history = [Item| S#state.history]}};
Expand Down Expand Up @@ -568,7 +595,8 @@ start(Mod, Options) ->

start(Func, Mod, Options) ->
SpawnOpt = proplists:get_value(spawn_opt, Options, []),
gen_server:Func({local, proc_name(Mod)}, ?MODULE, [Mod, Options], [{spawn_opt, SpawnOpt}]).
gen_server:Func({local, proc_name(Mod)}, ?MODULE, [Mod, Options],
[{spawn_opt, SpawnOpt}]).

cast(Mod, Msg) -> gen_server(cast, Mod, Msg).
call(Mod, Msg) -> gen_server(call, Mod, Msg).
Expand Down Expand Up @@ -606,11 +634,20 @@ unload_if_mocked(_P, L) ->

%% --- Mock handling ----------------------------------------------------------

valid_expect(M, F, A) ->
check_expect_result(ok) -> ok;
check_expect_result({error, Reason}) -> erlang:error(Reason).

validate_expect(M, F, A, CanExpect) ->
case expect_type(M, F, A) of
autogenerated -> erlang:error({cannot_mock_autogenerated, {M, F, A}});
builtin -> erlang:error({cannot_mock_builtin, {M, F, A}});
normal -> ok
autogenerated ->
{error, {cannot_mock_autogenerated, {M, F, A}}};
builtin ->
{error, {cannot_mock_builtin, {M, F, A}}};
normal ->
case CanExpect =:= any orelse lists:member({F, A}, CanExpect) of
true -> ok;
_ -> {error, {undefined_function, {M, F, A}}}
end
end.

init_expects(Mod, Options) ->
Expand All @@ -624,30 +661,28 @@ init_expects(Mod, Options) ->
passthrough_stub(Func, Arity) ->
{{Func, Arity}, [{arity_2_matcher(Arity), passthrough}]}.

parse_clause_specs(Mod, Func, ClauseSpecs) ->
parse_clause_specs(Mod, Func, ClauseSpecs, undefined, []).
parse_clause_specs(ClauseSpecs) ->
parse_clause_specs(ClauseSpecs, undefined, []).

parse_clause_specs(Mod, Func, [ClauseSpec | Rest], undefined, []) ->
{Arity, Clause} = parse_clause_spec(Mod, Func, ClauseSpec),
parse_clause_specs(Mod, Func, Rest, Arity, [Clause]);
parse_clause_specs(Mod, Func, [ClauseSpec | Rest], DeducedArity, Clauses) ->
{Arity, Clause} = parse_clause_spec(Mod, Func, ClauseSpec),
parse_clause_specs([ClauseSpec | Rest], undefined, []) ->
{Arity, Clause} = parse_clause_spec(ClauseSpec),
parse_clause_specs(Rest, Arity, [Clause]);
parse_clause_specs([ClauseSpec | Rest], DeducedArity, Clauses) ->
{Arity, Clause} = parse_clause_spec(ClauseSpec),
case Arity of
DeducedArity ->
parse_clause_specs(Mod, Func, Rest, DeducedArity,
[Clause | Clauses]);
parse_clause_specs(Rest, DeducedArity, [Clause | Clauses]);
_ ->
erlang:error({invalid_arity, {{expected, DeducedArity},
{actual, Arity},
{clause, Clause}}})
end;
parse_clause_specs(_Mod, _Func, [], DeducedArity, Clauses) ->
parse_clause_specs([], DeducedArity, Clauses) ->
{DeducedArity, lists:reverse(Clauses)}.


parse_clause_spec(Mod, Func, {ArgsPattern, RetSpec}) ->
parse_clause_spec({ArgsPattern, RetSpec}) ->
Arity = length(ArgsPattern),
valid_expect(Mod, Func, Arity),
MatchSpec = ets:match_spec_compile([?MATCH_SPEC(ArgsPattern)]),
Clause = {{pattern, ArgsPattern, MatchSpec}, RetSpec},
{Arity, Clause}.
Expand Down
43 changes: 28 additions & 15 deletions test/meck_tests.erl
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ setup() ->
% dbg:tracer(),
% dbg:p(all, call),
% dbg:tpl(meck, []),
ok = meck:new(mymod),
ok = meck:new(mymod, [non_strict]),
mymod.

teardown(Module) ->
Expand Down Expand Up @@ -165,7 +165,7 @@ validate_expected_error_(Mod) ->
?assertEqual(true, meck:validate(Mod)).

validate_chained_(Mod) ->
ok = meck:new(mymod2),
ok = meck:new(mymod2, [non_strict]),
ok = meck:expect(mymod2, test, fun() ->
meck:exception(error, test_error)
end),
Expand Down Expand Up @@ -507,7 +507,7 @@ sequence_(Mod) ->
?assert(meck:validate(Mod)).

sequence_multi_(Mod) ->
meck:new(mymod2),
meck:new(mymod2, [non_strict]),
Mods = [Mod, mymod2],
Sequence = [a, b, c, d, e],
?assertEqual(ok, meck:sequence(Mods, s, 2, Sequence)),
Expand Down Expand Up @@ -682,7 +682,7 @@ expect_arity_exception_(Mod) ->
?assertError(a, Mod:f(1001)).

loop_multi_(Mod) ->
meck:new(mymod2),
meck:new(mymod2, [non_strict]),
Mods = [Mod, mymod2],
Loop = [a, b, c, d, e],
?assertEqual(ok, meck:loop(Mods, l, 2, Loop)),
Expand Down Expand Up @@ -748,6 +748,19 @@ expect_ret_specs_(Mod) ->

%% --- Tests with own setup ----------------------------------------------------

undefined_module_test() ->
%% When/Then
?assertError(undefined_module, meck:new(blah, [no_link])).

undefined_function_test() ->
%% Given
meck:new(meck_test_module),
%% When/Then
meck:expect(meck_test_module, b, 0, ok),
?assertError({undefined_function, {meck_test_module, b, 1}},
meck:expect(meck_test_module, b, 1, ok)),
meck:unload(meck_test_module).

call_original_test() ->
false = code:purge(meck_test_module),
?assertEqual({module, meck_test_module}, code:load_file(meck_test_module)),
Expand All @@ -766,7 +779,7 @@ unload_renamed_original_test() ->

unload_all_test() ->
Mods = [test_a, test_b, test_c, test_d, test_e],
ok = meck:new(Mods),
ok = meck:new(Mods, [non_strict]),
?assertEqual(lists:sort(Mods), lists:sort(meck:unload())),
[?assertEqual(false, code:is_loaded(M)) || M <- Mods].

Expand All @@ -785,7 +798,7 @@ original_has_no_object_code_test() ->
ok = meck:unload(meck_on_disk).

passthrough_nonexisting_module_test() ->
ok = meck:new(mymod, [passthrough]),
ok = meck:new(mymod, [passthrough, non_strict]),
ok = meck:expect(mymod, test, fun() -> ok end),
?assertEqual(ok, mymod:test()),
ok = meck:unload(mymod).
Expand Down Expand Up @@ -915,7 +928,7 @@ cover_passthrough_test() ->

% @doc The mocked module is unloaded if the meck process crashes.
unload_when_crashed_test() ->
ok = meck:new(mymod),
ok = meck:new(mymod, [non_strict]),
?assertMatch({file, _}, code:is_loaded(mymod)),
SaltedName = mymod_meck,
Pid = whereis(SaltedName),
Expand All @@ -928,7 +941,7 @@ unload_when_crashed_test() ->

% @doc The mocked module is unloaded if the meck process crashes.
unlink_test() ->
ok = meck:new(mymod, [no_link]),
ok = meck:new(mymod, [no_link, non_strict]),
SaltedName = mymod_meck,
{links, Links} = process_info(whereis(SaltedName), links),
?assert(not lists:member(self(), Links)),
Expand All @@ -952,7 +965,7 @@ history_passthrough_test() ->

multi_test() ->
Mods = [mod1, mod2, mod3],
ok = meck:new(Mods),
ok = meck:new(Mods, [non_strict]),
ok = meck:expect(Mods, test, fun() -> ok end),
ok = meck:expect(Mods, test2, 0, ok),
[?assertEqual(ok, M:test()) || M <- Mods],
Expand All @@ -961,31 +974,31 @@ multi_test() ->

multi_invalid_test() ->
Mods = [mod1, mod2, mod3],
ok = meck:new(Mods),
ok = meck:new(Mods, [non_strict]),
ok = meck:expect(Mods, test, fun(1) -> ok end),
?assertError(function_clause, mod2:test(2)),
?assert(not meck:validate(Mods)),
ok = meck:unload(Mods).

multi_option_test() ->
Mods = [mod1, mod2, mod3],
ok = meck:new(Mods, [passthrough]),
ok = meck:new(Mods, [passthrough, non_strict]),
ok = meck:expect(Mods, test, fun() -> ok end),
[?assertEqual(ok, M:test()) || M <- Mods],
?assert(meck:validate(Mods)),
ok = meck:unload(Mods).

multi_shortcut_test() ->
Mods = [mod1, mod2, mod3],
ok = meck:new(Mods),
ok = meck:new(Mods, [non_strict]),
ok = meck:expect(Mods, test, 0, ok),
[?assertEqual(ok, M:test()) || M <- Mods],
?assert(meck:validate(Mods)),
ok = meck:unload(Mods).

multi_delete_test() ->
Mods = [mod1, mod2, mod3],
ok = meck:new(Mods),
ok = meck:new(Mods, [non_strict]),
ok = meck:expect(Mods, test, 0, ok),
?assertEqual(ok, meck:delete(Mods, test, 0)),
[?assertError(undef, M:test()) || M <- Mods],
Expand All @@ -995,7 +1008,7 @@ multi_delete_test() ->
multi_reset_test() ->
% Given
Mods = [mod1, mod2, mod3],
meck:new(Mods),
meck:new(Mods, [non_strict]),
meck:expect(Mods, test1, 0, ok),
meck:expect(Mods, test2, 0, ok),
mod1:test1(),
Expand Down Expand Up @@ -1042,7 +1055,7 @@ remote_teardown({Node, _Mod}) ->
ok = slave:stop(Node).

remote_meck_({Node, Mod}) ->
?assertEqual(ok, rpc:call(Node, meck, new, [Mod, [no_link]])),
?assertEqual(ok, rpc:call(Node, meck, new, [Mod, [no_link, non_strict]])),
?assertEqual(ok, rpc:call(Node, meck, expect, [Mod, test, 0, true])),
?assertEqual(true, rpc:call(Node, Mod, test, [])).

Expand Down