contains.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. "fmt"
  18. "reflect"
  19. )
  20. // Return a matcher that matches arrays slices with at least one element that
  21. // matches the supplied argument. If the argument x is not itself a Matcher,
  22. // this is equivalent to Contains(Equals(x)).
  23. func Contains(x interface{}) Matcher {
  24. var result containsMatcher
  25. var ok bool
  26. if result.elementMatcher, ok = x.(Matcher); !ok {
  27. result.elementMatcher = DeepEquals(x)
  28. }
  29. return &result
  30. }
  31. type containsMatcher struct {
  32. elementMatcher Matcher
  33. }
  34. func (m *containsMatcher) Description() string {
  35. return fmt.Sprintf("contains: %s", m.elementMatcher.Description())
  36. }
  37. func (m *containsMatcher) Matches(candidate interface{}) error {
  38. // The candidate must be a slice or an array.
  39. v := reflect.ValueOf(candidate)
  40. if v.Kind() != reflect.Slice && v.Kind() != reflect.Array {
  41. return NewFatalError("which is not a slice or array")
  42. }
  43. // Check each element.
  44. for i := 0; i < v.Len(); i++ {
  45. elem := v.Index(i)
  46. if matchErr := m.elementMatcher.Matches(elem.Interface()); matchErr == nil {
  47. return nil
  48. }
  49. }
  50. return fmt.Errorf("")
  51. }