package agentsource import ( "context" "errors" "testing" "time" "github.com/itworx/pulse/internal/agentstore" "github.com/itworx/pulse/internal/datasource" ) type healthReader map[agentstore.Capability]agentstore.Snapshot func (r healthReader) Latest(_ context.Context, capability agentstore.Capability) (agentstore.Snapshot, error) { snapshot, ok := r[capability] if !ok { return agentstore.Snapshot{}, agentstore.ErrNoSnapshot } return snapshot, nil } func TestHealthRequiresEveryCapabilityToBeFresh(t *testing.T) { now := time.Date(2026, 8, 12, 1, 0, 0, 0, time.UTC) reader := healthReader{ agentstore.CapabilityHost: { Capability: agentstore.CapabilityHost, ObservedAt: now.Add(-time.Second), ReceivedAt: now.Add(-time.Second), }, agentstore.CapabilityProcesses: { Capability: agentstore.CapabilityProcesses, ObservedAt: now.Add(-2 * time.Second), ReceivedAt: now.Add(-2 * time.Second), }, } health, err := Health(context.Background(), reader, []agentstore.Capability{agentstore.CapabilityHost, agentstore.CapabilityProcesses}, Windows{}, now) if err != nil { t.Fatal(err) } if health.State != datasource.HealthHealthy || health.LastSuccess != now.Add(-2*time.Second) { t.Fatalf("health = %#v", health) } missing, err := Health(context.Background(), reader, []agentstore.Capability{agentstore.CapabilityHost, agentstore.CapabilityContainers}, Windows{}, now) if err != nil { t.Fatal(err) } if missing.State != datasource.HealthUnknown || missing.ReasonCode != ReasonUnavailable { t.Fatalf("missing health = %#v", missing) } } func TestHealthRejectsStaleCapabilityAndPropagatesCancellation(t *testing.T) { now := time.Date(2026, 8, 12, 1, 0, 0, 0, time.UTC) reader := healthReader{agentstore.CapabilityHost: { Capability: agentstore.CapabilityHost, ObservedAt: now.Add(-time.Hour), ReceivedAt: now.Add(-time.Hour), }} health, err := Health(context.Background(), reader, []agentstore.Capability{agentstore.CapabilityHost}, Windows{}, now) if err != nil { t.Fatal(err) } if health.State != datasource.HealthUnknown || health.ReasonCode != ReasonStale { t.Fatalf("stale health = %#v", health) } cancelled, cancel := context.WithCancel(context.Background()) cancel() if _, err := Health(cancelled, reader, []agentstore.Capability{agentstore.CapabilityHost}, Windows{}, now); !errors.Is(err, context.Canceled) { t.Fatalf("cancellation error = %v", err) } }