package proc import ( "os" "path/filepath" "testing" ) func TestReadCgroup(t *testing.T) { tests := []struct { name string cgroupFile string wantPath string wantErr bool }{ { name: "cgroup v2 unified", cgroupFile: `0::/kubepods/pod-abc/container-123 `, wantPath: "/kubepods/pod-abc/container-123", wantErr: false, }, { name: "cgroup v2 with trailing newline", cgroupFile: `0::/docker/abc123def456 `, wantPath: "/docker/abc123def456", wantErr: false, }, { name: "cgroup v1 multiple controllers", cgroupFile: `12:blkio:/user.slice 11:memory:/docker/abc123 10:cpu,cpuacct:/docker/abc123 9:pids:/docker/abc123 `, wantPath: "/docker/abc123", wantErr: false, }, { name: "cgroup v2 preferred over v1", cgroupFile: `11:memory:/docker/old-path 0::/kubepods/new-path `, wantPath: "/kubepods/new-path", wantErr: false, }, { name: "empty file", cgroupFile: "", wantPath: "", wantErr: false, }, { name: "root cgroup", cgroupFile: `0::/ `, wantPath: "/", wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // Create a temp directory structure mimicking /proc tmpDir := t.TempDir() procDir := filepath.Join(tmpDir, "proc") pidDir := filepath.Join(procDir, "1234") if err := os.MkdirAll(pidDir, 0755); err != nil { t.Fatalf("Failed to create pid dir: %v", err) } if err := os.WriteFile(filepath.Join(pidDir, "cgroup"), []byte(tt.cgroupFile), 0644); err != nil { t.Fatalf("Failed to write cgroup file: %v", err) } got, err := ReadCgroup(procDir, 1234) if (err != nil) != tt.wantErr { t.Errorf("ReadCgroup() error = %v, wantErr %v", err, tt.wantErr) return } if !tt.wantErr && got.Path != tt.wantPath { t.Errorf("ReadCgroup() path = %q, want %q", got.Path, tt.wantPath) } }) } } func TestReadCgroup_FileNotFound(t *testing.T) { tmpDir := t.TempDir() _, err := ReadCgroup(tmpDir, 1234) if err == nil { t.Error("ReadCgroup() expected error for missing file, got nil") } }