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