pointer.go 1.3 KB

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