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.

isequal_ignoring_whitespace.py 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. __author__ = "Jon Reid"
  2. __copyright__ = "Copyright 2011 hamcrest.org"
  3. __license__ = "BSD, see License.txt"
  4. from hamcrest.core.base_matcher import BaseMatcher
  5. import six
  6. def stripspace(string):
  7. result = ''
  8. last_was_space = True
  9. for character in string:
  10. if character.isspace():
  11. if not last_was_space:
  12. result += ' '
  13. last_was_space = True
  14. else:
  15. result += character
  16. last_was_space = False
  17. return result.strip()
  18. class IsEqualIgnoringWhiteSpace(BaseMatcher):
  19. def __init__(self, string):
  20. if not isinstance(string, six.string_types):
  21. raise TypeError('IsEqualIgnoringWhiteSpace requires string')
  22. self.original_string = string
  23. self.stripped_string = stripspace(string)
  24. def _matches(self, item):
  25. if not isinstance(item, six.string_types):
  26. return False
  27. return self.stripped_string == stripspace(item)
  28. def describe_to(self, description):
  29. description.append_description_of(self.original_string) \
  30. .append_text(' ignoring whitespace')
  31. def equal_to_ignoring_whitespace(string):
  32. """Matches if object is a string equal to a given string, ignoring
  33. differences in whitespace.
  34. :param string: The string to compare against as the expected value.
  35. This matcher first checks whether the evaluated object is a string. If so,
  36. it compares it with ``string``, ignoring differences in runs of whitespace.
  37. Example::
  38. equal_to_ignoring_whitespace("hello world")
  39. will match ``"hello world"``.
  40. """
  41. return IsEqualIgnoringWhiteSpace(string)