dashbitco / mox

Mocks and explicit contracts in Elixir
1.35k stars 77 forks source link

Support registered process names in explicit allowances #43

Closed sgrshah closed 6 years ago

sgrshah commented 6 years ago

Hello, thank you for maintaining Mox!

Recently, I was attempting to declare an explicit allowance so that a child process could utilize the expectations defined in my test process. I attempted to create an allowance for a process with a registered name (called Verifier.Scheduler), which threw a FunctionClauseError:

  1) test call/2 resolves entitlements (Verifier.SchedulerTest)
     test/verifier/scheduler_test.exs:45
     ** (FunctionClauseError) no function clause matching in Mox.allow/3

     The following arguments were given to Mox.allow/3:

         # 1
         Verifier.Worker.Mock

         # 2
         #PID<0.386.0>

         # 3
         Verifier.Scheduler

     Attempted function clauses (showing 2 out of 2):

         def allow(_mock, owner_pid, allowed_pid) when owner_pid == allowed_pid
         def allow(mock, owner_pid, allowed_pid) when is_atom(mock) and is_pid(owner_pid) and is_pid(allowed_pid)

     code: allow(Verifier.Worker.Mock, self(), Verifier.Scheduler)
     stacktrace:
       (mox) lib/mox.ex:431: Mox.allow/3
       test/verifier/scheduler_test.exs:51: (test)

It looks like Mox does not currently support explicit allowances with registered processes names. I was able to work around this limitation by first fetching the pid of the registered process:

  pid = Process.whereis(Verifier.Scheduler)

I thought it might be helpful to add the following function clause to support explicit allowances with registered names:

def allow(mock, owner_pid, allowed_name) when is_atom(allowed_name) do
  allowed_pid = Process.whereis(allowed_name)
  allow(mock, owner_pid, allowed_pid)
end

Would this be helpful? If so, I can create a related PR.

josevalim commented 6 years ago

Yes, please send a PR. We should just call GenServer.whereis, as that will support atoms, the registry, etc.

sgrshah commented 6 years ago

Great, will do!