Skip to content

Commit

Permalink
Merge pull request #32 from JonRowe/prevent-kernel-being-an-issue
Browse files Browse the repository at this point in the history
Prevent default Kernel imports from conflicting with allowed functions
  • Loading branch information
brandonjoyce authored Feb 6, 2019
2 parents 13c7288 + 4d0159c commit cb8b0e4
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 1 deletion.
9 changes: 8 additions & 1 deletion lib/double.ex
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,7 @@ defmodule Double do
code = Enum.reduce(funcs, code, fn({function_name, func}, acc) ->
{signature, message} = function_parts(function_name, func)
acc <> """
#{unimport_if_needed(function_name, func)}
def #{function_name}(#{signature}) do
#{function_body(mod, message, function_name, signature)}
end
Expand All @@ -211,7 +212,7 @@ defmodule Double do
defp function_body(double_id, message, function_name, signature) do
"""
test_pid = Double.Registry.whereis_test(\"#{double_id}\")
send(test_pid, #{message})
Kernel.send(test_pid, #{message})
pid = Double.Registry.whereis_double(\"#{double_id}\")
func_list = Double.func_list(pid)
Double.FuncList.apply(func_list, :#{function_name}, [#{signature}])
Expand All @@ -234,6 +235,12 @@ defmodule Double do
{signature, message}
end

defp unimport_if_needed(function_name, func) do
if Enum.member?(Kernel.__info__(:functions), {function_name, func_arity = arity(func)}) do
"import Kernel, except: [#{function_name}: #{func_arity}]"
end
end

defp arity(func) do
:erlang.fun_info(func)[:arity]
end
Expand Down
8 changes: 8 additions & 0 deletions test/double_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,14 @@ defmodule DoubleTest do
assert dbl.loaded_applications() == :ok
end

test "can override kernel functions" do
dbl =
double(TestModule)
|> allow(:send, fn _, _ -> :ok end)

assert dbl.send(:a, :b) == :ok
end

test "verifies valid behavior doubles" do
dbl =
TestBehaviour
Expand Down
1 change: 1 addition & 0 deletions test/support/test_module.ex
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ defmodule TestModule do
def process(x, y, z), do: {x, y, z}
def another_function, do: nil
def another_function(x), do: x
def send(a, b), do: {a, b}
end

0 comments on commit cb8b0e4

Please sign in to comment.