github.com/spotmaxtech/k8s-apimachinery-v0260@v0.0.1/pkg/runtime/allocator_test.go (about) 1 /* 2 Copyright 2022 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package runtime 18 19 import ( 20 "math/rand" 21 "testing" 22 ) 23 24 func TestAllocatorRandomInputs(t *testing.T) { 25 maxBytes := 5 * 1000000 // 5 MB 26 iterations := rand.Intn(10000) + 10 27 target := &Allocator{} 28 29 for i := 0; i < iterations; i++ { 30 bytesToAllocate := rand.Intn(maxBytes) 31 buff := target.Allocate(uint64(bytesToAllocate)) 32 if cap(buff) < bytesToAllocate { 33 t.Fatalf("expected the buffer to allocate: %v bytes whereas it allocated: %v bytes", bytesToAllocate, cap(buff)) 34 } 35 if len(buff) != bytesToAllocate { 36 t.Fatalf("unexpected length of the buffer, expected: %v, got: %v", bytesToAllocate, len(buff)) 37 } 38 } 39 } 40 41 func TestAllocatorNeverShrinks(t *testing.T) { 42 target := &Allocator{} 43 initialSize := 1000000 // 1MB 44 initialBuff := target.Allocate(uint64(initialSize)) 45 if cap(initialBuff) < initialSize { 46 t.Fatalf("unexpected size of the buffer, expected at least 1MB, got: %v", cap(initialBuff)) 47 } 48 49 for i := initialSize; i > 0; i = i / 10 { 50 newBuff := target.Allocate(uint64(i)) 51 if cap(newBuff) < initialSize { 52 t.Fatalf("allocator is now allowed to shrink memory") 53 } 54 if len(newBuff) != i { 55 t.Fatalf("unexpected length of the buffer, expected: %v, got: %v", i, len(newBuff)) 56 } 57 } 58 } 59 60 func TestAllocatorZero(t *testing.T) { 61 target := &Allocator{} 62 initialSize := 1000000 // 1MB 63 buff := target.Allocate(uint64(initialSize)) 64 if cap(buff) < initialSize { 65 t.Fatalf("unexpected size of the buffer, expected at least 1MB, got: %v", cap(buff)) 66 } 67 if len(buff) != initialSize { 68 t.Fatalf("unexpected length of the buffer, expected: %v, got: %v", initialSize, len(buff)) 69 } 70 71 buff = target.Allocate(0) 72 if cap(buff) < initialSize { 73 t.Fatalf("unexpected size of the buffer, expected at least 1MB, got: %v", cap(buff)) 74 } 75 if len(buff) != 0 { 76 t.Fatalf("unexpected length of the buffer, expected: 0, got: %v", len(buff)) 77 } 78 }