github.com/choria-io/go-choria@v0.28.1-0.20240416190746-b3bf9c7d5a45/validator/duration/duration_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 duration 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/Duration") 18 } 19 20 var _ = Describe("ValidateString", func() { 21 It("Should match durations correctly", func() { 22 ok, err := ValidateString("1s") 23 Expect(err).ToNot(HaveOccurred()) 24 Expect(ok).To(BeTrue()) 25 26 ok, err = ValidateString("1h") 27 Expect(err).ToNot(HaveOccurred()) 28 Expect(ok).To(BeTrue()) 29 30 ok, err = ValidateString("1w") 31 Expect(err.Error()).To(MatchRegexp("time: unknown unit")) 32 Expect(ok).To(BeFalse()) 33 }) 34 }) 35 36 var _ = Describe("ValidateStructField", func() { 37 type t struct { 38 Interval string `validate:"duration"` 39 } 40 41 It("Should validate the struct correctly", func() { 42 st := t{"1h"} 43 44 val := reflect.ValueOf(st) 45 valueField := val.FieldByName("Interval") 46 typeField, _ := val.Type().FieldByName("Interval") 47 48 ok, err := ValidateStructField(valueField, typeField.Tag.Get("validate")) 49 Expect(err).ToNot(HaveOccurred()) 50 Expect(ok).To(BeTrue()) 51 52 st.Interval = "foo" 53 valueField = reflect.ValueOf(st).FieldByName("Interval") 54 ok, err = ValidateStructField(valueField, typeField.Tag.Get("validate")) 55 Expect(err.Error()).To(MatchRegexp("time: invalid duration")) 56 Expect(ok).To(BeFalse()) 57 }) 58 })