github.com/bytedance/go-tagexpr@v2.7.5-0.20210114074101-de5b8743ad85+incompatible/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"
    22  )
    23  
    24  func TestFunc(t *testing.T) {
    25  	var emailRegexp = regexp.MustCompile(
    26  		"^([A-Za-z0-9_\\-\\.\u4e00-\u9fa5])+\\@([A-Za-z0-9_\\-\\.])+\\.([A-Za-z]{2,8})$",
    27  	)
    28  	tagexpr.RegFunc("email", func(args ...interface{}) interface{} {
    29  		if len(args) == 0 {
    30  			return false
    31  		}
    32  		s, ok := args[0].(string)
    33  		if !ok {
    34  			return false
    35  		}
    36  		t.Log(s)
    37  		return emailRegexp.MatchString(s)
    38  	})
    39  
    40  	var vm = tagexpr.New("te")
    41  
    42  	type T struct {
    43  		Email string `te:"email($)"`
    44  	}
    45  	var cases = []struct {
    46  		email  string
    47  		expect bool
    48  	}{
    49  		{"", false},
    50  		{"henrylee2cn@gmail.com", true},
    51  	}
    52  
    53  	obj := new(T)
    54  	for _, c := range cases {
    55  		obj.Email = c.email
    56  		te := vm.MustRun(obj)
    57  		got := te.EvalBool("Email")
    58  		if got != c.expect {
    59  			t.Fatalf("email: %s, expect: %v, but got: %v", c.email, c.expect, got)
    60  		}
    61  	}
    62  
    63  	// test len
    64  	type R struct {
    65  		Str string `vd:"mblen($)<6"`
    66  	}
    67  	var lenCases = []struct {
    68  		str    string
    69  		expect bool
    70  	}{
    71  		{"123", true},
    72  		{"一二三四五六七", false},
    73  		{"一二三四五", true},
    74  	}
    75  
    76  	lenObj := new(R)
    77  	vm = tagexpr.New("vd")
    78  	for _, lenCase := range lenCases {
    79  		lenObj.Str = lenCase.str
    80  		te := vm.MustRun(lenObj)
    81  		got := te.EvalBool("Str")
    82  		if got != lenCase.expect {
    83  			t.Fatalf("string: %v, expect: %v, but got: %v", lenCase.str, lenCase.expect, got)
    84  		}
    85  	}
    86  
    87  }