github.com/opencontainers/runc@v1.2.0-rc.1.0.20240520010911-492dc558cdd6/libcontainer/cgroups/fscommon/utils_test.go (about) 1 package fscommon 2 3 import ( 4 "math" 5 "os" 6 "path/filepath" 7 "strconv" 8 "testing" 9 10 "github.com/opencontainers/runc/libcontainer/cgroups" 11 ) 12 13 const ( 14 cgroupFile = "cgroup.file" 15 floatValue = 2048.0 16 floatString = "2048" 17 ) 18 19 func init() { 20 cgroups.TestMode = true 21 } 22 23 func TestGetCgroupParamsInt(t *testing.T) { 24 // Setup tempdir. 25 tempDir := t.TempDir() 26 tempFile := filepath.Join(tempDir, cgroupFile) 27 28 // Success. 29 if err := os.WriteFile(tempFile, []byte(floatString), 0o755); err != nil { 30 t.Fatal(err) 31 } 32 value, err := GetCgroupParamUint(tempDir, cgroupFile) 33 if err != nil { 34 t.Fatal(err) 35 } else if value != floatValue { 36 t.Fatalf("Expected %d to equal %f", value, floatValue) 37 } 38 39 // Success with new line. 40 err = os.WriteFile(tempFile, []byte(floatString+"\n"), 0o755) 41 if err != nil { 42 t.Fatal(err) 43 } 44 value, err = GetCgroupParamUint(tempDir, cgroupFile) 45 if err != nil { 46 t.Fatal(err) 47 } else if value != floatValue { 48 t.Fatalf("Expected %d to equal %f", value, floatValue) 49 } 50 51 // Success with negative values 52 err = os.WriteFile(tempFile, []byte("-12345"), 0o755) 53 if err != nil { 54 t.Fatal(err) 55 } 56 value, err = GetCgroupParamUint(tempDir, cgroupFile) 57 if err != nil { 58 t.Fatal(err) 59 } else if value != 0 { 60 t.Fatalf("Expected %d to equal %d", value, 0) 61 } 62 63 // Success with negative values lesser than min int64 64 s := strconv.FormatFloat(math.MinInt64, 'f', -1, 64) 65 err = os.WriteFile(tempFile, []byte(s), 0o755) 66 if err != nil { 67 t.Fatal(err) 68 } 69 value, err = GetCgroupParamUint(tempDir, cgroupFile) 70 if err != nil { 71 t.Fatal(err) 72 } else if value != 0 { 73 t.Fatalf("Expected %d to equal %d", value, 0) 74 } 75 76 // Not a float. 77 err = os.WriteFile(tempFile, []byte("not-a-float"), 0o755) 78 if err != nil { 79 t.Fatal(err) 80 } 81 _, err = GetCgroupParamUint(tempDir, cgroupFile) 82 if err == nil { 83 t.Fatal("Expecting error, got none") 84 } 85 86 // Unknown file. 87 err = os.Remove(tempFile) 88 if err != nil { 89 t.Fatal(err) 90 } 91 _, err = GetCgroupParamUint(tempDir, cgroupFile) 92 if err == nil { 93 t.Fatal("Expecting error, got none") 94 } 95 }