github.com/dolthub/go-mysql-server@v0.18.0/sql/expression/function/json/json_length_test.go (about) 1 // Copyright 2023 Dolthub, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package json 16 17 import ( 18 "fmt" 19 "strings" 20 "testing" 21 22 "github.com/stretchr/testify/require" 23 "gopkg.in/src-d/go-errors.v1" 24 25 "github.com/dolthub/go-mysql-server/sql" 26 ) 27 28 func TestJsonLength(t *testing.T) { 29 _, err := NewJSONValid() 30 require.True(t, errors.Is(err, sql.ErrInvalidArgumentNumber)) 31 32 f1 := buildGetFieldExpressions(t, NewJsonLength, 1) 33 f2 := buildGetFieldExpressions(t, NewJsonLength, 2) 34 35 testCases := []struct { 36 f sql.Expression 37 row sql.Row 38 exp interface{} 39 err bool 40 }{ 41 { 42 f: f1, 43 row: sql.Row{`null`}, 44 exp: nil, 45 }, 46 { 47 f: f1, 48 row: sql.Row{`1`}, 49 exp: 1, 50 }, 51 { 52 f: f1, 53 row: sql.Row{`[1]`}, 54 exp: 1, 55 }, 56 { 57 f: f1, 58 row: sql.Row{`"fjsadflkd"`}, 59 exp: 1, 60 }, 61 { 62 f: f1, 63 row: sql.Row{`[1, false]`}, 64 exp: 2, 65 }, 66 { 67 f: f1, 68 row: sql.Row{`[1, {"a": 1}]`}, 69 exp: 2, 70 }, 71 { 72 f: f1, 73 row: sql.Row{`{"a": 1}`}, 74 exp: 1, 75 }, 76 77 { 78 f: f2, 79 row: sql.Row{`{"a": [1, false]}`, nil}, 80 exp: nil, 81 }, 82 { 83 f: f2, 84 row: sql.Row{`{"a": [1, false]}`, 123}, 85 err: true, 86 }, 87 { 88 f: f2, 89 row: sql.Row{`{"a": [1, false]}`, "$.a"}, 90 exp: 2, 91 }, 92 { 93 f: f2, 94 row: sql.Row{`{"a": [1, {"a": 1}]}`, "$.a"}, 95 exp: 2, 96 }, 97 { 98 f: f2, 99 row: sql.Row{`{"a": 1, "b": [2, 3], "c": {"d": "foo"}}`, "$.b"}, 100 exp: 2, 101 }, 102 { 103 f: f2, 104 row: sql.Row{`{"a": 1, "b": [2, 3], "c": {"d": "foo"}}`, "$.b[0]"}, 105 exp: 1, 106 }, 107 { 108 f: f2, 109 row: sql.Row{`{"a": 1, "b": [2, 3], "c": {"d": "foo"}}`, "$.c.d"}, 110 exp: 1, 111 }, 112 { 113 f: f2, 114 row: sql.Row{`{"a": 1, "b": [2, 3], "c": {"d": "foo"}}`, "$.d"}, 115 exp: nil, 116 }, 117 } 118 119 for _, tt := range testCases { 120 var args []string 121 for _, a := range tt.row { 122 args = append(args, fmt.Sprintf("%v", a)) 123 } 124 t.Run(strings.Join(args, ", "), func(t *testing.T) { 125 require := require.New(t) 126 // any error case will result in output of 'false' value 127 result, err := tt.f.Eval(sql.NewEmptyContext(), tt.row) 128 if tt.err { 129 require.Error(err) 130 } else { 131 require.NoError(err) 132 } 133 require.Equal(tt.exp, result) 134 }) 135 } 136 }