github.com/MontFerret/ferret@v0.18.0/pkg/runtime/expressions/return_test.go (about) 1 package expressions_test 2 3 import ( 4 "context" 5 "testing" 6 7 "github.com/MontFerret/ferret/pkg/runtime/expressions/literals" 8 "github.com/MontFerret/ferret/pkg/runtime/values" 9 10 . "github.com/smartystreets/goconvey/convey" 11 12 "github.com/MontFerret/ferret/pkg/runtime/core" 13 "github.com/MontFerret/ferret/pkg/runtime/expressions" 14 ) 15 16 func TestReturnExpression(t *testing.T) { 17 Convey("Should create a return expression", t, func() { 18 sourceMap := core.NewSourceMap("test", 1, 10) 19 predicate, err := expressions.NewVariableExpression(sourceMap, "testExp") 20 So(err, ShouldBeNil) 21 22 exp, err := expressions.NewReturnExpression(sourceMap, predicate) 23 So(err, ShouldBeNil) 24 So(exp, ShouldHaveSameTypeAs, &expressions.ReturnExpression{}) 25 }) 26 27 Convey("Should not create a return expression with an empty predicate", t, func() { 28 sourceMap := core.NewSourceMap("test", 1, 1) 29 exp, err := expressions.NewReturnExpression(sourceMap, nil) 30 31 So(err, ShouldBeError) 32 So(exp, ShouldBeNil) 33 }) 34 35 Convey("Should exec a return expression with an existing predicate", t, func() { 36 sourceMap := core.NewSourceMap("test", 1, 1) 37 predicate, err := expressions.NewVariableExpression(sourceMap, "test") 38 So(err, ShouldBeNil) 39 40 exp, err := expressions.NewReturnExpression(sourceMap, predicate) 41 So(err, ShouldBeNil) 42 43 rootScope, fn := core.NewRootScope() 44 scope := rootScope.Fork() 45 So(scope.SetVariable("test", values.NewString("value")), ShouldBeNil) 46 So(fn(), ShouldBeNil) 47 48 value, err := exp.Exec(context.Background(), scope) 49 So(err, ShouldBeNil) 50 So(value, ShouldNotBeNil) 51 So(value, ShouldEqual, "value") 52 }) 53 54 Convey("Should not exec a return expression with a missing predicate", t, func() { 55 sourceMap := core.NewSourceMap("test", 1, 1) 56 predicate, err := expressions.NewVariableExpression(sourceMap, "notExist") 57 So(err, ShouldBeNil) 58 59 exp, err := expressions.NewReturnExpression(sourceMap, predicate) 60 So(err, ShouldBeNil) 61 62 rootScope, fn := core.NewRootScope() 63 scope := rootScope.Fork() 64 scope.SetVariable("test", values.NewString("value")) 65 fn() 66 67 value, err := exp.Exec(context.Background(), scope) 68 So(err, ShouldNotBeNil) 69 So(err.(*core.SourceErrorDetail).BaseError, ShouldHaveSameTypeAs, core.ErrNotFound) 70 So(value, ShouldHaveSameTypeAs, values.None) 71 }) 72 73 Convey("Should stop an execution when context is cancelled", t, func() { 74 sourceMap := core.NewSourceMap("test", 1, 1) 75 predicate := literals.NewIntLiteral(1) 76 77 exp, err := expressions.NewReturnExpression(sourceMap, predicate) 78 So(err, ShouldBeNil) 79 80 rootScope, _ := core.NewRootScope() 81 scope := rootScope.Fork() 82 83 ctx, cancel := context.WithCancel(context.Background()) 84 cancel() 85 86 _, err = exp.Exec(ctx, scope) 87 So(err, ShouldEqual, core.ErrTerminated) 88 }) 89 }