如何在 Elixir ExUnit.Case 的管道内断言 (Elixir)

How to assert inside a pipeline in Elixir ExUnit.Case (Elixir)

我有以下有效的测试:

  test "accepts a request on a socket and sends back a response (using tasks)" do
    spawn(HttpServer, :start, [4000])

    urls = [
      "http://localhost:4000/products",
      "http://localhost:4000/shops",
    ]

    urls
    |> Enum.map(&Task.async(fn -> HTTPoison.get(&1) end))
    |> Enum.map(&Task.await/1)
    |> Enum.map(&assert_successful_response/1)
  end

  defp assert_successful_response({:ok, response}) do
    assert response.status_code == 200
  end

但是,我正在寻找一种方法来删除 assert_successful_response 方法并在管道内进行断言。下面的示例举例说明了我正在努力完成的事情,但当然,它不起作用:

    urls
    |> Enum.map(&Task.async(fn -> HTTPoison.get(&1) end))
    |> Enum.map(&Task.await/1)
    |> Enum.map(&Task.async(fn(response) -> 
      assert response.status_code == 200
    end))

我该怎么做?

首先,当你不使用结果时,你不需要Enum.map/2;请改用 Enum.each/2

如果我正确理解了要求,这将有效:

urls
|> Enum.map(&Task.async(fn -> HTTPoison.get(&1) end))
|> Enum.map(&Task.await/1)
|> Enum.each(&assert(match?({:ok, %{status_code: 200}}, &1)))

或者,

assert(elem(&1, 0) == :ok and elem(&1, 1).status_code == 200))