github.com/onsi/gomega@v1.32.0/gstruct/pointer.go (about) 1 // untested sections: 3 2 3 package gstruct 4 5 import ( 6 "fmt" 7 "reflect" 8 9 "github.com/onsi/gomega/format" 10 "github.com/onsi/gomega/types" 11 ) 12 13 //PointTo applies the given matcher to the value pointed to by actual. It fails if the pointer is 14 //nil. 15 // actual := 5 16 // Expect(&actual).To(PointTo(Equal(5))) 17 func PointTo(matcher types.GomegaMatcher) types.GomegaMatcher { 18 return &PointerMatcher{ 19 Matcher: matcher, 20 } 21 } 22 23 type PointerMatcher struct { 24 Matcher types.GomegaMatcher 25 26 // Failure message. 27 failure string 28 } 29 30 func (m *PointerMatcher) Match(actual interface{}) (bool, error) { 31 val := reflect.ValueOf(actual) 32 33 // return error if actual type is not a pointer 34 if val.Kind() != reflect.Ptr { 35 return false, fmt.Errorf("PointerMatcher expects a pointer but we have '%s'", val.Kind()) 36 } 37 38 if !val.IsValid() || val.IsNil() { 39 m.failure = format.Message(actual, "not to be <nil>") 40 return false, nil 41 } 42 43 // Forward the value. 44 elem := val.Elem().Interface() 45 match, err := m.Matcher.Match(elem) 46 if !match { 47 m.failure = m.Matcher.FailureMessage(elem) 48 } 49 return match, err 50 } 51 52 func (m *PointerMatcher) FailureMessage(_ interface{}) (message string) { 53 return m.failure 54 } 55 56 func (m *PointerMatcher) NegatedFailureMessage(actual interface{}) (message string) { 57 return m.Matcher.NegatedFailureMessage(actual) 58 }