stringcontainsinorder.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. __author__ = "Romilly Cocking"
  2. __copyright__ = "Copyright 2011 hamcrest.org"
  3. __license__ = "BSD, see License.txt"
  4. from hamcrest.core.base_matcher import BaseMatcher
  5. from hamcrest.core.helpers.hasmethod import hasmethod
  6. import six
  7. class StringContainsInOrder(BaseMatcher):
  8. def __init__(self, *substrings):
  9. for substring in substrings:
  10. if not isinstance(substring, six.string_types):
  11. raise TypeError(self.__class__.__name__
  12. + ' requires string arguments')
  13. self.substrings = substrings
  14. def _matches(self, item):
  15. if not hasmethod(item, 'find'):
  16. return False
  17. from_index = 0
  18. for substring in self.substrings:
  19. from_index = item.find(substring, from_index)
  20. if from_index == -1:
  21. return False
  22. return True
  23. def describe_to(self, description):
  24. description.append_list('a string containing ', ', ', ' in order',
  25. self.substrings)
  26. def string_contains_in_order(*substrings):
  27. """Matches if object is a string containing a given list of substrings in
  28. relative order.
  29. :param string1,...: A comma-separated list of strings.
  30. This matcher first checks whether the evaluated object is a string. If so,
  31. it checks whether it contains a given list of strings, in relative order to
  32. each other. The searches are performed starting from the beginning of the
  33. evaluated string.
  34. Example::
  35. string_contains_in_order("bc", "fg", "jkl")
  36. will match "abcdefghijklm".
  37. """
  38. return StringContainsInOrder(*substrings)