Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add mock function into Timeout Task's process dictionary #237

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions lib/tesla/middleware/timeout.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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 _ ->
Expand Down
18 changes: 18 additions & 0 deletions test/tesla/middleware/timeout_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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