github.com/choria-io/go-choria@v0.28.1-0.20240416190746-b3bf9c7d5a45/validator/regex/regex_test.go (about) 1 // Copyright (c) 2020-2021, R.I. Pienaar and the Choria Project contributors 2 // 3 // SPDX-License-Identifier: Apache-2.0 4 5 package regex 6 7 import ( 8 "reflect" 9 "testing" 10 11 . "github.com/onsi/ginkgo/v2" 12 . "github.com/onsi/gomega" 13 ) 14 15 func TestFileContent(t *testing.T) { 16 RegisterFailHandler(Fail) 17 RunSpecs(t, "Validator/Regex") 18 } 19 20 var _ = Describe("ValidateString", func() { 21 It("Should match strings correctly", func() { 22 ok, err := ValidateString("hello world", "world$") 23 Expect(err).ToNot(HaveOccurred()) 24 Expect(ok).To(BeTrue()) 25 26 ok, err = ValidateString("hello", "world$") 27 Expect(err).To(MatchError("input does not match 'world$'")) 28 Expect(ok).To(BeFalse()) 29 30 ok, err = ValidateString("hello", "invalid(") 31 Expect(err).To(MatchError("invalid regex 'invalid('")) 32 Expect(ok).To(BeFalse()) 33 }) 34 }) 35 36 var _ = Describe("ValidateStructField", func() { 37 type t struct { 38 String string `validate:"regex=world$"` 39 Invalid string `validate:"regex"` 40 } 41 42 It("Should fail for invalid tags", func() { 43 st := t{"1", "foo"} 44 45 val := reflect.ValueOf(st) 46 valueField := val.FieldByName("Invalid") 47 typeField, _ := val.Type().FieldByName("Invalid") 48 49 ok, err := ValidateStructField(valueField, typeField.Tag.Get("validate")) 50 Expect(err).To(MatchError("invalid tag 'regex', must be in the form regex=^hello.+world$")) 51 Expect(ok).To(BeFalse()) 52 }) 53 54 It("Should match the regex correctly", func() { 55 st := t{"fail", "foo"} 56 57 val := reflect.ValueOf(st) 58 valueField := val.FieldByName("String") 59 typeField, _ := val.Type().FieldByName("String") 60 61 ok, err := ValidateStructField(valueField, typeField.Tag.Get("validate")) 62 Expect(err).To(MatchError("input does not match 'world$'")) 63 Expect(ok).To(BeFalse()) 64 65 st.String = "hello world" 66 val = reflect.ValueOf(st) 67 valueField = val.FieldByName("String") 68 69 ok, err = ValidateStructField(valueField, typeField.Tag.Get("validate")) 70 Expect(err).ToNot(HaveOccurred()) 71 Expect(ok).To(BeTrue()) 72 }) 73 })