diff --git a/lib/tesla/middleware/timeout.ex b/lib/tesla/middleware/timeout.ex index 1e5fb1a0..54adee1e 100644 --- a/lib/tesla/middleware/timeout.ex +++ b/lib/tesla/middleware/timeout.ex @@ -37,8 +37,14 @@ defmodule Tesla.Middleware.Timeout do end defp safe_async(func) do + mock_fun = Process.get(Tesla.Mock) + Task.async(fn -> try do + if(is_function(mock_fun)) do + Process.put(Tesla.Mock, mock_fun) + end + {:ok, func.()} rescue e in _ -> diff --git a/test/tesla/middleware/timeout_test.exs b/test/tesla/middleware/timeout_test.exs index c416b027..13cf7cf7 100644 --- a/test/tesla/middleware/timeout_test.exs +++ b/test/tesla/middleware/timeout_test.exs @@ -49,6 +49,12 @@ defmodule Tesla.Middleware.TimeoutTest do end end + defmodule MockedClient do + use Tesla + + plug Tesla.Middleware.Timeout + end + describe "using custom timeout (100ms)" do test "should return timeout error when the stack timeout" do assert {:error, :timeout} = Client.get("/sleep_150ms") @@ -95,4 +101,16 @@ defmodule Tesla.Middleware.TimeoutTest do assert catch_exit(Client.get("/exit")) == :exit_value end end + + describe "using Tesla.Mock and timeouts" do + test "should return the mocked response instead of mock error" do + Application.put_env(:tesla, MockedClient, adapter: Tesla.Mock) + + Tesla.Mock.mock(fn %{method: :get, url: "https://mocked.test.com/path"} -> + %Tesla.Env{status: 200} + end) + + assert {:ok, %Tesla.Env{status: 200}} = MockedClient.get("https://mocked.test.com/path") + end + end end