github.com/MontFerret/ferret@v0.18.0/pkg/runtime/collections/slice_test.go (about) 1 package collections_test 2 3 import ( 4 "context" 5 "testing" 6 7 . "github.com/smartystreets/goconvey/convey" 8 9 "github.com/MontFerret/ferret/pkg/runtime/collections" 10 "github.com/MontFerret/ferret/pkg/runtime/core" 11 "github.com/MontFerret/ferret/pkg/runtime/values" 12 ) 13 14 func sliceIterator(value []core.Value) collections.Iterator { 15 iter, _ := collections.NewDefaultSliceIterator(value) 16 17 return iter 18 } 19 20 func TestSliceIterator(t *testing.T) { 21 Convey("Should iterate over a slice", t, func() { 22 arr := []core.Value{ 23 values.NewInt(1), 24 values.NewInt(2), 25 values.NewInt(3), 26 values.NewInt(4), 27 values.NewInt(5), 28 } 29 30 iter := sliceIterator(arr) 31 32 res := make([]core.Value, 0, len(arr)) 33 ctx := context.Background() 34 scope, _ := core.NewRootScope() 35 36 pos := 0 37 38 for { 39 nextScope, err := iter.Next(ctx, scope) 40 41 if err != nil { 42 if core.IsNoMoreData(err) { 43 break 44 } 45 46 So(err, ShouldBeNil) 47 } 48 49 key := nextScope.MustGetVariable(collections.DefaultKeyVar) 50 item := nextScope.MustGetVariable(collections.DefaultValueVar) 51 52 So(key.Unwrap(), ShouldEqual, pos) 53 54 res = append(res, item) 55 56 pos++ 57 } 58 59 So(res, ShouldHaveLength, len(arr)) 60 }) 61 62 Convey("Should iterate over a slice in the same order", t, func() { 63 arr := []core.Value{ 64 values.NewInt(1), 65 values.NewInt(2), 66 values.NewInt(3), 67 values.NewInt(4), 68 values.NewInt(5), 69 } 70 71 iter := sliceIterator(arr) 72 ctx := context.Background() 73 scope, _ := core.NewRootScope() 74 75 res, err := collections.ToSlice(ctx, scope, iter) 76 77 So(err, ShouldBeNil) 78 79 for idx := range arr { 80 expected := arr[idx] 81 nextScope := res[idx] 82 actual := nextScope.MustGetVariable(collections.DefaultValueVar) 83 84 So(actual, ShouldEqual, expected) 85 } 86 }) 87 88 Convey("Should return an error when exhausted", t, func() { 89 arr := []core.Value{ 90 values.NewInt(1), 91 values.NewInt(2), 92 values.NewInt(3), 93 values.NewInt(4), 94 values.NewInt(5), 95 } 96 97 iter := sliceIterator(arr) 98 ctx := context.Background() 99 scope, _ := core.NewRootScope() 100 101 _, err := collections.ToSlice(ctx, scope, iter) 102 103 So(err, ShouldBeNil) 104 105 item, err := iter.Next(ctx, scope) 106 107 So(item, ShouldBeNil) 108 So(err, ShouldEqual, core.ErrNoMoreData) 109 }) 110 111 Convey("Should NOT iterate over an empty slice", t, func() { 112 arr := []core.Value{} 113 114 iter := sliceIterator(arr) 115 ctx := context.Background() 116 scope, _ := core.NewRootScope() 117 118 item, err := iter.Next(ctx, scope) 119 120 So(item, ShouldBeNil) 121 So(err, ShouldEqual, core.ErrNoMoreData) 122 }) 123 }