Debian Codegraph @

behave4cmd0/textutil.py

raw
1 # -*- coding -*-
2 """
3 Provides some command utility functions.
4
5 TODO:
6 matcher that ignores empty lines and whitespace and has contains comparison
7 """
8
9 from __future__ import absolute_import, print_function
10 from hamcrest import assert_that, is_not, equal_to, contains_string
11 # DISABLED: from behave4cmd.hamcrest_text import matches_regexp
12 import codecs
13
14 DEBUG = False
15
16 # -----------------------------------------------------------------------------
17 # CLASS: TextProxy
18 # -----------------------------------------------------------------------------
19 # class TextProxy(object):
20 # """
21 # Simplifies conversion between (Unicode) string and its byte representation.
22 # Provides a ValueObject to store a string or its byte representation.
23 # Afterwards you can explicitly access both representations by using:
24 #
25 # EXAMPLE:
26 #
27 # .. testcode::
28 #
29 # from behave4cmd.textutil import TextProxy
30 # message = TextProxy("Hello world", encoding="UTF-8")
31 # assert message.data == "Hello world" # -- RAW DATA access.
32 # assert isinstance(message.text, basestring)
33 # assert isinstance(message.bytes, bytes)
34 # assert message == "Hello world"
35 # assert len(message) == len(message.data) == 11
36 # """
37 # encoding_errors = "strict"
38 # default_encoding = "UTF-8"
39 #
40 # def __init__(self, data=None, encoding=None, errors=None):
41 # self.encoding = encoding or self.default_encoding
42 # self.errors = errors or self.encoding_errors
43 # self.set(data)
44 #
45 # def get(self):
46 # return self.data
47 #
48 # def set(self, data):
49 # self.data = data or ""
50 # self._text = None
51 # self._bytes = None
52 #
53 # def clear(self):
54 # self.set(None)
55 #
56 # @property
57 # def text(self):
58 # """Provide access to string-representation of the data."""
59 # if self._text is None:
60 # if isinstance(self.data, basestring):
61 # _text = self.data
62 # elif isinstance(self.data, bytes):
63 # _text = codecs.decode(self.data, self.encoding, self.errors)
64 # else:
65 # _text = str(self.data)
66 # self._text = _text
67 # assert isinstance(self._text, basestring)
68 # return self._text
69 #
70 # @property
71 # def bytes(self):
72 # """Provide access to byte-representation of the data."""
73 # if self._bytes is None:
74 # if isinstance(self.data, bytes) and not isinstance(self.data, str):
75 # self._bytes = self.data
76 # else:
77 # text = self.data
78 # if not isinstance(text, basestring):
79 # text = unicode(text)
80 # assert isinstance(text, basestring)
81 # self._bytes = codecs.encode(text, self.encoding, self.errors)
82 # assert isinstance(self._bytes, bytes)
83 # return self._bytes
84 #
85 # def __repr__(self):
86 # """Textual representation of this object."""
87 # data = self.data or ""
88 # prefix = ""
89 # if isinstance(data, bytes) and not isinstance(data, basestring):
90 # prefix= u"b"
91 # # str(self.text)
92 # # str(self.encoding)
93 # # str(prefix)
94 # # _ = u"<TextProxy data[size=%d]=x'x', encoding=x>" % len(self)
95 # # _ = u"<TextProxy data[size=x]=%s'x', encoding=x>" % prefix
96 # # _ = u"<TextProxy data[size=x]=x'%s', encoding=x>" % self.text
97 # # _ = u"<TextProxy data[size=x]=x'x', encoding=%s>" % self.encoding
98 # return u"<TextProxy data[size=%d]=%s'%s', encoding=%s>" %\
99 # (len(self), prefix, self.text, self.encoding)
100 #
101 # def __str__(self):
102 # """Conversion into str() object."""
103 # return self.text
104 #
105 # def __bytes__(self):
106 # """Conversion into bytes() object."""
107 # return self.bytes
108 #
109 # def __bool__(self):
110 # """Conversion into a bool value, used for truth testing."""
111 # return bool(self.data)
112 #
113 # def __iter__(self):
114 # """Conversion into an iterator."""
115 # return iter(self.data)
116 #
117 # def __contains__(self, item):
118 # """Check if item is contained in raw data."""
119 # if isinstance(item, basestring):
120 # return item in self.text
121 # elif isinstance(item, bytes):
122 # return item in self.bytes
123 # else:
124 # return item in self.data
125 #
126 # def __len__(self):
127 # if self.data is None:
128 # return 0
129 # return len(self.data)
130 #
131 # def __nonzero__(self):
132 # return len(self) > 0
133 #
134 # def __eq__(self, other):
135 # if isinstance(other, basestring):
136 # return self.text == other
137 # elif isinstance(other, bytes):
138 # return self.bytes == other
139 # else:
140 # return self.data == other
141 #
142 # def __ne__(self, other):
143 # return not (self == other)
144 #
145 # -----------------------------------------------------------------------------
146 # UTILITY FUNCTIONS:
147 # -----------------------------------------------------------------------------
148 def template_substitute(text, **kwargs):
149 """
150 Replace placeholders in text by using the data mapping.
151 Other placeholders that is not represented by data is left untouched.
152
153 :param text: Text to search and replace placeholders.
154 :param data: Data mapping/dict for placeholder key and values.
155 :return: Potentially modified text with replaced placeholders.
156 """
157 for name, value in kwargs.items():
158 placeholder_pattern = "{%s}" % name
159 if placeholder_pattern in text:
160 text = text.replace(placeholder_pattern, value)
161 return text
162
163
164 def text_remove_empty_lines(text):
165 """
166 Whitespace normalization:
167
168 - Strip empty lines
169 - Strip trailing whitespace
170 """
171 lines = [ line.rstrip() for line in text.splitlines() if line.strip() ]
172 return "\n".join(lines)
173
174 def text_normalize(text):
175 """
176 Whitespace normalization:
177
178 - Strip empty lines
179 - Strip leading whitespace in a line
180 - Strip trailing whitespace in a line
181 - Normalize line endings
182 """
183 # if not isinstance(text, str):
184 if isinstance(text, bytes):
185 # -- MAYBE: command.ouput => bytes, encoded stream output.
186 text = codecs.decode(text)
187 lines = [ line.strip() for line in text.splitlines() if line.strip() ]
188 return "\n".join(lines)
189
190 # -----------------------------------------------------------------------------
191 # ASSERTIONS:
192 # -----------------------------------------------------------------------------
193 from hamcrest.library.text.substringmatcher import SubstringMatcher
194 from hamcrest.core.helpers.hasmethod import hasmethod
195
196 class StringContainsMultipleTimes(SubstringMatcher):
197
198 def __init__(self, substring, expected_count):
199 super(StringContainsMultipleTimes, self).__init__(substring)
200 self.expected_count = expected_count
201 self.actual_count = 0
202
203 def describe_to(self, description):
204 description.append_text('a string ') \
205 .append_text(self.relationship()) \
206 .append_text(" ") \
207 .append_description_of(self.substring) \
208 .append_text(" ") \
209 .append_description_of(self.expected_count) \
210 .append_text(" times instead of ") \
211 .append_description_of(self.actual_count)
212
213 def _matches(self, item):
214 if not hasmethod(item, "count"):
215 return False
216 self.actual_count = item.count(self.substring)
217 return self.actual_count == self.expected_count
218
219 def relationship(self):
220 return "containing"
221
222
223 def contains_substring_multiple_times(substring, expected_count):
224 return StringContainsMultipleTimes(substring, expected_count)
225
226
227 # -----------------------------------------------------------------------------
228 # ASSERTIONS:
229 # -----------------------------------------------------------------------------
230 def assert_text_should_equal(actual_text, expected_text):
231 assert_that(actual_text, equal_to(expected_text))
232
233 def assert_text_should_not_equal(actual_text, expected_text):
234 assert_that(actual_text, is_not(equal_to(expected_text)))
235
236 def assert_text_should_contain_exactly(text, expected_part):
237 assert_that(text, contains_string(expected_part))
238
239 def assert_text_should_not_contain_exactly(text, expected_part):
240 assert_that(text, is_not(contains_string(expected_part)))
241
242 def assert_text_should_contain(text, expected_part):
243 assert_that(text, contains_string(expected_part))
244
245 def assert_normtext_should_contain_multiple_times(text, expected_text, count):
246 assert_that(text, contains_substring_multiple_times(expected_text, count))
247
248 def assert_text_should_not_contain(text, unexpected_part):
249 assert_that(text, is_not(contains_string(unexpected_part)))
250
251 def assert_normtext_should_equal(actual_text, expected_text):
252 expected_text2 = text_normalize(expected_text.strip())
253 actual_text2 = text_normalize(actual_text.strip())
254 assert_that(actual_text2, equal_to(expected_text2))
255
256 def assert_normtext_should_not_equal(actual_text, expected_text):
257 expected_text2 = text_normalize(expected_text.strip())
258 actual_text2 = text_normalize(actual_text.strip())
259 assert_that(actual_text2, is_not(equal_to(expected_text2)))
260
261 def assert_normtext_should_contain(text, expected_part):
262 expected_part2 = text_normalize(expected_part)
263 actual_text = text_normalize(text.strip())
264 if DEBUG:
265 print("expected:\n{0}".format(expected_part2))
266 print("actual:\n{0}".format(actual_text))
267 assert_text_should_contain(actual_text, expected_part2)
268
269 def assert_normtext_should_not_contain(text, unexpected_part):
270 unexpected_part2 = text_normalize(unexpected_part)
271 actual_text = text_normalize(text.strip())
272 if DEBUG:
273 print("expected:\n{0}".format(unexpected_part2))
274 print("actual:\n{0}".format(actual_text))
275 assert_text_should_not_contain(actual_text, unexpected_part2)
276
277
278 # def assert_text_should_match_pattern(text, pattern):
279 # """
280 # Assert that the :attr:`text` matches the regular expression :attr:`pattern`.
281 #
282 # :param text: Multi-line text (as string).
283 # :param pattern: Regular expression pattern (as string, compiled regexp).
284 # :raise: AssertionError, if text matches not the pattern.
285 # """
286 # assert_that(text, matches_regexp(pattern))
287 #
288 # def assert_text_should_not_match_pattern(text, pattern):
289 # """
290 # Assert that the :attr:`text` matches not the regular expression
291 # :attr:`pattern`.
292 #
293 # :param text: Multi-line text (as string).
294 # :param pattern: Regular expression pattern (as string, compiled regexp).
295 # :raise: AssertionError, if text matches the pattern.
296 # """
297 # assert_that(text, is_not(matches_regexp(pattern)))
298 #
299 # -----------------------------------------------------------------------------
300 # MAIN:
301 # -----------------------------------------------------------------------------
302 if __name__ == "__main__":
303 import doctest
304 doctest.testmod()