【问题标题】:How to use bypass with Finch in Elixir tests?如何在 Elixir 测试中使用 Finch 旁路?
【发布时间】:2021-03-28 17:39:11
【问题描述】:

我的项目使用 Finch 发出并行 HTTP 请求。

我尝试在我的测试中添加绕过,但未检测到 HTTP 请求。当我运行测试时,我得到这个错误:

No HTTP request arrived at Bypass

这是我的测试:

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

这是我的 MyClient 模块:

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

【问题讨论】:

  • 我从来没有使用过旁路,但是看看文档...你在test/test_helper.exs 中开始绕过应用程序了吗?

标签: elixir finch


【解决方案1】:

无论您点击什么 URI,Bypass 都不会接管 HTTP 连接。它在 localhost 上的随机端口上设置了一个测试服务器。您需要获取该端口 (bypass.port),使用它构造一个 localhost URI,然后将该 URI 传递给您的测试,以便被调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多