pointee.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright 2012 Aaron Jacobs. All Rights Reserved.
  2. // Author: aaronjjacobs@gmail.com (Aaron Jacobs)
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. package oglematchers
  16. import (
  17. "errors"
  18. "fmt"
  19. "reflect"
  20. )
  21. // Return a matcher that matches non-nil pointers whose pointee matches the
  22. // wrapped matcher.
  23. func Pointee(m Matcher) Matcher {
  24. return &pointeeMatcher{m}
  25. }
  26. type pointeeMatcher struct {
  27. wrapped Matcher
  28. }
  29. func (m *pointeeMatcher) Matches(c interface{}) (err error) {
  30. // Make sure the candidate is of the appropriate type.
  31. cv := reflect.ValueOf(c)
  32. if !cv.IsValid() || cv.Kind() != reflect.Ptr {
  33. return NewFatalError("which is not a pointer")
  34. }
  35. // Make sure the candidate is non-nil.
  36. if cv.IsNil() {
  37. return NewFatalError("")
  38. }
  39. // Defer to the wrapped matcher. Fix up empty errors so that failure messages
  40. // are more helpful than just printing a pointer for "Actual".
  41. pointee := cv.Elem().Interface()
  42. err = m.wrapped.Matches(pointee)
  43. if err != nil && err.Error() == "" {
  44. s := fmt.Sprintf("whose pointee is %v", pointee)
  45. if _, ok := err.(*FatalError); ok {
  46. err = NewFatalError(s)
  47. } else {
  48. err = errors.New(s)
  49. }
  50. }
  51. return err
  52. }
  53. func (m *pointeeMatcher) Description() string {
  54. return fmt.Sprintf("pointee(%s)", m.wrapped.Description())
  55. }