github.com/prebid/prebid-server/v2@v2.18.0/util/reflectutil/slice_test.go (about) 1 package reflectutil 2 3 import ( 4 "testing" 5 6 "github.com/modern-go/reflect2" 7 "github.com/stretchr/testify/assert" 8 ) 9 10 func TestUnsafeSliceCloneSimple(t *testing.T) { 11 testCases := []struct { 12 name string 13 given []int 14 }{ 15 { 16 name: "empty", 17 given: []int{}, 18 }, 19 { 20 name: "one", 21 given: []int{1}, 22 }, 23 { 24 name: "many", 25 given: []int{1, 2}, 26 }, 27 } 28 29 for _, test := range testCases { 30 t.Run(test.name, func(t *testing.T) { 31 original := test.given 32 clonePtr := UnsafeSliceClone(reflect2.PtrOf(test.given), reflect2.TypeOf([]int{}).(*reflect2.UnsafeSliceType)) 33 clone := *(*[]int)(clonePtr) 34 35 assert.NotSame(t, original, clone, "reference") 36 assert.Equal(t, original, clone, "equality") 37 assert.Equal(t, len(original), len(clone), "len") 38 assert.Equal(t, cap(original), cap(clone), "cap") 39 }) 40 } 41 } 42 43 func TestUnsafeSliceCloneComplex(t *testing.T) { 44 type foo struct { 45 value string 46 } 47 48 testCases := []struct { 49 name string 50 given []foo 51 }{ 52 { 53 name: "empty", 54 given: []foo{}, 55 }, 56 { 57 name: "one", 58 given: []foo{{value: "a"}}, 59 }, 60 { 61 name: "many", 62 given: []foo{{value: "a"}, {value: "b"}}, 63 }, 64 } 65 66 for _, test := range testCases { 67 t.Run(test.name, func(t *testing.T) { 68 original := test.given 69 clonePtr := UnsafeSliceClone(reflect2.PtrOf(test.given), reflect2.TypeOf([]foo{}).(*reflect2.UnsafeSliceType)) 70 clone := *(*[]foo)(clonePtr) 71 72 assert.NotSame(t, original, clone, "reference") 73 assert.Equal(t, original, clone, "equality") 74 assert.Equal(t, len(original), len(clone), "len") 75 assert.Equal(t, cap(original), cap(clone), "cap") 76 }) 77 } 78 }