proxMon/server/test/server/metrics_test.exs

66 lines
2.3 KiB
Elixir

defmodule Server.MetricsTest do
use Server.DataCase, async: true
alias Server.Metrics
alias Server.Hosts
setup do
{:ok, {host, _token}} = Hosts.create_host("pve-01")
%{host: host}
end
describe "record_sample/4" do
test "inserts a metric row with the given payload", %{host: host} do
ts = DateTime.utc_now()
payload = %{"host" => %{"load1" => 0.5}}
assert {:ok, metric} = Metrics.record_sample(host.id, "fast", ts, payload)
assert metric.host_id == host.id
assert metric.interval_type == "fast"
assert metric.payload == payload
assert metric.collected_at == ts
end
test "rejects unknown interval_type", %{host: host} do
ts = DateTime.utc_now()
assert {:error, cs} = Metrics.record_sample(host.id, "nope", ts, %{})
assert %{interval_type: ["is invalid"]} = errors_on(cs)
end
test "rejects unknown host_id" do
ts = DateTime.utc_now()
assert {:error, cs} = Metrics.record_sample(999_999, "fast", ts, %{})
assert %{host: ["does not exist"]} = errors_on(cs)
end
end
describe "latest_sample/2" do
test "returns most recent sample for a host and interval", %{host: host} do
{:ok, _} = Metrics.record_sample(host.id, "fast", dt(-60), %{"v" => 1})
{:ok, _} = Metrics.record_sample(host.id, "fast", dt(-30), %{"v" => 2})
{:ok, _} = Metrics.record_sample(host.id, "fast", dt(-10), %{"v" => 3})
assert %{payload: %{"v" => 3}} = Metrics.latest_sample(host.id, "fast")
end
test "returns nil when no samples exist", %{host: host} do
assert Metrics.latest_sample(host.id, "fast") == nil
end
end
describe "delete_older_than/1" do
test "deletes samples with collected_at before the cutoff", %{host: host} do
{:ok, _} = Metrics.record_sample(host.id, "fast", dt(-3600 * 50), %{"v" => "old"})
{:ok, keep} = Metrics.record_sample(host.id, "fast", dt(-60), %{"v" => "fresh"})
cutoff = DateTime.add(DateTime.utc_now(), -48 * 3600, :second)
assert {1, nil} = Metrics.delete_older_than(cutoff)
remaining = Server.Repo.all(Server.Schema.Metric)
assert length(remaining) == 1
assert hd(remaining).id == keep.id
end
end
defp dt(offset_seconds), do: DateTime.add(DateTime.utc_now(), offset_seconds, :second)
end