Skip to content

Commit

Permalink
Reset to private mode once global owner is dead
Browse files Browse the repository at this point in the history
  • Loading branch information
edgurgel committed Feb 2, 2019
1 parent 029a616 commit b057988
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 7 deletions.
30 changes: 23 additions & 7 deletions lib/mimic/server.ex
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,8 @@ defmodule Mimic.Server do

def init([]) do
:ets.new(__MODULE__, [:named_table, :protected, :set])
:ets.insert_new(__MODULE__, {:mode, :private})
{:ok, %State{mode: :private}}
state = do_set_private_mode(%State{})
{:ok, state}
end

def handle_cast({:exit, pid}, state) do
Expand All @@ -136,6 +136,14 @@ defmodule Mimic.Server do
select = [{{{pid, :_}}, [], [true]}, {{{:_, :_}, pid}, [], [true]}]

:ets.select_delete(__MODULE__, select)

state =
if pid == state.global_pid do
do_set_private_mode(state)
else
state
end

%{state | expectations: expectations, stubs: stubs}
end

Expand Down Expand Up @@ -240,13 +248,11 @@ defmodule Mimic.Server do
end

def handle_call({:set_global_mode, owner_pid}, _from, state) do
:ets.insert(__MODULE__, {:mode, :global, owner_pid})
{:reply, :ok, %{state | global_pid: owner_pid, mode: :global}}
{:reply, :ok, do_set_global_mode(owner_pid, state)}
end

def handle_call(:set_private_mode, _from, state) do
:ets.insert(__MODULE__, {:mode, :private})
{:reply, :ok, %{state | global_pid: nil, mode: :private}}
{:reply, :ok, do_set_private_mode(state)}
end

def handle_call({:allow, module, owner_pid, allowed_pid}, _from, state = %State{mode: :private}) do
Expand All @@ -266,7 +272,7 @@ defmodule Mimic.Server do
_from,
state = %State{mode: :global}
) do
{:reply, {:error, :global_mode}, state}
{:reply, {:error, :global}, state}
end

def handle_call({:verify, pid}, _from, state) do
Expand Down Expand Up @@ -333,4 +339,14 @@ defmodule Mimic.Server do
{fun, _} = Code.eval_quoted({:fn, [], clause})
fun
end

defp do_set_global_mode(owner_pid, state) do
:ets.insert(__MODULE__, {:mode, :global, owner_pid})
%{state | global_pid: owner_pid, mode: :global}
end

defp do_set_private_mode(state) do
:ets.insert(__MODULE__, {:mode, :private})
%{state | global_pid: nil, mode: :private}
end
end
18 changes: 18 additions & 0 deletions test/mimic_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,24 @@ defmodule Mimic.Test do
end
end

describe "default mode" do
test "private mode is the default mode" do
Task.async(fn ->
Mimic.set_mimic_global()
stub(Calculator, :add, fn _, _ -> :stub end)

Task.async(fn ->
assert Calculator.add(3, 7) == :stub
end)
|> Task.await()
end)
|> Task.await()

stub(Calculator, :add, fn _, _ -> :private_stub end)
assert Calculator.add(3, 7) == :private_stub
end
end

describe "stub/1 private mode" do
setup :set_mimic_private

Expand Down

0 comments on commit b057988

Please sign in to comment.