has_substr.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. import (
  17. "errors"
  18. "fmt"
  19. "reflect"
  20. "strings"
  21. )
  22. // HasSubstr returns a matcher that matches strings containing s as a
  23. // substring.
  24. func HasSubstr(s string) Matcher {
  25. return &hasSubstrMatcher{s}
  26. }
  27. type hasSubstrMatcher struct {
  28. needle string
  29. }
  30. func (m *hasSubstrMatcher) Description() string {
  31. return fmt.Sprintf("has substring \"%s\"", m.needle)
  32. }
  33. func (m *hasSubstrMatcher) Matches(c interface{}) error {
  34. v := reflect.ValueOf(c)
  35. if v.Kind() != reflect.String {
  36. return NewFatalError("which is not a string")
  37. }
  38. // Perform the substring search.
  39. haystack := v.String()
  40. if strings.Contains(haystack, m.needle) {
  41. return nil
  42. }
  43. return errors.New("")
  44. }