1
0
mirror of https://github.com/MontFerret/ferret.git synced 2024-12-16 11:37:36 +02:00
ferret/pkg/runtime/collections/slice_test.go

118 lines
2.3 KiB
Go
Raw Normal View History

package collections_test
import (
2018-10-28 07:45:26 +02:00
"context"
"github.com/MontFerret/ferret/pkg/runtime/collections"
"github.com/MontFerret/ferret/pkg/runtime/core"
"github.com/MontFerret/ferret/pkg/runtime/values"
. "github.com/smartystreets/goconvey/convey"
"testing"
)
func sliceIterator(value []core.Value) collections.Iterator {
2018-10-28 07:45:26 +02:00
iter, _ := collections.NewDefaultSliceIterator(value)
return iter
}
func TestSliceIterator(t *testing.T) {
Convey("Should iterate over a slice", t, func() {
arr := []core.Value{
values.NewInt(1),
values.NewInt(2),
values.NewInt(3),
values.NewInt(4),
values.NewInt(5),
}
iter := sliceIterator(arr)
res := make([]core.Value, 0, len(arr))
2018-10-28 07:45:26 +02:00
ctx := context.Background()
scope, _ := core.NewRootScope()
pos := 0
2018-10-28 07:45:26 +02:00
for {
nextScope, err := iter.Next(ctx, scope)
So(err, ShouldBeNil)
2018-10-28 07:45:26 +02:00
if nextScope == nil {
break
}
key := nextScope.MustGetVariable(collections.DefaultKeyVar)
item := nextScope.MustGetVariable(collections.DefaultValueVar)
So(key.Unwrap(), ShouldEqual, pos)
res = append(res, item)
pos += 1
}
So(res, ShouldHaveLength, len(arr))
})
Convey("Should iterate over a slice in the same order", t, func() {
arr := []core.Value{
values.NewInt(1),
values.NewInt(2),
values.NewInt(3),
values.NewInt(4),
values.NewInt(5),
}
iter := sliceIterator(arr)
2018-10-28 07:45:26 +02:00
ctx := context.Background()
scope, _ := core.NewRootScope()
2018-10-28 07:45:26 +02:00
res, err := collections.ToSlice(ctx, scope, iter)
2018-10-28 07:45:26 +02:00
So(err, ShouldBeNil)
for idx := range arr {
expected := arr[idx]
2018-10-28 07:45:26 +02:00
nextScope := res[idx]
actual := nextScope.MustGetVariable(collections.DefaultValueVar)
So(actual, ShouldEqual, expected)
}
})
Convey("Should return an error when exhausted", t, func() {
arr := []core.Value{
values.NewInt(1),
values.NewInt(2),
values.NewInt(3),
values.NewInt(4),
values.NewInt(5),
}
iter := sliceIterator(arr)
2018-10-28 07:45:26 +02:00
ctx := context.Background()
scope, _ := core.NewRootScope()
2018-10-28 07:45:26 +02:00
_, err := collections.ToSlice(ctx, scope, iter)
2018-10-28 07:45:26 +02:00
item, err := iter.Next(ctx, scope)
So(item, ShouldBeNil)
2018-10-28 07:45:26 +02:00
So(err, ShouldBeNil)
})
Convey("Should NOT iterate over an empty slice", t, func() {
arr := []core.Value{}
iter := sliceIterator(arr)
2018-10-28 07:45:26 +02:00
ctx := context.Background()
scope, _ := core.NewRootScope()
2018-10-28 07:45:26 +02:00
item, err := iter.Next(ctx, scope)
2018-10-28 07:45:26 +02:00
So(item, ShouldBeNil)
So(err, ShouldBeNil)
})
}