From 4d0159cfe61fa54e3a61a902df430ad316c13974 Mon Sep 17 00:00:00 2001 From: Jon Rowe Date: Mon, 4 Feb 2019 18:52:14 +0000 Subject: [PATCH] Prevent default Kernel imports from conflicting with allowed functions --- lib/double.ex | 9 ++++++++- test/double_test.exs | 8 ++++++++ test/support/test_module.ex | 1 + 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/lib/double.ex b/lib/double.ex index 2b004e0..34165b3 100644 --- a/lib/double.ex +++ b/lib/double.ex @@ -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 @@ -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}]) @@ -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 diff --git a/test/double_test.exs b/test/double_test.exs index 1d9c9f5..04e9ffc 100644 --- a/test/double_test.exs +++ b/test/double_test.exs @@ -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 diff --git a/test/support/test_module.ex b/test/support/test_module.ex index 9ffe38f..33c9a3a 100644 --- a/test/support/test_module.ex +++ b/test/support/test_module.ex @@ -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