package metrics import "testing" func TestFlatten(t *testing.T) { s := Sample{T: 1000, CPU: 10, Cores: []float64{5, 15}, Mem: Mem{Total: 200, Used: 50}, Temps: []Temp{{Chip: "nvme", Label: "Composite", C: 40, Crit: 85}, {Chip: "nvme", Label: "Composite", C: 45}}, Fans: []Fan{{Chip: "nct6775", Label: "fan2", RPM: 1100}}, FS: []FS{{Mount: "/", Size: 100, Used: 25}}, fsT: 900} got := map[string]any{} for _, x := range flatten(s, "") { if _, dup := got[x.ID]; dup { t.Errorf("duplicate id %s", x.ID) } got[x.ID] = x.Value } for id, want := range map[string]any{"cpu.usage": 10.0, "cpu.core.1.usage": 15.0, "mem.used_pct": 25.0, "temp.nvme.composite": 40.0, "temp.nvme.composite_2": 45.0, "fan.nct6775.fan2": 1100.0, "fs.root.used_pct": 25.0} { if got[id] != want { t.Errorf("%s = %v, want %v", id, got[id], want) } } one := flatten(s, "temp.nvme.composite_2") if len(one) != 1 || one[0].Value != 45.0 { t.Errorf("only: got %+v", one) } for _, x := range flatten(s, "fs.root.used") { if x.T != 900 { t.Errorf("fs sensor should carry the fs read time, got %d", x.T) } } } func TestSensorHistory(t *testing.T) { c := NewCollector() c.ring = []Sample{{T: 1, CPU: 10}, {T: 2, CPU: 20, Net: []Net{{Iface: "eth0", Up: true, RxBps: 5}}}} h, ok := c.SensorHistory("cpu.usage") if !ok || len(h.V) != 2 || h.V[1] != 20 || h.Unit != "%" { t.Fatalf("cpu: %+v %v", h, ok) } if h, ok := c.SensorHistory("net.eth0.rx"); !ok || len(h.V) != 1 || h.T[0] != 2 { t.Fatalf("net: a sensor that appeared later has a shorter history, got %+v %v", h, ok) } if _, ok := c.SensorHistory("net.eth0.up"); ok { t.Error("a state has no history") } if _, ok := c.SensorHistory("nope"); ok { t.Error("unknown id") } }