github.com/MontFerret/ferret@v0.18.0/pkg/runtime/collections/while_pre_test.go (about) 1 package collections_test 2 3 import ( 4 "context" 5 "testing" 6 7 "github.com/MontFerret/ferret/pkg/runtime/collections" 8 "github.com/MontFerret/ferret/pkg/runtime/core" 9 10 . "github.com/smartystreets/goconvey/convey" 11 ) 12 13 func TestDoWhileIterator(t *testing.T) { 14 Convey("Should iterate while a predicate returns true", t, func() { 15 predicateCounter := 0 16 iterationCounter := 0 17 expectedCount := 10 18 19 iterator, err := collections.NewDefaultWhileIterator(collections.WhileModePre, func(ctx context.Context, scope *core.Scope) (bool, error) { 20 if predicateCounter == (expectedCount - 1) { 21 return false, nil 22 } 23 24 predicateCounter++ 25 26 return true, nil 27 }) 28 29 So(err, ShouldBeNil) 30 31 scope, fn := core.NewRootScope() 32 defer fn() 33 err = collections.ForEach(context.Background(), scope, iterator, func(ctx context.Context, scope *core.Scope) bool { 34 iterationCounter++ 35 36 return true 37 }) 38 39 So(err, ShouldBeNil) 40 So(iterationCounter, ShouldEqual, expectedCount) 41 }) 42 43 Convey("Should iterate once if a predicate returns false", t, func() { 44 iterationCounter := 0 45 expectedCount := 1 46 47 iterator, err := collections.NewDefaultWhileIterator(collections.WhileModePre, func(ctx context.Context, scope *core.Scope) (bool, error) { 48 return false, nil 49 }) 50 51 So(err, ShouldBeNil) 52 53 scope, fn := core.NewRootScope() 54 defer fn() 55 err = collections.ForEach(context.Background(), scope, iterator, func(ctx context.Context, scope *core.Scope) bool { 56 iterationCounter++ 57 58 return true 59 }) 60 61 So(err, ShouldBeNil) 62 So(iterationCounter, ShouldEqual, expectedCount) 63 }) 64 }