github.com/dylandreimerink/gobpfld@v0.6.1-0.20220205171531-e79c330ad608/map_stack_test.go (about) 1 //go:build bpftests 2 // +build bpftests 3 4 package gobpfld 5 6 import ( 7 "math/rand" 8 "testing" 9 10 "github.com/dylandreimerink/gobpfld/bpftypes" 11 "github.com/dylandreimerink/gobpfld/kernelsupport" 12 ) 13 14 func TestStackMap(t *testing.T) { 15 if !kernelsupport.CurrentFeatures.Map.Has(kernelsupport.KFeatMapStack) { 16 t.Skip("skipping test, current kernel version has no support for stack maps") 17 } 18 19 const maxEntries = 20 20 stack := StackMap{ 21 AbstractMap: AbstractMap{ 22 Name: MustNewObjName("test"), 23 Definition: BPFMapDef{ 24 Type: bpftypes.BPF_MAP_TYPE_STACK, 25 KeySize: 0, 26 ValueSize: sizeOfUint64, 27 MaxEntries: maxEntries, 28 }, 29 }, 30 } 31 32 err := stack.Load() 33 if err != nil { 34 t.Fatal(err) 35 } 36 defer stack.Close() 37 38 validationMap := make([]int64, maxEntries) 39 for i := 0; i < maxEntries; i++ { 40 val := rand.Int63() 41 err = stack.Push(&val) 42 validationMap[i] = int64(val) 43 if err != nil { 44 t.Fatal(err) 45 } 46 } 47 48 var v int64 49 err = stack.Peek(&v) 50 if err != nil { 51 t.Fatal(err) 52 } 53 54 if v != validationMap[len(validationMap)-1] { 55 t.Fatalf("invalid peek, got: %d, expected: %d", v, validationMap[len(validationMap)-1]) 56 } 57 58 for i := maxEntries - 1; i >= 0; i-- { 59 var v int64 60 err = stack.Pop(&v) 61 if err != nil { 62 t.Fatal(err) 63 } 64 65 if v != validationMap[i] { 66 t.Fatalf("invalid pop, got: %d, expected: %d", v, validationMap[i]) 67 } 68 } 69 } 70 71 func TestStackMapIterator(t *testing.T) { 72 if !kernelsupport.CurrentFeatures.Map.Has(kernelsupport.KFeatMapStack) { 73 t.Skip("skipping test, current kernel version has no support for stack maps") 74 } 75 76 const maxEntries = 20 77 stack := StackMap{ 78 AbstractMap: AbstractMap{ 79 Name: MustNewObjName("test"), 80 Definition: BPFMapDef{ 81 Type: bpftypes.BPF_MAP_TYPE_STACK, 82 KeySize: 0, 83 ValueSize: sizeOfUint64, 84 MaxEntries: maxEntries, 85 }, 86 }, 87 } 88 89 err := stack.Load() 90 if err != nil { 91 t.Fatal(err) 92 } 93 defer stack.Close() 94 95 validationMap := make([]int64, maxEntries) 96 for i := 0; i < maxEntries; i++ { 97 val := rand.Int63() 98 err = stack.Push(&val) 99 validationMap[i] = int64(val) 100 if err != nil { 101 t.Fatal(err) 102 } 103 } 104 105 i := maxEntries - 1 106 var v int64 107 err = MapIterForEach(stack.Iterator(), nil, &v, func(_, _ interface{}) error { 108 if v != validationMap[i] { 109 t.Fatalf("invalid pop, got: %d, expected: %d", v, validationMap[i]) 110 } 111 i-- 112 113 return nil 114 }) 115 if err != nil { 116 t.Fatal(err) 117 } 118 }