在Elixir中如何模拟临时故障

时间:2017-10-27 08:37:06

标签: elixir ex-unit

我正在用Mox模拟一个HTTP调用(使用特斯拉):

  test "Token expiry is handled by re-applying for a token on the fly", %{conn: conn} do
    TeslaMock
    |> expect(:call, 8, fn env, _opts ->
      case env.url do
        "http://fake.server.com/v1/token" ->
          %{env | status: 200, body: Poison.encode!(
                     %{token_type: "Bearer",
                     access_token: "cHBtKbMDNdc3uX2LIhCy9eVwkodhEc87s6e5Fk0lRS",
                     expires_in: 86400})
          }
        "http://fake.server.com/v1/system" ->
          %{env | status: 200, body: Poison.encode!(%{uptime: 10})}
      end
    end)

    assert json_response(get(conn, "/v1/system"), 200) == %{"uptime" => 10}

我需要假服务器首先回复:401令牌过期到/ v1 / system,我的模块发出/ v1 / token,然后重试/ v1 / system并成功。 什么是实现这一目标的好方法?

1 个答案:

答案 0 :(得分:0)

您可以使用Agent来跟踪对/v1/system发出的请求数。然后,如果它是第一个请求,则返回401,否则返回200。

{:ok, counter} = Agent.start_link(fn -> 0 end)

TeslaMock
|> expect(:call, 8, fn env, _opts ->
  case env.url do
    "http://fake.server.com/v1/token" ->
      ...
    "http://fake.server.com/v1/system" ->
      # Increment the counter.
      Agent.update(counter, &(&1 + 1))
      if Agent.get(counter, &(&1)) == 1 do
        # First request.
        %{env | status: 401, body: ...}
      else
        # Second or later request.
        %{env | status: 200, body: Poison.encode!(%{uptime: 10})}
      end
  end
end)