github.com/wangyougui/gf/v2@v2.6.5/util/gvalid/gvalid_z_unit_feature_custom_error_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/wangyougui/gf.
     6  
     7  package gvalid_test
     8  
     9  import (
    10  	"context"
    11  	"strings"
    12  	"testing"
    13  
    14  	"github.com/wangyougui/gf/v2/frame/g"
    15  	"github.com/wangyougui/gf/v2/test/gtest"
    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  = g.Validator().Data(val).Rules(rule).Run(context.TODO())
    24  			msg  = map[string]string{
    25  				"ipv4": "The value `0.0.0` is not 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  = g.Validator().Data(val).Rules(rule).Run(context.TODO())
    38  		)
    39  		t.Assert(err.FirstError(), "The value `0.0.0` is not a valid IPv4 address")
    40  	})
    41  }
    42  
    43  func Test_CustomError1(t *testing.T) {
    44  	rule := "integer|length:6,16"
    45  	msgs := map[string]string{
    46  		"integer": "请输入一个整数",
    47  		"length":  "参数长度不对啊老铁",
    48  	}
    49  	e := g.Validator().Data("6.66").Rules(rule).Messages(msgs).Run(context.TODO())
    50  	if e == nil || len(e.Map()) != 2 {
    51  		t.Error("规则校验失败")
    52  	} else {
    53  		if v, ok := e.Map()["integer"]; ok {
    54  			if strings.Compare(v.Error(), msgs["integer"]) != 0 {
    55  				t.Error("错误信息不匹配")
    56  			}
    57  		}
    58  		if v, ok := e.Map()["length"]; ok {
    59  			if strings.Compare(v.Error(), msgs["length"]) != 0 {
    60  				t.Error("错误信息不匹配")
    61  			}
    62  		}
    63  	}
    64  }
    65  
    66  func Test_CustomError2(t *testing.T) {
    67  	rule := "integer|length:6,16"
    68  	msgs := "请输入一个整数|参数长度不对啊老铁"
    69  	e := g.Validator().Data("6.66").Rules(rule).Messages(msgs).Run(context.TODO())
    70  	if e == nil || len(e.Map()) != 2 {
    71  		t.Error("规则校验失败")
    72  	} else {
    73  		if v, ok := e.Map()["integer"]; ok {
    74  			if strings.Compare(v.Error(), "请输入一个整数") != 0 {
    75  				t.Error("错误信息不匹配")
    76  			}
    77  		}
    78  		if v, ok := e.Map()["length"]; ok {
    79  			if strings.Compare(v.Error(), "参数长度不对啊老铁") != 0 {
    80  				t.Error("错误信息不匹配")
    81  			}
    82  		}
    83  	}
    84  }