isdict_containing.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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 IsDictContaining(BaseMatcher):
  8. def __init__(self, key_matcher, value_matcher):
  9. self.key_matcher = key_matcher
  10. self.value_matcher = value_matcher
  11. def _matches(self, dictionary):
  12. if hasmethod(dictionary, 'items'):
  13. for key, value in dictionary.items():
  14. if self.key_matcher.matches(key) and self.value_matcher.matches(value):
  15. return True
  16. return False
  17. def describe_to(self, description):
  18. description.append_text('a dictionary containing [') \
  19. .append_description_of(self.key_matcher) \
  20. .append_text(': ') \
  21. .append_description_of(self.value_matcher) \
  22. .append_text(']')
  23. def has_entry(key_match, value_match):
  24. """Matches if dictionary contains key-value entry satisfying a given pair
  25. of matchers.
  26. :param key_match: The matcher to satisfy for the key, or an expected value
  27. for :py:func:`~hamcrest.core.core.isequal.equal_to` matching.
  28. :param value_match: The matcher to satisfy for the value, or an expected
  29. value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching.
  30. This matcher iterates the evaluated dictionary, searching for any key-value
  31. entry that satisfies ``key_match`` and ``value_match``. If a matching entry
  32. is found, ``has_entry`` is satisfied.
  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. Examples::
  37. has_entry(equal_to('foo'), equal_to(1))
  38. has_entry('foo', 1)
  39. """
  40. return IsDictContaining(wrap_matcher(key_match), wrap_matcher(value_match))