github.com/gogf/gf/v2@v2.7.4/util/gvalid/gvalid_z_unit_issue_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 "fmt" 12 "testing" 13 "time" 14 15 "github.com/gogf/gf/v2/errors/gerror" 16 "github.com/gogf/gf/v2/frame/g" 17 "github.com/gogf/gf/v2/net/ghttp" 18 "github.com/gogf/gf/v2/test/gtest" 19 "github.com/gogf/gf/v2/util/guid" 20 "github.com/gogf/gf/v2/util/gvalid" 21 ) 22 23 type Foo struct { 24 Bar *Bar `p:"bar" v:"required-without:Baz"` 25 Baz *Baz `p:"baz" v:"required-without:Bar"` 26 } 27 type Bar struct { 28 BarKey string `p:"bar_key" v:"required"` 29 } 30 type Baz struct { 31 BazKey string `p:"baz_key" v:"required"` 32 } 33 34 // https://github.com/gogf/gf/issues/2503 35 func Test_Issue2503(t *testing.T) { 36 foo := &Foo{ 37 Bar: &Bar{BarKey: "value"}, 38 } 39 err := gvalid.New().Data(foo).Run(context.Background()) 40 if err != nil { 41 t.Fatal(err) 42 } 43 } 44 45 type Issue3636SliceV struct{} 46 47 func init() { 48 rule := Issue3636SliceV{} 49 gvalid.RegisterRule(rule.Name(), rule.Run) 50 } 51 52 func (r Issue3636SliceV) Name() string { 53 return "slice-v" 54 } 55 56 func (r Issue3636SliceV) Message() string { 57 return "not a slice" 58 } 59 60 func (r Issue3636SliceV) Run(_ context.Context, in gvalid.RuleFuncInput) error { 61 for _, v := range in.Value.Slice() { 62 if v == "" { 63 return gerror.New("empty value") 64 } 65 } 66 if !in.Value.IsSlice() { 67 return gerror.New("not a slice") 68 } 69 return nil 70 } 71 72 type Issue3636HelloReq struct { 73 g.Meta `path:"/hello" method:"POST"` 74 75 Name string `json:"name" v:"required" dc:"Your name"` 76 S []string `json:"s" v:"slice-v" dc:"S"` 77 } 78 type Issue3636HelloRes struct { 79 Name string `json:"name" v:"required" dc:"Your name"` 80 S []string `json:"s" v:"slice-v" dc:"S"` 81 } 82 83 type Issue3636Hello struct{} 84 85 func (Issue3636Hello) Say(ctx context.Context, req *Issue3636HelloReq) (res *Issue3636HelloRes, err error) { 86 res = &Issue3636HelloRes{ 87 Name: req.Name, 88 S: req.S, 89 } 90 return 91 } 92 93 // https://github.com/gogf/gf/issues/3636 94 func Test_Issue3636(t *testing.T) { 95 s := g.Server(guid.S()) 96 s.Use(ghttp.MiddlewareHandlerResponse) 97 s.Group("/", func(group *ghttp.RouterGroup) { 98 group.Bind( 99 new(Issue3636Hello), 100 ) 101 }) 102 s.SetDumpRouterMap(false) 103 s.Start() 104 defer s.Shutdown() 105 106 time.Sleep(100 * time.Millisecond) 107 108 gtest.C(t, func(t *gtest.T) { 109 c := g.Client() 110 c.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", s.GetListenedPort())) 111 t.Assert( 112 c.PostContent(ctx, "/hello", `{"name": "t", "s" : []}`), 113 `{"code":0,"message":"","data":{"name":"t","s":[]}}`, 114 ) 115 }) 116 }