forked from peburrows/goth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoth_test.exs
100 lines (82 loc) · 2.56 KB
/
goth_test.exs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
defmodule GothTest do
use ExUnit.Case, async: true
test "fetch/1", %{test: test} do
now = System.system_time(:second)
bypass = Bypass.open()
Bypass.expect(bypass, fn conn ->
body = ~s|{"access_token":"dummy","expires_in":3599,"token_type":"Bearer"}|
Plug.Conn.resp(conn, 200, body)
end)
config = [
name: test,
source:
{:service_account, random_service_account_credentials(),
url: "http://localhost:#{bypass.port}"}
]
start_supervised!({Goth, config})
{:ok, token} = Goth.fetch(test)
assert token.token == "dummy"
assert token.type == "Bearer"
assert_in_delta token.expires, now + 3599, 1
Bypass.down(bypass)
{:ok, ^token} = Goth.fetch(test)
end
@tag :capture_log
test "retries", %{test: test} do
Process.flag(:trap_exit, true)
pid = self()
bypass = Bypass.open()
Bypass.expect(bypass, fn conn ->
send(pid, :pong)
Plug.Conn.resp(conn, 500, "oops")
end)
Goth.Server.start_link(
name: test,
source:
{:service_account, random_service_account_credentials(),
url: "http://localhost:#{bypass.port}"},
http_client: {Goth.HTTPClient.Hackney, []},
retry_after: 10
)
# higher timeouts since calculating JWT is expensive
assert_receive :pong, 1000
assert_receive :pong, 1000
assert_receive :pong, 1000
assert_receive {:EXIT, _,
{%RuntimeError{message: "too many failed attempts to refresh" <> _}, _}},
1000
end
test "refresh", %{test: test} do
pid = self()
bypass = Bypass.open()
Bypass.expect(bypass, fn conn ->
send(pid, :pong)
body = ~s|{"access_token":#{System.unique_integer()},"expires_in":1,"token_type":"Bearer"}|
Plug.Conn.resp(conn, 200, body)
end)
config = [
name: test,
source:
{:service_account, random_service_account_credentials(),
url: "http://localhost:#{bypass.port}"},
retries: 0
]
start_supervised!({Goth, config})
# higher timeouts since calculating JWT is expensive
assert_receive :pong, 1000
assert_receive :pong, 1000
assert_receive :pong, 1000
end
defp random_service_account_credentials() do
%{
"private_key" => random_private_key(),
"client_email" => "[email protected]",
"token_uri" => "/"
}
end
defp random_private_key() do
private_key = :public_key.generate_key({:rsa, 2048, 65537})
{:ok, private_key}
:public_key.pem_encode([:public_key.pem_entry_encode(:RSAPrivateKey, private_key)])
end
end