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.

isdict_containingkey.py 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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 IsDictContainingKey(BaseMatcher):
  8. def __init__(self, key_matcher):
  9. self.key_matcher = key_matcher
  10. def _matches(self, dictionary):
  11. if hasmethod(dictionary, 'keys'):
  12. for key in dictionary.keys():
  13. if self.key_matcher.matches(key):
  14. return True
  15. return False
  16. def describe_to(self, description):
  17. description.append_text('a dictionary containing key ') \
  18. .append_description_of(self.key_matcher)
  19. def has_key(key_match):
  20. """Matches if dictionary contains an entry whose key satisfies a given
  21. matcher.
  22. :param key_match: The matcher to satisfy for the key, or an expected value
  23. for :py:func:`~hamcrest.core.core.isequal.equal_to` matching.
  24. This matcher iterates the evaluated dictionary, searching for any key-value
  25. entry whose key satisfies the given matcher. If a matching entry is found,
  26. ``has_key`` is satisfied.
  27. Any argument that is not a matcher is implicitly wrapped in an
  28. :py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for
  29. equality.
  30. Examples::
  31. has_key(equal_to('foo'))
  32. has_key('foo')
  33. """
  34. return IsDictContainingKey(wrap_matcher(key_match))