1

我正在使用 Mox 模拟 HTTP 调用(使用 Tesla),如下所示:

  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 token expired to /v1/system,我的模块发出/v1/token,然后重试/v1/system并成功。有什么好方法可以做到这一点?

4

1 回答 1

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)
于 2017-10-27T08:46:09.737 回答