...
1
16
17 package runtime
18
19 import (
20 "math/rand"
21 "testing"
22 )
23
24 func TestAllocatorRandomInputs(t *testing.T) {
25 maxBytes := 5 * 1000000
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
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
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 }
79
View as plain text