a73x

internal/server/api/hostinfo_api_test.go

Ref:   Size: 2.2 KiB   History

package api

import (
	"testing"

	"github.com/a73x/eitri/internal/server/registry"
	"github.com/a73x/eitri/internal/server/store"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

// Facts are persisted, so the HTTP host response carries them regardless of
// online state.
func TestHostResponseIncludesFacts(t *testing.T) {
	ts, st, _, _, _ := newServer(t)
	out := enroll(t, ts)
	hostID := out["host_id"]

	require.NoError(t, st.UpdateHostFacts(hostID, store.HostFacts{
		OSID: "debian", OSPretty: "Debian GNU/Linux 12 (bookworm)", OSVersion: "12",
		Kernel: "6.1.0-18-amd64", CPUModel: "AMD EPYC 7302P", Virt: "kvm",
	}))

	hosts := decodeJSONKeys(t, do(t, "GET", ts.URL+"/api/v1/hosts", testPAT, nil))
	require.Len(t, hosts, 1)
	assert.Equal(t, "Debian GNU/Linux 12 (bookworm)", hosts[0]["os_pretty"])
	assert.Equal(t, "6.1.0-18-amd64", hosts[0]["kernel"])
	assert.Equal(t, "kvm", hosts[0]["virt"])
}

// Metrics are registry-only: present when online, nil when the host has no
// live state.
func TestToHostResponseMetricsOnlyWhenOnline(t *testing.T) {
	h := store.Host{ID: "h1", Name: "host-a", OSPretty: "Debian GNU/Linux 12 (bookworm)"}

	online := registry.HostState{
		Metrics: registry.Metrics{UptimeS: 3600, MemUsedMB: 2048, Load1: 1.5, DiskFreeGB: 80},
		Online:  true,
	}
	hr := toHostResponse(h, online, true, store.Alloc{})
	require.NotNil(t, hr.Metrics)
	assert.Equal(t, int64(3600), hr.Metrics.UptimeS)
	assert.Equal(t, int64(2048), hr.Metrics.MemUsedMB)
	assert.InDelta(t, 1.5, hr.Metrics.Load1, 0.001)
	// Facts ride along even for a value-built response.
	assert.Equal(t, "Debian GNU/Linux 12 (bookworm)", hr.OSPretty)

	offline := toHostResponse(h, registry.HostState{}, false, store.Alloc{})
	assert.Nil(t, offline.Metrics, "metrics omitted when the host is not online")

	// Stale registry state (reported once, then went silent): ok=true but
	// Online=false. Metrics must NOT be served stale — gated on Online, not ok.
	stale := registry.HostState{
		Metrics: registry.Metrics{UptimeS: 3600, Load1: 1.5},
		Online:  false,
	}
	hr = toHostResponse(h, stale, true, store.Alloc{})
	assert.Nil(t, hr.Metrics, "stale (offline-but-known) host must not serve live metrics")
}