ad236d4cb35bf3deb33c389583411e7a8496728d
[anni] / test / pleroma / web / endpoint / metrics_exporter_test.exs
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.Endpoint.MetricsExporterTest do
6   # Modifies AppEnv, has to stay synchronous
7   use Pleroma.Web.ConnCase
8
9   alias Pleroma.Web.Endpoint.MetricsExporter
10
11   defp config do
12     Application.get_env(:prometheus, MetricsExporter)
13   end
14
15   describe "with default config" do
16     test "does NOT expose app metrics", %{conn: conn} do
17       conn
18       |> get(config()[:path])
19       |> json_response(404)
20     end
21   end
22
23   describe "when enabled" do
24     setup do
25       initial_config = config()
26       on_exit(fn -> Application.put_env(:prometheus, MetricsExporter, initial_config) end)
27
28       Application.put_env(
29         :prometheus,
30         MetricsExporter,
31         Keyword.put(initial_config, :enabled, true)
32       )
33     end
34
35     test "serves app metrics", %{conn: conn} do
36       conn = get(conn, config()[:path])
37       assert response = response(conn, 200)
38
39       for metric <- [
40             "http_requests_total",
41             "http_request_duration_microseconds",
42             "phoenix_controller_call_duration",
43             "telemetry_scrape_duration",
44             "erlang_vm_memory_atom_bytes_total"
45           ] do
46         assert response =~ ~r/#{metric}/
47       end
48     end
49
50     test "when IP whitelist configured, " <>
51            "serves app metrics only if client IP is whitelisted",
52          %{conn: conn} do
53       Application.put_env(
54         :prometheus,
55         MetricsExporter,
56         Keyword.put(config(), :ip_whitelist, ["127.127.127.127", {1, 1, 1, 1}, '255.255.255.255'])
57       )
58
59       conn
60       |> get(config()[:path])
61       |> json_response(404)
62
63       conn
64       |> Map.put(:remote_ip, {127, 127, 127, 127})
65       |> get(config()[:path])
66       |> response(200)
67     end
68   end
69 end