github.com/MontFerret/ferret@v0.18.0/pkg/compiler/compiler_ternary_test.go (about) 1 package compiler_test 2 3 import ( 4 "context" 5 "fmt" 6 "testing" 7 8 . "github.com/smartystreets/goconvey/convey" 9 10 "github.com/MontFerret/ferret/pkg/compiler" 11 ) 12 13 func TestTernaryOperator(t *testing.T) { 14 Convey("Should compile ternary operator", t, func() { 15 c := compiler.New() 16 p, err := c.Compile(` 17 FOR i IN [1, 2, 3, 4, 5, 6] 18 RETURN i < 3 ? i * 3 : i * 2 19 `) 20 21 So(err, ShouldBeNil) 22 23 out, err := p.Run(context.Background()) 24 25 So(err, ShouldBeNil) 26 27 So(string(out), ShouldEqual, `[3,6,6,8,10,12]`) 28 }) 29 30 Convey("Should compile ternary operator with shortcut", t, func() { 31 c := compiler.New() 32 p, err := c.Compile(` 33 FOR i IN [1, 2, 3, 4, 5, 6] 34 RETURN i < 3 ? : i * 2 35 `) 36 37 So(err, ShouldBeNil) 38 39 out, err := p.Run(context.Background()) 40 41 So(err, ShouldBeNil) 42 43 So(string(out), ShouldEqual, `[true,true,6,8,10,12]`) 44 }) 45 46 Convey("Should compile ternary operator with shortcut with nones", t, func() { 47 c := compiler.New() 48 p, err := c.Compile(` 49 FOR i IN [NONE, 2, 3, 4, 5, 6] 50 RETURN i ? : i 51 `) 52 53 So(err, ShouldBeNil) 54 55 out, err := p.Run(context.Background()) 56 57 So(err, ShouldBeNil) 58 59 So(string(out), ShouldEqual, `[null,2,3,4,5,6]`) 60 }) 61 62 Convey("Should compile ternary operator with default values", t, func() { 63 vals := []string{ 64 "0", 65 "0.0", 66 "''", 67 "NONE", 68 "FALSE", 69 } 70 71 c := compiler.New() 72 73 for _, val := range vals { 74 p, err := c.Compile(fmt.Sprintf(` 75 FOR i IN [%s, 1, 2, 3] 76 RETURN i ? i * 2 : 'no value' 77 `, val)) 78 79 So(err, ShouldBeNil) 80 81 out, err := p.Run(context.Background()) 82 83 So(err, ShouldBeNil) 84 85 So(string(out), ShouldEqual, `["no value",2,4,6]`) 86 } 87 }) 88 89 Convey("Multi expression", t, func() { 90 out := compiler.New().MustCompile(` 91 RETURN 0 && true ? "1" : "some" 92 `).MustRun(context.Background()) 93 94 So(string(out), ShouldEqual, `"some"`) 95 96 out = compiler.New().MustCompile(` 97 RETURN length([]) > 0 && true ? "1" : "some" 98 `).MustRun(context.Background()) 99 100 So(string(out), ShouldEqual, `"some"`) 101 }) 102 } 103 104 func BenchmarkTernaryOperator(b *testing.B) { 105 p := compiler.New().MustCompile(` 106 LET a = "a" 107 LET b = "b" 108 LET c = FALSE 109 RETURN c ? a : b; 110 111 `) 112 113 for n := 0; n < b.N; n++ { 114 p.Run(context.Background()) 115 } 116 } 117 118 func BenchmarkTernaryOperatorDef(b *testing.B) { 119 p := compiler.New().MustCompile(` 120 LET a = "a" 121 LET b = "b" 122 LET c = FALSE 123 RETURN c ? : a; 124 125 `) 126 127 for n := 0; n < b.N; n++ { 128 p.Run(context.Background()) 129 } 130 }