Skip to content

Commit 7579d9f

Browse files
carrascoacdyordis
andauthored
Improve Mock module to work properly with Timeout middleware (#668)
Co-authored-by: Yordis Prieto <[email protected]>
1 parent 40966e5 commit 7579d9f

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

lib/tesla/mock.ex

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,16 @@ defmodule Tesla.Mock do
226226
end
227227

228228
defp pdict_set(fun), do: Process.put(__MODULE__, fun)
229-
defp pdict_get, do: Process.get(__MODULE__)
229+
230+
# Gets the mock fun for the current process or its ancestors
231+
defp pdict_get do
232+
pid_holder =
233+
Enum.find(Process.get(:"$ancestors", []), self(), fn ancestor ->
234+
!is_nil(Process.get(ancestor, __MODULE__))
235+
end)
236+
237+
pid_holder |> Process.info() |> Keyword.get(:dictionary) |> Keyword.get(__MODULE__)
238+
end
230239

231240
defp agent_set(fun) do
232241
case Process.whereis(__MODULE__) do

test/tesla/mock_test.exs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,17 @@ defmodule Tesla.MockTest do
8484
assert env.status == 201
8585
assert env.body == %{"id" => 42}
8686
end
87+
88+
test "mock a request inside a spawned process" do
89+
task =
90+
Task.async(fn ->
91+
assert {:ok, %Tesla.Env{} = env} = Client.get("/json")
92+
assert env.status == 200
93+
assert env.body == %{"json" => 123}
94+
end)
95+
96+
Task.await(task)
97+
end
8798
end
8899

89100
describe "without mock" do

0 commit comments

Comments
 (0)