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.

hasproperty.py 5.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. from hamcrest.core.base_matcher import BaseMatcher
  2. from hamcrest.core import anything
  3. from hamcrest.core.core.allof import all_of
  4. from hamcrest.core.string_description import StringDescription
  5. from hamcrest.core.helpers.hasmethod import hasmethod
  6. from hamcrest.core.helpers.wrap_matcher import wrap_matcher as wrap_shortcut
  7. __author__ = "Chris Rose"
  8. __copyright__ = "Copyright 2011 hamcrest.org"
  9. __license__ = "BSD, see License.txt"
  10. class IsObjectWithProperty(BaseMatcher):
  11. def __init__(self, property_name, value_matcher):
  12. self.property_name = property_name
  13. self.value_matcher = value_matcher
  14. def _matches(self, o):
  15. if o is None:
  16. return False
  17. if not hasattr(o, self.property_name):
  18. return False
  19. value = getattr(o, self.property_name)
  20. return self.value_matcher.matches(value)
  21. def describe_to(self, description):
  22. description.append_text("an object with a property '") \
  23. .append_text(self.property_name) \
  24. .append_text("' matching ") \
  25. .append_description_of(self.value_matcher)
  26. def describe_mismatch(self, item, mismatch_description):
  27. if item is None:
  28. mismatch_description.append_text('was None')
  29. return
  30. if not hasattr(item, self.property_name):
  31. mismatch_description.append_value(item) \
  32. .append_text(' did not have the ') \
  33. .append_value(self.property_name) \
  34. .append_text(' property')
  35. return
  36. mismatch_description.append_text('property ').append_value(self.property_name).append_text(' ')
  37. value = getattr(item, self.property_name)
  38. self.value_matcher.describe_mismatch(value, mismatch_description)
  39. def __str__(self):
  40. d = StringDescription()
  41. self.describe_to(d)
  42. return str(d)
  43. def has_property(name, match=None):
  44. """Matches if object has a property with a given name whose value satisfies
  45. a given matcher.
  46. :param name: The name of the property.
  47. :param match: Optional matcher to satisfy.
  48. This matcher determines if the evaluated object has a property with a given
  49. name. If no such property is found, ``has_property`` is not satisfied.
  50. If the property is found, its value is passed to a given matcher for
  51. evaluation. If the ``match`` argument is not a matcher, it is implicitly
  52. wrapped in an :py:func:`~hamcrest.core.core.isequal.equal_to` matcher to
  53. check for equality.
  54. If the ``match`` argument is not provided, the
  55. :py:func:`~hamcrest.core.core.isanything.anything` matcher is used so that
  56. ``has_property`` is satisfied if a matching property is found.
  57. Examples::
  58. has_property('name', starts_with('J'))
  59. has_property('name', 'Jon')
  60. has_property('name')
  61. """
  62. if match is None:
  63. match = anything()
  64. return IsObjectWithProperty(name, wrap_shortcut(match))
  65. def has_properties(*keys_valuematchers, **kv_args):
  66. """Matches if an object has properties satisfying all of a dictionary
  67. of string property names and corresponding value matchers.
  68. :param matcher_dict: A dictionary mapping keys to associated value matchers,
  69. or to expected values for
  70. :py:func:`~hamcrest.core.core.isequal.equal_to` matching.
  71. Note that the keys must be actual keys, not matchers. Any value argument
  72. that is not a matcher is implicitly wrapped in an
  73. :py:func:`~hamcrest.core.core.isequal.equal_to` matcher to check for
  74. equality.
  75. Examples::
  76. has_properties({'foo':equal_to(1), 'bar':equal_to(2)})
  77. has_properties({'foo':1, 'bar':2})
  78. ``has_properties`` also accepts a list of keyword arguments:
  79. .. function:: has_properties(keyword1=value_matcher1[, keyword2=value_matcher2[, ...]])
  80. :param keyword1: A keyword to look up.
  81. :param valueMatcher1: The matcher to satisfy for the value, or an expected
  82. value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching.
  83. Examples::
  84. has_properties(foo=equal_to(1), bar=equal_to(2))
  85. has_properties(foo=1, bar=2)
  86. Finally, ``has_properties`` also accepts a list of alternating keys and their
  87. value matchers:
  88. .. function:: has_properties(key1, value_matcher1[, ...])
  89. :param key1: A key (not a matcher) to look up.
  90. :param valueMatcher1: The matcher to satisfy for the value, or an expected
  91. value for :py:func:`~hamcrest.core.core.isequal.equal_to` matching.
  92. Examples::
  93. has_properties('foo', equal_to(1), 'bar', equal_to(2))
  94. has_properties('foo', 1, 'bar', 2)
  95. """
  96. if len(keys_valuematchers) == 1:
  97. try:
  98. base_dict = keys_valuematchers[0].copy()
  99. for key in base_dict:
  100. base_dict[key] = wrap_shortcut(base_dict[key])
  101. except AttributeError:
  102. raise ValueError('single-argument calls to has_properties must pass a dict as the argument')
  103. else:
  104. if len(keys_valuematchers) % 2:
  105. raise ValueError('has_properties requires key-value pairs')
  106. base_dict = {}
  107. for index in range(int(len(keys_valuematchers) / 2)):
  108. base_dict[keys_valuematchers[2 * index]] = wrap_shortcut(keys_valuematchers[2 * index + 1])
  109. for key, value in kv_args.items():
  110. base_dict[key] = wrap_shortcut(value)
  111. return all_of(*[has_property(property_name, property_value_matcher) for \
  112. property_name, property_value_matcher in base_dict.items()])