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.

haslength.py 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. from hamcrest.core.base_matcher import BaseMatcher
  2. from hamcrest.core.helpers.hasmethod import hasmethod
  3. from hamcrest.core.helpers.wrap_matcher import wrap_matcher
  4. __author__ = "Jon Reid"
  5. __copyright__ = "Copyright 2011 hamcrest.org"
  6. __license__ = "BSD, see License.txt"
  7. class HasLength(BaseMatcher):
  8. def __init__(self, len_matcher):
  9. self.len_matcher = len_matcher
  10. def _matches(self, item):
  11. if not hasmethod(item, '__len__'):
  12. return False
  13. return self.len_matcher.matches(len(item))
  14. def describe_mismatch(self, item, mismatch_description):
  15. super(HasLength, self).describe_mismatch(item, mismatch_description)
  16. if hasmethod(item, '__len__'):
  17. mismatch_description.append_text(' with length of ') \
  18. .append_description_of(len(item))
  19. def describe_to(self, description):
  20. description.append_text('an object with length of ') \
  21. .append_description_of(self.len_matcher)
  22. def has_length(match):
  23. """Matches if ``len(item)`` satisfies a given matcher.
  24. :param match: The matcher to satisfy, or an expected value for
  25. :py:func:`~hamcrest.core.core.isequal.equal_to` matching.
  26. This matcher invokes the :py:func:`len` function on the evaluated object to
  27. get its length, passing the result to a given matcher for evaluation.
  28. If the ``match`` argument is not a matcher, it is implicitly wrapped in an
  29. :py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for
  30. :equality.
  31. Examples::
  32. has_length(greater_than(6))
  33. has_length(5)
  34. """
  35. return HasLength(wrap_matcher(match))