@@ -2,8 +2,10 @@ defmodule RealtimeWeb.MetricsControllerTest do
22 # Usage of Clustered
33 # Also changing Application env
44 use RealtimeWeb.ConnCase , async: false
5+ alias Realtime.GenRpc
56
67 import ExUnit.CaptureLog
8+ use Mimic
79
810 setup_all do
911 metrics_tags = % {
@@ -45,9 +47,13 @@ defmodule RealtimeWeb.MetricsControllerTest do
4547 end
4648
4749 test "returns 200 and log on timeout" , % { conn: conn } do
48- current_value = Application . get_env ( :realtime , :metrics_rpc_timeout )
49- on_exit ( fn -> Application . put_env ( :realtime , :metrics_rpc_timeout , current_value ) end )
50- Application . put_env ( :realtime , :metrics_rpc_timeout , 0 )
50+ Mimic . stub ( GenRpc , :call , fn node , mod , func , args , opts ->
51+ if node != node ( ) do
52+ { :error , :rpc_error , :timeout }
53+ else
54+ call_original ( GenRpc , :call , [ node , mod , func , args , opts ] )
55+ end
56+ end )
5157
5258 log =
5359 capture_log ( fn ->
@@ -84,4 +90,64 @@ defmodule RealtimeWeb.MetricsControllerTest do
8490 |> response ( 403 )
8591 end
8692 end
93+
94+ describe "GET /metrics/:region" do
95+ setup % { conn: conn } do
96+ # The metrics pipeline requires authentication
97+ jwt_secret = Application . fetch_env! ( :realtime , :metrics_jwt_secret )
98+ token = generate_jwt_token ( jwt_secret , % { } )
99+ authenticated_conn = put_req_header ( conn , "authorization" , "Bearer #{ token } " )
100+
101+ { :ok , conn: authenticated_conn }
102+ end
103+
104+ test "returns 200" , % { conn: conn } do
105+ assert response =
106+ conn
107+ |> get ( ~p" /metrics/ap-southeast-2" )
108+ |> text_response ( 200 )
109+
110+ # Check prometheus like metrics
111+ assert response =~
112+ "# HELP beam_system_schedulers_online_info The number of scheduler threads that are online."
113+
114+ assert response =~ "region=\" ap-southeast-2\" "
115+ refute response =~ "region=\" us-east-1\" "
116+ end
117+
118+ test "returns 200 and log on timeout" , % { conn: conn } do
119+ Mimic . stub ( GenRpc , :call , fn _node , _mod , _func , _args , _opts ->
120+ { :error , :rpc_error , :timeout }
121+ end )
122+
123+ log =
124+ capture_log ( fn ->
125+ assert response =
126+ conn
127+ |> get ( ~p" /metrics/ap-southeast-2" )
128+ |> text_response ( 200 )
129+
130+ assert response == ""
131+ end )
132+
133+ assert log =~ "Cannot fetch metrics from the node"
134+ end
135+
136+ test "returns 403 when authorization header is missing" , % { conn: conn } do
137+ assert conn
138+ |> delete_req_header ( "authorization" )
139+ |> get ( ~p" /metrics/ap-southeast-2" )
140+ |> response ( 403 )
141+ end
142+
143+ test "returns 403 when authorization header is wrong" , % { conn: conn } do
144+ token = generate_jwt_token ( "bad_secret" , % { } )
145+
146+ assert _ =
147+ conn
148+ |> put_req_header ( "authorization" , "Bearer #{ token } " )
149+ |> get ( ~p" /metrics/ap-southeast-2" )
150+ |> response ( 403 )
151+ end
152+ end
87153end
0 commit comments