gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/runsc/sandbox/memory_test.go (about) 1 // Copyright 2021 The gVisor Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package sandbox 16 17 import ( 18 "bytes" 19 "fmt" 20 "math" 21 "strings" 22 "testing" 23 ) 24 25 func TestTotalSystemMemory(t *testing.T) { 26 for _, tc := range []struct { 27 name string 28 content string 29 want uint64 30 err string 31 }{ 32 { 33 name: "simple", 34 content: "MemTotal: 123\n", 35 want: 123, 36 }, 37 { 38 name: "kb", 39 content: "MemTotal: 123 kB\n", 40 want: 123 * 1024, 41 }, 42 { 43 name: "multi-line", 44 content: "Something: 123\nMemTotal: 456\nAnotherThing: 789\n", 45 want: 456, 46 }, 47 { 48 name: "not-found", 49 content: "Something: 123 kB\nAnotherThing: 789 kB\n", 50 err: "not found", 51 }, 52 { 53 name: "no-number", 54 content: "MemTotal: \n", 55 err: "malformed", 56 }, 57 { 58 name: "only-unit", 59 content: "MemTotal: kB\n", 60 err: "invalid syntax", 61 }, 62 { 63 name: "negative", 64 content: "MemTotal: -1\n", 65 err: "invalid syntax", 66 }, 67 { 68 name: "overflow", 69 content: fmt.Sprintf("MemTotal: %d kB\n", uint64(math.MaxUint64)), 70 err: "too large", 71 }, 72 { 73 name: "unkown-unit", 74 content: "MemTotal: 123 mB\n", 75 err: "unknown unit", 76 }, 77 } { 78 t.Run(tc.name, func(t *testing.T) { 79 mem, err := parseTotalSystemMemory(bytes.NewReader([]byte(tc.content))) 80 if len(tc.err) > 0 { 81 if err == nil || !strings.Contains(err.Error(), tc.err) { 82 t.Errorf("parseTotalSystemMemory(%q) invalid error: %v, want: %v", tc.content, err, tc.err) 83 } 84 } else { 85 if tc.want != mem { 86 t.Errorf("parseTotalSystemMemory(%q) got: %v, want: %v", tc.content, mem, tc.want) 87 } 88 } 89 }) 90 } 91 }