isdict_containingentries.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  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 IsDictContainingEntries(BaseMatcher):
  8. def __init__(self, value_matchers):
  9. self.value_matchers = sorted(value_matchers.items())
  10. def _not_a_dictionary(self, dictionary, mismatch_description):
  11. if mismatch_description:
  12. mismatch_description.append_description_of(dictionary) \
  13. .append_text(' is not a mapping object')
  14. return False
  15. def matches(self, dictionary, mismatch_description=None):
  16. for key, value_matcher in self.value_matchers:
  17. try:
  18. if not key in dictionary:
  19. if mismatch_description:
  20. mismatch_description.append_text('no ') \
  21. .append_description_of(key) \
  22. .append_text(' key in ') \
  23. .append_description_of(dictionary)
  24. return False
  25. except TypeError:
  26. return self._not_a_dictionary(dictionary, mismatch_description)
  27. try:
  28. actual_value = dictionary[key]
  29. except TypeError:
  30. return self._not_a_dictionary(dictionary, mismatch_description)
  31. if not value_matcher.matches(actual_value):
  32. if mismatch_description:
  33. mismatch_description.append_text('value for ') \
  34. .append_description_of(key) \
  35. .append_text(' ')
  36. value_matcher.describe_mismatch(actual_value, mismatch_description)
  37. return False
  38. return True
  39. def describe_mismatch(self, item, mismatch_description):
  40. self.matches(item, mismatch_description)
  41. def describe_keyvalue(self, index, value, description):
  42. """Describes key-value pair at given index."""
  43. description.append_description_of(index) \
  44. .append_text(': ') \
  45. .append_description_of(value)
  46. def describe_to(self, description):
  47. description.append_text('a dictionary containing {')
  48. first = True
  49. for key, value in self.value_matchers:
  50. if not first:
  51. description.append_text(', ')
  52. self.describe_keyvalue(key, value, description)
  53. first = False
  54. description.append_text('}')
  55. def has_entries(*keys_valuematchers, **kv_args):
  56. """Matches if dictionary contains entries satisfying a dictionary of keys
  57. and corresponding value matchers.
  58. :param matcher_dict: A dictionary mapping keys to associated value matchers,
  59. or to expected values for
  60. :py:func:`~hamcrest.core.core.isequal.equal_to` matching.
  61. Note that the keys must be actual keys, not matchers. Any value argument
  62. that is not a matcher is implicitly wrapped in an
  63. :py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for
  64. equality.
  65. Examples::
  66. has_entries({'foo':equal_to(1), 'bar':equal_to(2)})
  67. has_entries({'foo':1, 'bar':2})
  68. ``has_entries`` also accepts a list of keyword arguments:
  69. .. function:: has_entries(keyword1=value_matcher1[, keyword2=value_matcher2[, ...]])
  70. :param keyword1: A keyword to look up.
  71. :param valueMatcher1: The matcher to satisfy for the value, or an expected
  72. value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching.
  73. Examples::
  74. has_entries(foo=equal_to(1), bar=equal_to(2))
  75. has_entries(foo=1, bar=2)
  76. Finally, ``has_entries`` also accepts a list of alternating keys and their
  77. value matchers:
  78. .. function:: has_entries(key1, value_matcher1[, ...])
  79. :param key1: A key (not a matcher) to look up.
  80. :param valueMatcher1: The matcher to satisfy for the value, or an expected
  81. value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching.
  82. Examples::
  83. has_entries('foo', equal_to(1), 'bar', equal_to(2))
  84. has_entries('foo', 1, 'bar', 2)
  85. """
  86. if len(keys_valuematchers) == 1:
  87. try:
  88. base_dict = keys_valuematchers[0].copy()
  89. for key in base_dict:
  90. base_dict[key] = wrap_matcher(base_dict[key])
  91. except AttributeError:
  92. raise ValueError('single-argument calls to has_entries must pass a dict as the argument')
  93. else:
  94. if len(keys_valuematchers) % 2:
  95. raise ValueError('has_entries requires key-value pairs')
  96. base_dict = {}
  97. for index in range(int(len(keys_valuematchers) / 2)):
  98. base_dict[keys_valuematchers[2 * index]] = wrap_matcher(keys_valuematchers[2 * index + 1])
  99. for key, value in kv_args.items():
  100. base_dict[key] = wrap_matcher(value)
  101. return IsDictContainingEntries(base_dict)