You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

issequence_onlycontaining.py 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. from hamcrest.core.base_matcher import BaseMatcher
  2. from hamcrest.core.core.anyof import any_of
  3. from hamcrest.core.helpers.hasmethod import hasmethod
  4. from hamcrest.core.helpers.wrap_matcher import wrap_matcher
  5. __author__ = "Jon Reid"
  6. __copyright__ = "Copyright 2011 hamcrest.org"
  7. __license__ = "BSD, see License.txt"
  8. class IsSequenceOnlyContaining(BaseMatcher):
  9. def __init__(self, matcher):
  10. self.matcher = matcher
  11. def _matches(self, sequence):
  12. try:
  13. sequence = list(sequence)
  14. if len(sequence) == 0:
  15. return False
  16. for item in sequence:
  17. if not self.matcher.matches(item):
  18. return False
  19. return True
  20. except TypeError:
  21. return False
  22. def describe_to(self, description):
  23. description.append_text('a sequence containing items matching ') \
  24. .append_description_of(self.matcher)
  25. def only_contains(*items):
  26. """Matches if each element of sequence satisfies any of the given matchers.
  27. :param match1,...: A comma-separated list of matchers.
  28. This matcher iterates the evaluated sequence, confirming whether each
  29. element satisfies any of the given matchers.
  30. Example::
  31. only_contains(less_than(4))
  32. will match ``[3,1,2]``.
  33. Any argument that is not a matcher is implicitly wrapped in an
  34. :py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for
  35. equality.
  36. """
  37. matchers = []
  38. for item in items:
  39. matchers.append(wrap_matcher(item))
  40. return IsSequenceOnlyContaining(any_of(*matchers))