//go:build linux package main import ( "os" "path/filepath" "testing" ) type supply map[string]string func buildTree(t *testing.T, supplies map[string]supply) string { t.Helper() root := t.TempDir() for name, fields := range supplies { dir := filepath.Join(root, name) if err := os.MkdirAll(dir, 0o755); err != nil { t.Fatal(err) } for key, value := range fields { if err := os.WriteFile(filepath.Join(dir, key), []byte(value+"\n"), 0o644); err != nil { t.Fatal(err) } } } return root } func TestSysfsOnBatteryTable(t *testing.T) { cases := []struct { name string supplies map[string]supply want bool }{ {"desktop without battery", map[string]supply{"AC": {"type": "Mains", "online": "1"}}, false}, {"empty tree", map[string]supply{}, false}, {"laptop discharging", map[string]supply{"BAT0": {"type": "Battery", "status": "Discharging"}, "AC": {"type": "Mains", "online": "0"}}, true}, {"laptop charging", map[string]supply{"BAT0": {"type": "Battery", "status": "Charging"}, "AC": {"type": "Mains", "online": "1"}}, false}, {"laptop full on mains", map[string]supply{"BAT0": {"type": "Battery", "status": "Full"}, "AC": {"type": "Mains", "online": "1"}}, false}, {"discharging but usb-c online", map[string]supply{"BAT0": {"type": "Battery", "status": "Discharging"}, "ucsi": {"type": "USB", "online": "1"}}, false}, {"discharging usb-c offline", map[string]supply{"BAT0": {"type": "Battery", "status": "Discharging"}, "ucsi": {"type": "USB_C", "online": "0"}}, true}, {"adp supply online", map[string]supply{"BAT1": {"type": "Battery", "status": "Discharging"}, "ADP1": {"type": "ADP", "online": "1"}}, false}, {"peripheral battery ignored", map[string]supply{"hid": {"type": "Battery", "status": "Discharging", "scope": "Device"}, "AC": {"type": "Mains", "online": "1"}}, false}, {"peripheral only", map[string]supply{"hid": {"type": "Battery", "status": "Discharging", "scope": "Device"}}, false}, {"unknown status", map[string]supply{"BAT0": {"type": "Battery", "status": "Unknown"}}, false}, } for _, item := range cases { got, err := sysfsOnBattery(buildTree(t, item.supplies)) if err != nil || got != item.want { t.Errorf("%s: got %v err %v", item.name, got, err) } } } func TestSysfsMissingRootIsAnError(t *testing.T) { if _, err := sysfsOnBattery(filepath.Join(t.TempDir(), "nope")); err == nil { t.Fatal("expected an error") } }