github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zvalid/bind_test.go (about) 1 package zvalid 2 3 import ( 4 "testing" 5 6 "github.com/sohaha/zlsgo" 7 ) 8 9 func TestVar(t *testing.T) { 10 tt := zlsgo.NewTest(t) 11 12 var str string 13 err := Var(&str, Text("is var").RemoveSpace()) 14 tt.EqualNil(err) 15 tt.Equal("isvar", str) 16 17 var i int 18 err = Var(&i, Text("is var").RemoveSpace()) 19 tt.Equal(true, err != nil) 20 tt.Equal(0, i) 21 err = Var(&i, Text("99").RemoveSpace()) 22 tt.EqualNil(err) 23 tt.Equal(99, i) 24 25 var iu uint 26 err = Var(&iu, Text("99").RemoveSpace()) 27 tt.EqualNil(err) 28 tt.Equal(uint(99), iu) 29 30 var f32 float32 31 val := Text("99.0") 32 err = Var(&f32, val) 33 tt.EqualNil(err) 34 tt.Equal(float32(99), f32) 35 36 var sts []string 37 err = Var(&sts, Text("1,2,3,go").Separator(",")) 38 tt.EqualNil(err) 39 tt.Equal([]string{"1", "2", "3", "go"}, sts) 40 41 var data struct { 42 Name string 43 } 44 45 err = Batch( 46 BatchVar(&data.Name, Text("yes name")), 47 ) 48 tt.EqualNil(err) 49 tt.Equal("yes name", data.Name) 50 51 } 52 53 func TestVarDefault(t *testing.T) { 54 tt := zlsgo.NewTest(t) 55 56 var email string 57 err := Var(&email, Text("email").IsMail()) 58 t.Log(email, err) 59 tt.EqualExit(email, "") 60 tt.EqualTrue(err != nil) 61 62 err = Var(&email, Text("email").IsMail().Default(666)) 63 t.Log(email, err) 64 tt.EqualExit(email, "") 65 tt.EqualTrue(err != nil) 66 67 err = Var(&email, Text("email").Silent().IsMail().Default("qq@qq.com")) 68 t.Log(email, err) 69 tt.EqualExit("qq@qq.com", email) 70 tt.NoError(err) 71 72 err = Var(&email, Text("email").IsMail().Default("qq@qq.com")) 73 t.Log(email, err) 74 tt.EqualExit(email, "qq@qq.com") 75 tt.NoError(err) 76 77 var nu int 78 err = Var(&nu, Text("Number").IsNumber().Default(123)) 79 t.Log(nu, err) 80 tt.NoError(err) 81 tt.EqualExit(nu, 123) 82 83 var b bool 84 err = Var(&b, Text("true").IsBool().Default(false)) 85 t.Log(b, err) 86 tt.EqualTrue(err == nil) 87 tt.EqualExit(b, true) 88 89 var i uint 90 err = Var(&i, Text("true").IsNumber().Default(uint(123))) 91 t.Log(b, err) 92 tt.NoError(err) 93 tt.EqualExit(uint(123), i) 94 95 var f float32 96 err = Var(&f, Text("true").IsNumber().Default(float32(123))) 97 t.Log(b, err) 98 tt.NoError(err) 99 tt.EqualExit(float32(123), f) 100 }