aprs.me/test/aprsme/telemetry/database_metrics_test.exs
Graham McIntire aa0c6e6566
refactor: pattern-match in DeviceCache and DatabaseMetrics + add tests
- DeviceCache.pattern_matches?: replace a 3-branch `cond` with a
  two-clause `case` on `String.contains?(pattern, "?")`. The old `*`
  branch was dead code (it did the same exact-match compare as the
  fallback), so it's removed.
- Telemetry.DatabaseMetrics.collect_postgres_metrics: dispatch on
  environment atom via multi-clause private functions instead of
  `if Application.get_env(...) == :test`.

New tests:
- DeviceCache wildcard/exact lookup paths exercised via a seeded cache.
- MobileUserSocket connect/3 for x_headers/peer_data/empty info and
  rate-limit deny.
- DatabaseMetrics pool-metrics emission captured via :telemetry handler
  and the :test-env short-circuit.
2026-04-23 13:46:00 -05:00

59 lines
1.8 KiB
Elixir

defmodule Aprsme.Telemetry.DatabaseMetricsTest do
# Attaches telemetry handlers at test-specific event names so each test is
# isolated, but we still keep async: false to avoid handler-name collisions
# in process-global state.
use ExUnit.Case, async: false
alias Aprsme.Telemetry.DatabaseMetrics
defp attach_collector(event, tag \\ to_string(System.unique_integer([:positive]))) do
test_pid = self()
handler_id = "test-#{tag}-#{Enum.join(event, ",")}"
:telemetry.attach(
handler_id,
event,
fn ^event, measurements, metadata, _ ->
send(test_pid, {:telemetry, event, measurements, metadata})
end,
nil
)
on_exit(fn -> :telemetry.detach(handler_id) end)
handler_id
end
describe "collect_postgres_metrics/0 in :test env" do
test "is a no-op returning :ok" do
original = Application.get_env(:aprsme, :env)
Application.put_env(:aprsme, :env, :test)
try do
assert DatabaseMetrics.collect_postgres_metrics() == :ok
after
Application.put_env(:aprsme, :env, original)
end
end
end
describe "collect_db_pool_metrics/0" do
test "emits [:aprsme, :repo, :pool] telemetry with pool_size from config" do
attach_collector([:aprsme, :repo, :pool])
DatabaseMetrics.collect_db_pool_metrics()
assert_receive {:telemetry, [:aprsme, :repo, :pool], measurements, _}, 1_000
assert Map.has_key?(measurements, :size)
assert Map.has_key?(measurements, :idle)
assert Map.has_key?(measurements, :busy)
assert Map.has_key?(measurements, :available)
assert Map.has_key?(measurements, :queue_length)
assert Map.has_key?(measurements, :total)
end
end
describe "collect_pgbouncer_metrics/0" do
test "is a no-op returning :ok" do
assert DatabaseMetrics.collect_pgbouncer_metrics() == :ok
end
end
end