Skip to content

Commit

Permalink
Move add expectation error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
ypconstante committed Jun 23, 2024
1 parent 2ddd80c commit 79a2363
Showing 1 changed file with 34 additions and 30 deletions.
64 changes: 34 additions & 30 deletions lib/mox.ex
Original file line number Diff line number Diff line change
Expand Up @@ -685,11 +685,8 @@ defmodule Mox do
:ok ->
:ok

{:error, error} when is_binary(error) ->
raise ArgumentError, error

{:error, error} ->
raise error
raise_cannot_add_expectation!(error, mock)
end
end

Expand All @@ -700,14 +697,41 @@ defmodule Mox do
:ok ->
:ok

{:error, error} when is_binary(error) ->
raise ArgumentError, error

{:error, error} ->
raise error
raise_cannot_add_expectation!(error, mock)
end
end

defp raise_cannot_add_expectation!(
%NimbleOwnership.Error{reason: {:already_allowed, owner_pid}},
mock
) do
inspected = inspect(self())

raise ArgumentError, """
cannot add expectations/stubs to #{inspect(mock)} in the current process (#{inspected}) \
because the process has been allowed by #{inspect(owner_pid)}. \
You cannot define expectations/stubs in a process that has been allowed
"""
end

defp raise_cannot_add_expectation!(
%NimbleOwnership.Error{reason: {:not_shared_owner, global_pid}},
mock
) do
inspected = inspect(self())

raise ArgumentError, """
cannot add expectations/stubs to #{inspect(mock)} in the current process (#{inspected}) \
because Mox is in global mode and the global process is #{inspect(global_pid)}. \
Only the process that set Mox to global can set expectations/stubs in global mode
"""
end

defp raise_cannot_add_expectation!(error, _mock) do
raise error
end

@doc """
Allows other processes to share expectations and stubs
defined by owner process.
Expand Down Expand Up @@ -937,28 +961,8 @@ defmodule Mox do
update_fun = &{:ok, init_or_merge_expectations(&1, key_expectation_list)}

case get_and_update(owner_pid, mock, update_fun) do
{:ok, value} ->
value

{:error, %NimbleOwnership.Error{reason: {:already_allowed, _}}} ->
inspected = inspect(self())

{:error,
"""
cannot add expectations/stubs to #{inspect(mock)} in the current process (#{inspected}) \
because the process has been allowed by #{inspect(owner_pid)}. \
You cannot define expectations/stubs in a process that has been allowed
"""}

{:error, %NimbleOwnership.Error{reason: {:not_shared_owner, global_pid}}} ->
inspected = inspect(self())

{:error,
"""
cannot add expectations/stubs to #{inspect(mock)} in the current process (#{inspected}) \
because Mox is in global mode and the global process is #{inspect(global_pid)}. \
Only the process that set Mox to global can set expectations/stubs in global mode
"""}
{:ok, _value} ->
:ok

{:error, error} ->
{:error, error}
Expand Down

0 comments on commit 79a2363

Please sign in to comment.