pointer.go 1.3 KB

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