github.com/MontFerret/ferret@v0.18.0/pkg/runtime/collections/keyed_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 objectIterator(obj *values.Object) collections.Iterator { 15 iter, _ := collections.NewDefaultKeyedIterator(obj) 16 17 return iter 18 } 19 20 func TestObjectIterator(t *testing.T) { 21 Convey("Should iterate over a map", t, func() { 22 m := values.NewObjectWith( 23 values.NewObjectProperty("one", values.NewInt(1)), 24 values.NewObjectProperty("two", values.NewInt(2)), 25 values.NewObjectProperty("three", values.NewInt(3)), 26 values.NewObjectProperty("four", values.NewInt(4)), 27 values.NewObjectProperty("five", values.NewInt(5)), 28 ) 29 30 iter := objectIterator(m) 31 32 res := make([]core.Value, 0, m.Length()) 33 34 ctx := context.Background() 35 scope, _ := core.NewRootScope() 36 37 for { 38 nextScope, err := iter.Next(ctx, scope) 39 40 if err != nil { 41 if core.IsNoMoreData(err) { 42 break 43 } 44 45 So(err, ShouldBeNil) 46 } 47 48 key := nextScope.MustGetVariable(collections.DefaultKeyVar) 49 item := nextScope.MustGetVariable(collections.DefaultValueVar) 50 51 expected, exists := m.Get(values.NewString(key.String())) 52 53 So(bool(exists), ShouldBeTrue) 54 So(expected, ShouldEqual, item) 55 56 res = append(res, item) 57 } 58 59 So(res, ShouldHaveLength, m.Length()) 60 }) 61 62 Convey("Should return an error when exhausted", t, func() { 63 m := values.NewObjectWith( 64 values.NewObjectProperty("one", values.NewInt(1)), 65 values.NewObjectProperty("two", values.NewInt(2)), 66 values.NewObjectProperty("three", values.NewInt(3)), 67 values.NewObjectProperty("four", values.NewInt(4)), 68 values.NewObjectProperty("five", values.NewInt(5)), 69 ) 70 71 iter := objectIterator(m) 72 73 ctx := context.Background() 74 scope, _ := core.NewRootScope() 75 76 res, err := collections.ToSlice(ctx, scope, iter) 77 78 So(err, ShouldBeNil) 79 So(res, ShouldNotBeNil) 80 81 nextScope, err := iter.Next(ctx, scope) 82 83 So(nextScope, ShouldBeNil) 84 So(err, ShouldEqual, core.ErrNoMoreData) 85 }) 86 87 Convey("Should NOT iterate over a empty map", t, func() { 88 m := values.NewObject() 89 90 iter := objectIterator(m) 91 92 ctx := context.Background() 93 scope, _ := core.NewRootScope() 94 95 nextScope, err := iter.Next(ctx, scope) 96 97 So(nextScope, ShouldBeNil) 98 So(err, ShouldEqual, core.ErrNoMoreData) 99 }) 100 }