github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/validator/validator_z_strfmt_test.go (about) 1 package validator_test 2 3 import ( 4 "fmt" 5 "testing" 6 7 . "github.com/onsi/gomega" 8 9 . "github.com/machinefi/w3bstream/pkg/depends/kit/validator" 10 . "github.com/machinefi/w3bstream/pkg/depends/kit/validator/strfmt" 11 ) 12 13 func ExampleNewRegexpStrfmtValidator() { 14 fmt.Println(AlphaValidator.Validate("a")) 15 fmt.Println(AlphaValidator.Validate("1")) 16 fmt.Println(EmailValidator.Validate("a.b.c+123@xxx.com")) 17 // Output: 18 // <nil> 19 // alpha ^[a-zA-Z]+$ not match 1 20 // <nil> 21 } 22 23 func TestStrfmtValidator_Validate(t *testing.T) { 24 cases := []struct { 25 value interface{} 26 rule string 27 vldt *StrFmt 28 }{ 29 {"abc", "@alpha", AlphaValidator}, 30 {"a.b.c+123@xxx.com", "@email", EmailValidator}, 31 {"0x3110752149AF23Ee65968C2019b7c86D12B32229", "@ethAddress", EthAddressValidator}, 32 } 33 34 for _, c := range cases { 35 name := fmt.Sprintf( 36 "%s|%s|%s", c.vldt.Names()[0], c.rule, c.value, 37 ) 38 t.Run(name, func(t *testing.T) { 39 fact := NewFactory() 40 fact.Register(c.vldt) 41 v, err := fact.Compile(bg, []byte(c.rule), rttString) 42 NewWithT(t).Expect(err).To(BeNil()) 43 err = v.Validate(c.value) 44 NewWithT(t).Expect(err).To(BeNil()) 45 }) 46 } 47 } 48 49 func TestStrfmtValidator_ValidateFailed(t *testing.T) { 50 cases := []struct { 51 value interface{} 52 rule string 53 vldt *StrFmt 54 }{ 55 // TODO should support multi validator like @alpha|@string[1,32] 56 {1, "@number", NumberValidator}, 57 {".", "@number", NumberValidator}, 58 {"x#abc.com", "@email", EmailValidator}, 59 {"123", "@alpha", AlphaValidator}, 60 {"0x3110752149AF23Ee", "@ethAddress", EthAddressValidator}, 61 } 62 63 for _, c := range cases { 64 name := fmt.Sprintf( 65 "%s|%s|%s", c.vldt.Names()[0], c.rule, c.value, 66 ) 67 t.Run(name, func(t *testing.T) { 68 err := c.vldt.Validate(c.value) 69 NewWithT(t).Expect(err).NotTo(BeNil()) 70 // t.Logf("\n%v", err) 71 }) 72 } 73 }