github.com/choria-io/go-choria@v0.28.1-0.20240416190746-b3bf9c7d5a45/validator/ipaddress/ipaddress_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 ipaddress 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/IPAddress") 18 } 19 20 var _ = Describe("ValidateString", func() { 21 It("Should match ipv4 addresses correctly", func() { 22 ok, err := ValidateString("1.2.3.4") 23 Expect(err).ToNot(HaveOccurred()) 24 Expect(ok).To(BeTrue()) 25 26 ok, err = ValidateString("2a00:1450:4003:807::200e") 27 Expect(err).ToNot(HaveOccurred()) 28 Expect(ok).To(BeTrue()) 29 30 ok, err = ValidateString("foo") 31 Expect(err).To(MatchError("foo is not an IP address")) 32 Expect(ok).To(BeFalse()) 33 }) 34 }) 35 36 var _ = Describe("ValidateStructField", func() { 37 type t struct { 38 IP string `validate:"ipaddress"` 39 } 40 41 It("Should validate the struct correctly", func() { 42 st := t{"1.2.3.4"} 43 44 val := reflect.ValueOf(st) 45 valueField := val.FieldByName("IP") 46 typeField, _ := val.Type().FieldByName("IP") 47 48 ok, err := ValidateStructField(valueField, typeField.Tag.Get("validate")) 49 Expect(err).ToNot(HaveOccurred()) 50 Expect(ok).To(BeTrue()) 51 52 st.IP = "foo" 53 valueField = reflect.ValueOf(st).FieldByName("IP") 54 ok, err = ValidateStructField(valueField, typeField.Tag.Get("validate")) 55 Expect(err).To(MatchError("foo is not an IP address")) 56 Expect(ok).To(BeFalse()) 57 58 st.IP = "2a00:1450:4003:807::200e" 59 valueField = reflect.ValueOf(st).FieldByName("IP") 60 ok, err = ValidateStructField(valueField, typeField.Tag.Get("validate")) 61 Expect(err).ToNot(HaveOccurred()) 62 Expect(ok).To(BeTrue()) 63 }) 64 })