github.com/bytedance/go-tagexpr/v2@v2.9.8/spec_func_test.go (about) 1 // Copyright 2019 Bytedance Inc. All Rights Reserved. 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 tagexpr_test 16 17 import ( 18 "regexp" 19 "testing" 20 21 "github.com/bytedance/go-tagexpr/v2" 22 "github.com/stretchr/testify/assert" 23 ) 24 25 func TestFunc(t *testing.T) { 26 var emailRegexp = regexp.MustCompile( 27 "^([A-Za-z0-9_\\-\\.\u4e00-\u9fa5])+\\@([A-Za-z0-9_\\-\\.])+\\.([A-Za-z]{2,8})$", 28 ) 29 tagexpr.RegFunc("email", func(args ...interface{}) interface{} { 30 if len(args) == 0 { 31 return false 32 } 33 s, ok := args[0].(string) 34 if !ok { 35 return false 36 } 37 t.Log(s) 38 return emailRegexp.MatchString(s) 39 }) 40 41 var vm = tagexpr.New("te") 42 43 type T struct { 44 Email string `te:"email($)"` 45 } 46 var cases = []struct { 47 email string 48 expect bool 49 }{ 50 {"", false}, 51 {"henrylee2cn@gmail.com", true}, 52 } 53 54 obj := new(T) 55 for _, c := range cases { 56 obj.Email = c.email 57 te := vm.MustRun(obj) 58 got := te.EvalBool("Email") 59 if got != c.expect { 60 t.Fatalf("email: %s, expect: %v, but got: %v", c.email, c.expect, got) 61 } 62 } 63 64 // test len 65 type R struct { 66 Str string `vd:"mblen($)<6"` 67 } 68 var lenCases = []struct { 69 str string 70 expect bool 71 }{ 72 {"123", true}, 73 {"一二三四五六七", false}, 74 {"一二三四五", true}, 75 } 76 77 lenObj := new(R) 78 vm = tagexpr.New("vd") 79 for _, lenCase := range lenCases { 80 lenObj.Str = lenCase.str 81 te := vm.MustRun(lenObj) 82 got := te.EvalBool("Str") 83 if got != lenCase.expect { 84 t.Fatalf("string: %v, expect: %v, but got: %v", lenCase.str, lenCase.expect, got) 85 } 86 } 87 } 88 89 func TestRangeIn(t *testing.T) { 90 var vm = tagexpr.New("te") 91 type S struct { 92 F []string `te:"range($, in(#v, '', 'ttp', 'euttp'))"` 93 } 94 a := []string{"ttp", "", "euttp"} 95 r := vm.MustRun(S{ 96 F: a, 97 // F: b, 98 }) 99 assert.Equal(t, []interface{}{true, true, true}, r.Eval("F")) 100 }