我正在用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并成功。 什么是实现这一目标的好方法?
答案 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)