eproxus / meck

A mocking library for Erlang
http://eproxus.github.io/meck
Apache License 2.0
811 stars 231 forks source link

Export access to original function in passthrough mode #70

Closed slfritchie closed 12 years ago

slfritchie commented 12 years ago

Hi, sorry I didn't cook up a pull request the usual way. This is a really small change, but it's tremendously useful. When a module is defined in passthrough mode, when doing the following:

meck:new(foo, [passthrough]),
meck:expect(foo, bar, fun(X) case random:uniform(100) of
    N when N < 50 ->
        %% somehow call the original foo:bar/1 function but with
        %% the same X or perhaps a modified X.
    _ ->
        %% Do something completely novel, like we usually
        %% do with Meck.
    end).

Using this new function, we could put the following into the first case clause:

meck:orig_apply(foo, bar, [X]);

or perhaps:

meck:orig_apply(foo, bar, [modify_somehow(X)]);

The small patch is:

diff --git a/src/meck.erl b/src/meck.erl
index 1669c32..6f8a577 100644
--- a/src/meck.erl
+++ b/src/meck.erl
@@ -40,6 +40,7 @@
 -export([called/4]).
 -export([num_calls/3]).
 -export([num_calls/4]).
+-export([orig_apply/3]).

 %% Callback exports
 -export([init/1]).
@@ -455,6 +456,9 @@ proc_name(Name) -> list_to_atom(atom_to_list(Name) ++ "_meck").

 original_name(Name) -> list_to_atom(atom_to_list(Name) ++ "_meck_original").

+orig_apply(Name, Func, Args) ->
+    erlang:apply(original_name(Name), Func, Args).
+
 wait_for_exit(Mod) ->
     MonitorRef = erlang:monitor(process, proc_name(Mod)),
     receive {'DOWN', MonitorRef, _Type, _Object, _Info} -> ok end.

Thanks for considering. I'm happily using this new function for nefarious testing purposes. The rest of Meck is quite useful, thanks for all of your work.

eproxus commented 12 years ago

Thanks! The passthrough/1 function that already exists already allows you to call the original function. However, it had one limitation that it exited the expect-function when it was called. This is now changed in c336ce1a63997c14a27776d019afe715e0ae24e1 (based on the solution in your patch) where you can also use the return value inside the expect-function:

meck:expect(m, f, fun(N) -> M = meck:passthrough([N+1]), M / 2 end).

(This also closes the old #2 issue on the same topic).