has_substr.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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 NewMatcher(
  26. func(c interface{}) error { return hasSubstr(s, c) },
  27. fmt.Sprintf("has substring \"%s\"", s))
  28. }
  29. func hasSubstr(needle string, c interface{}) error {
  30. v := reflect.ValueOf(c)
  31. if v.Kind() != reflect.String {
  32. return NewFatalError("which is not a string")
  33. }
  34. // Perform the substring search.
  35. haystack := v.String()
  36. if strings.Contains(haystack, needle) {
  37. return nil
  38. }
  39. return errors.New("")
  40. }