error.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Copyright 2011 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. // Error returns a matcher that matches non-nil values implementing the
  17. // built-in error interface for whom the return value of Error() matches the
  18. // supplied matcher.
  19. //
  20. // For example:
  21. //
  22. // err := errors.New("taco burrito")
  23. //
  24. // Error(Equals("taco burrito")) // matches err
  25. // Error(HasSubstr("taco")) // matches err
  26. // Error(HasSubstr("enchilada")) // doesn't match err
  27. //
  28. func Error(m Matcher) Matcher {
  29. return &errorMatcher{m}
  30. }
  31. type errorMatcher struct {
  32. wrappedMatcher Matcher
  33. }
  34. func (m *errorMatcher) Description() string {
  35. return "error " + m.wrappedMatcher.Description()
  36. }
  37. func (m *errorMatcher) Matches(c interface{}) error {
  38. // Make sure that c is an error.
  39. e, ok := c.(error)
  40. if !ok {
  41. return NewFatalError("which is not an error")
  42. }
  43. // Pass on the error text to the wrapped matcher.
  44. return m.wrappedMatcher.Matches(e.Error())
  45. }