github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/objects/keys_test.go (about) 1 package objects_test 2 3 import ( 4 "context" 5 "testing" 6 7 "github.com/MontFerret/ferret/pkg/runtime/values/types" 8 9 "github.com/MontFerret/ferret/pkg/runtime/values" 10 "github.com/MontFerret/ferret/pkg/stdlib/objects" 11 12 . "github.com/smartystreets/goconvey/convey" 13 ) 14 15 func TestKeys(t *testing.T) { 16 Convey("Keys(obj, false) should return 'a', 'c', 'b' in any order", t, func() { 17 obj := values.NewObjectWith( 18 values.NewObjectProperty("a", values.NewInt(0)), 19 values.NewObjectProperty("b", values.NewInt(1)), 20 values.NewObjectProperty("c", values.NewInt(2)), 21 ) 22 23 keys, err := objects.Keys(context.Background(), obj) 24 keysArray := keys.(*values.Array) 25 26 So(err, ShouldEqual, nil) 27 So(keysArray.Type().Equals(types.Array), ShouldBeTrue) 28 So(keysArray.Length(), ShouldEqual, 3) 29 30 for _, k := range []string{"b", "a", "c"} { 31 iof := keysArray.IndexOf(values.NewString(k)) 32 So(iof, ShouldNotEqual, -1) 33 } 34 }) 35 36 Convey("Keys(obj, false) should return ['a', 'b', 'c']", t, func() { 37 obj := values.NewObjectWith( 38 values.NewObjectProperty("b", values.NewInt(0)), 39 values.NewObjectProperty("a", values.NewInt(1)), 40 values.NewObjectProperty("c", values.NewInt(3)), 41 ) 42 43 keys, err := objects.Keys(context.Background(), obj, values.NewBoolean(true)) 44 keysArray := keys.(*values.Array) 45 46 So(err, ShouldEqual, nil) 47 48 for idx, key := range []string{"a", "b", "c"} { 49 So(keysArray.Get(values.NewInt(idx)), ShouldEqual, values.NewString(key)) 50 } 51 }) 52 53 Convey("When there are no keys", t, func() { 54 obj := values.NewObject() 55 56 keys, err := objects.Keys(context.Background(), obj, values.NewBoolean(true)) 57 keysArray := keys.(*values.Array) 58 59 So(err, ShouldEqual, nil) 60 So(keysArray.Length(), ShouldEqual, values.NewInt(0)) 61 So(int(keysArray.Length()), ShouldEqual, 0) 62 63 keys, err = objects.Keys(context.Background(), obj, values.NewBoolean(false)) 64 keysArray = keys.(*values.Array) 65 66 So(err, ShouldEqual, nil) 67 So(keysArray.Length(), ShouldEqual, values.NewInt(0)) 68 So(int(keysArray.Length()), ShouldEqual, 0) 69 }) 70 71 Convey("When not enough arguments", t, func() { 72 _, err := objects.Keys(context.Background()) 73 74 So(err, ShouldBeError) 75 }) 76 77 Convey("When first argument isn't object", t, func() { 78 notObj := values.NewInt(0) 79 80 _, err := objects.Keys(context.Background(), notObj) 81 82 So(err, ShouldBeError) 83 }) 84 85 Convey("When second argument isn't boolean", t, func() { 86 obj := values.NewObject() 87 88 _, err := objects.Keys(context.Background(), obj, obj) 89 90 So(err, ShouldBeError) 91 }) 92 93 }