Skip to content

Commit

Permalink
Improve Mock module to work properly with Timeout middleware (#668)
Browse files Browse the repository at this point in the history
Co-authored-by: Yordis Prieto <[email protected]>
  • Loading branch information
carrascoacd and yordis authored Apr 25, 2024
1 parent 40966e5 commit 7579d9f
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
11 changes: 10 additions & 1 deletion lib/tesla/mock.ex
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,16 @@ defmodule Tesla.Mock do
end

defp pdict_set(fun), do: Process.put(__MODULE__, fun)
defp pdict_get, do: Process.get(__MODULE__)

# Gets the mock fun for the current process or its ancestors
defp pdict_get do
pid_holder =
Enum.find(Process.get(:"$ancestors", []), self(), fn ancestor ->
!is_nil(Process.get(ancestor, __MODULE__))
end)

pid_holder |> Process.info() |> Keyword.get(:dictionary) |> Keyword.get(__MODULE__)
end

defp agent_set(fun) do
case Process.whereis(__MODULE__) do
Expand Down
11 changes: 11 additions & 0 deletions test/tesla/mock_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,17 @@ defmodule Tesla.MockTest do
assert env.status == 201
assert env.body == %{"id" => 42}
end

test "mock a request inside a spawned process" do
task =
Task.async(fn ->
assert {:ok, %Tesla.Env{} = env} = Client.get("/json")
assert env.status == 200
assert env.body == %{"json" => 123}
end)

Task.await(task)
end
end

describe "without mock" do
Expand Down

0 comments on commit 7579d9f

Please sign in to comment.