Skip to content

Commit 601e7b6

Browse files
authored
fix: bring back searching for mocks in ancestors (#771)
1 parent c53bd1b commit 601e7b6

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

lib/tesla/mock.ex

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,15 @@ defmodule Tesla.Mock do
229229

230230
# Gets the mock fun for the current process or its ancestors
231231
defp pdict_get do
232-
potential_mock_holder_pids = [self() | Enum.reverse(Process.get(:"$callers", []))]
232+
callers = Process.get(:"$callers", [])
233+
# TODO: the standard way is to just look in $callers.
234+
# However, we were using $ancestors before and users were depending on that behaviour
235+
# https://github.com/elixir-tesla/tesla/issues/765
236+
# To make sure we don't break existing flows,
237+
# we will check mocks *both* in $callers and $ancestors
238+
# We might want to remove checking in $ancestors in a major release
239+
ancestors = Process.get(:"$ancestors", [])
240+
potential_mock_holder_pids = [self() | Enum.reverse(callers) ++ Enum.reverse(ancestors)]
233241

234242
Enum.find_value(potential_mock_holder_pids, nil, fn pid ->
235243
{:dictionary, process_dictionary} = Process.info(pid, :dictionary)

test/tesla/mock_test.exs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,31 @@ defmodule Tesla.MockTest do
148148
end
149149
end
150150

151+
describe "agent" do
152+
defmodule MyAgent do
153+
use Agent
154+
155+
def start_link(_arg) do
156+
Agent.start_link(fn -> Client.get!("/ancestors-test") end, name: __MODULE__)
157+
end
158+
end
159+
160+
# TODO: the standard way is to just look in $callers.
161+
# However, we were using $ancestors before and users were depending on that behaviour
162+
# https://github.com/elixir-tesla/tesla/issues/765
163+
# To make sure we don't break existing flows,
164+
# we will check mocks *both* in $callers and $ancestors
165+
# We might want to remove checking in $ancestors in a major release
166+
test "allows mocking in the ancestor" do
167+
mock(fn
168+
%{url: "/ancestors-test"} ->
169+
{:ok, %Tesla.Env{status: 200, body: "ancestors work"}}
170+
end)
171+
172+
{:ok, _pid} = MyAgent.start_link([])
173+
end
174+
end
175+
151176
describe "without mock" do
152177
test "raise on unmocked request" do
153178
assert_raise Tesla.Mock.Error, fn ->

0 commit comments

Comments
 (0)