Search code examples
elixirex-unit

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


I have the following test that is working:

  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

However, I'm searching for a way to remove the assert_successful_response method and do the assertion inside the pipeline. The example below exemplify what I'm trying to accomplish, but of course, it isn't working:

    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))

How can I do that?


Solution

  • In the first place, you don’t need Enum.map/2 when you don’t use the result; use Enum.each/2 instead.

    If I understood the requirement properly, this would work:

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

    or, alternatively,

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