PSPDFKit-labs / bypass

Bypass provides a quick way to create a custom plug that can be put in place instead of an actual HTTP server to return prebaked responses to client requests.
https://hex.pm/packages/bypass
MIT License
964 stars 111 forks source link

How to use bypass with Finch? #116

Closed danicuki closed 3 years ago

danicuki commented 3 years ago

My project uses Finch to make parallel HTTP requests.

I tried to add bypass to my tests, but the HTTP requests are not being detected. When I run the test, I get this error:

No HTTP request arrived at Bypass

Here is my test:

defmodule MyClientTest do
  use ExUnit.Case, async: true

  setup do
    bypass = Bypass.open()
    {:ok, bypass: bypass}
  end

  describe "list_apps" do
    test "should have an expected app", %{bypass: bypass} do
      {:ok, contents} = File.read("test/apps.json")

      Bypass.expect(
        bypass,
        fn conn ->
          Plug.Conn.resp(conn, 200, contents)
        end
      )

      list_apps = MyClient.list_apps()
      assert length(list_apps) == 57
    end
  end
end

Here is my MyClient module:

defmodule MyClient do
  alias Finch.Response

  def child_spec do
    {Finch,
     name: __MODULE__,
     pools: %{
       "https://myapp.com" => [size: 100]
     }}
  end

  def applications_response do
    :get
    |> Finch.build("https://myapp.com/v2/apps.json")
    |> Finch.request(__MODULE__)
  end

  def handle_applications_response({:ok, %Response{body: body}}) do
    body
    |> Jason.decode!()
    end
  end

  def list_apps do
    handle_applications_response(applications_response())
  end

end
wkirschbaum commented 3 years ago

I don't think bypass does anything magical, so you still have to set your host on the client to the bypass listener: host = "http://localhost:#{bypass.port}"

ream88 commented 3 years ago

@wkirschbaum is right, basically you need to instruct Finch to use another URL for testing. I also build an example app here: https://github.com/ream88/bypass-issue116