【问题标题】:How to assert inside a pipeline in Elixir ExUnit.Case (Elixir)如何在 Elixir ExUnit.Case (Elixir) 中的管道内断言
【发布时间】:2021-03-16 23:52:42
【问题描述】:

我正在进行以下测试:

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

我该怎么做?

【问题讨论】:

    标签: elixir ex-unit


    【解决方案1】:

    首先,不使用结果时不需要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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-25
      • 2021-03-08
      • 1970-01-01
      • 2015-02-20
      • 1970-01-01
      相关资源
      最近更新 更多