github.com/gogf/gf@v1.16.9/util/gvalid/gvalid_z_unit_customerror_test.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 package gvalid_test 8 9 import ( 10 "context" 11 "strings" 12 "testing" 13 14 "github.com/gogf/gf/test/gtest" 15 "github.com/gogf/gf/util/gvalid" 16 ) 17 18 func Test_Map(t *testing.T) { 19 gtest.C(t, func(t *gtest.T) { 20 var ( 21 rule = "ipv4" 22 val = "0.0.0" 23 err = gvalid.CheckValue(context.TODO(), val, rule, nil) 24 msg = map[string]string{ 25 "ipv4": "The value must be a valid IPv4 address", 26 } 27 ) 28 t.Assert(err.Map(), msg) 29 }) 30 } 31 32 func Test_FirstString(t *testing.T) { 33 gtest.C(t, func(t *gtest.T) { 34 var ( 35 rule = "ipv4" 36 val = "0.0.0" 37 err = gvalid.CheckValue(context.TODO(), val, rule, nil) 38 n = err.FirstString() 39 ) 40 t.Assert(n, "The value must be a valid IPv4 address") 41 }) 42 } 43 44 func Test_CustomError1(t *testing.T) { 45 rule := "integer|length:6,16" 46 msgs := map[string]string{ 47 "integer": "请输入一个整数", 48 "length": "参数长度不对啊老铁", 49 } 50 e := gvalid.CheckValue(context.TODO(), "6.66", rule, msgs) 51 if e == nil || len(e.Map()) != 2 { 52 t.Error("规则校验失败") 53 } else { 54 if v, ok := e.Map()["integer"]; ok { 55 if strings.Compare(v, msgs["integer"]) != 0 { 56 t.Error("错误信息不匹配") 57 } 58 } 59 if v, ok := e.Map()["length"]; ok { 60 if strings.Compare(v, msgs["length"]) != 0 { 61 t.Error("错误信息不匹配") 62 } 63 } 64 } 65 } 66 67 func Test_CustomError2(t *testing.T) { 68 rule := "integer|length:6,16" 69 msgs := "请输入一个整数|参数长度不对啊老铁" 70 e := gvalid.CheckValue(context.TODO(), "6.66", rule, msgs) 71 if e == nil || len(e.Map()) != 2 { 72 t.Error("规则校验失败") 73 } else { 74 if v, ok := e.Map()["integer"]; ok { 75 if strings.Compare(v, "请输入一个整数") != 0 { 76 t.Error("错误信息不匹配") 77 } 78 } 79 if v, ok := e.Map()["length"]; ok { 80 if strings.Compare(v, "参数长度不对啊老铁") != 0 { 81 t.Error("错误信息不匹配") 82 } 83 } 84 } 85 }