package main import ( "math" "os" "testing" ) func approx(a, b float64) bool { return math.Abs(a-b) < 0.01 } func TestParseLoadAvg(t *testing.T) { got := parseLoadAvg([]byte("0.42 0.31 0.19 1/234 5678\n")) if !approx(got, 0.42) { t.Fatalf("load = %v, want 0.42", got) } if v := parseLoadAvg([]byte("")); v != 0 { t.Fatalf("empty load = %v, want 0", v) } } func TestParseCPUStat(t *testing.T) { total, idle, ok := parseCPUStat([]byte("cpu 100 0 50 800 50 0 0 0 0 0\ncpu0 1 2 3 4\n")) if !ok { t.Fatal("parseCPUStat not ok") } // total = 100+0+50+800+50 = 1000; idle = idle(800)+iowait(50) = 850. if total != 1000 || idle != 850 { t.Fatalf("total=%d idle=%d, want 1000/850", total, idle) } } func TestCPUBusyPct(t *testing.T) { // From (total 1000, idle 850) to (total 1100, idle 900): dTotal=100, dIdle=50 // → busy = 50/100 = 50%. if got := cpuBusyPct(1000, 850, 1100, 900); !approx(got, 50) { t.Fatalf("busy = %v, want 50", got) } // No forward progress → 0 (guards a counter reset / same sample). if got := cpuBusyPct(1000, 850, 1000, 850); got != 0 { t.Fatalf("no-delta busy = %v, want 0", got) } // idle jumping more than total is clamped, never negative. if got := cpuBusyPct(1000, 850, 1100, 1000); got != 0 { t.Fatalf("clamped busy = %v, want 0", got) } } func TestParseMemUsedPct(t *testing.T) { // total 1000, available 250 → used 75%. mem := []byte("MemTotal: 1000 kB\nMemFree: 100 kB\nMemAvailable: 250 kB\n") if got := parseMemUsedPct(mem); !approx(got, 75) { t.Fatalf("mem used = %v, want 75", got) } if got := parseMemUsedPct([]byte("garbage")); got != 0 { t.Fatalf("garbage mem = %v, want 0", got) } } func TestParseHandle(t *testing.T) { for _, tc := range []struct { in string want uint32 bad bool }{ {"0x81000100", 0x81000100, false}, {"81000100", 0x81000100, false}, {"0X01800100", 0x01800100, false}, {"nope", 0, true}, } { h, err := parseHandle(tc.in) if tc.bad { if err == nil { t.Errorf("parseHandle(%q) = %#x, want error", tc.in, uint32(h)) } continue } if err != nil || uint32(h) != tc.want { t.Errorf("parseHandle(%q) = %#x, %v; want %#x", tc.in, uint32(h), err, tc.want) } } } func TestHostOf(t *testing.T) { for _, tc := range []struct{ in, want string }{ {"diskless-server.bitasylum.org:9600", "diskless-server.bitasylum.org"}, {"host", "host"}, {"[2001:db8::1]:9600", "2001:db8::1"}, } { if got := hostOf(tc.in); got != tc.want { t.Errorf("hostOf(%q) = %q, want %q", tc.in, got, tc.want) } } } func TestReadKioskURL(t *testing.T) { dir := t.TempDir() f := dir + "/kiosk.env" if err := os.WriteFile(f, []byte("# comment\nKIOSK_URL=\"http://boot.fleet.lab/kiosk/\"\nOTHER=x\n"), 0o644); err != nil { t.Fatal(err) } if got := readKioskURL(f); got != "http://boot.fleet.lab/kiosk/" { t.Fatalf("kiosk url = %q", got) } if got := readKioskURL(dir + "/missing"); got != "" { t.Fatalf("missing kiosk env = %q, want empty", got) } }