Debian Codegraph @

tests/tabular_output/test_preprocessors.py

raw
1 # -*- coding: utf-8 -*-
2 """Test CLI Helpers' tabular output preprocessors."""
3
4 from __future__ import unicode_literals
5 from decimal import Decimal
6 import os
7
8 import pytest
9
10 from cli_helpers.compat import HAS_PYGMENTS
11 from cli_helpers.tabular_output.preprocessors import (
12 align_decimals,
13 bytes_to_string,
14 convert_to_string,
15 convert_to_undecoded_string,
16 quote_whitespaces,
17 override_missing_value,
18 override_tab_value,
19 style_output,
20 format_numbers,
21 format_timestamps,
22 )
23
24 if HAS_PYGMENTS:
25 from pygments.style import Style
26 from pygments.token import Token
27
28 import inspect
29 import cli_helpers.tabular_output.preprocessors
30 import types
31
32
33 @pytest.fixture
34 def TwoFiftySixColor():
35 # todo: finalize this fixture by resetting the env value
36 os.environ["COLORTERM"] = ""
37
38
39 def test_convert_to_string():
40 """Test the convert_to_string() function."""
41 data = [[1, "John"], [2, "Jill"]]
42 headers = [0, "name"]
43 expected = ([["1", "John"], ["2", "Jill"]], ["0", "name"])
44 results = convert_to_string(data, headers)
45
46 assert expected == (list(results[0]), results[1])
47
48
49 def test_convert_to_undecoded_string():
50 """Test the convert_to_undecoded_string() function."""
51 data = [[1, "John"], [2, b"Jill"], [3, None]]
52 headers = [0, "name"]
53 expected = ([["1", "John"], ["2", "0x4a696c6c"], ["3", None]], ["0", "name"])
54 results = convert_to_undecoded_string(data, headers)
55
56 assert expected == (list(results[0]), results[1])
57
58
59 def test_override_missing_values():
60 """Test the override_missing_values() function."""
61 data = [[1, None], [2, "Jill"]]
62 headers = [0, "name"]
63 expected = ([[1, "<EMPTY>"], [2, "Jill"]], [0, "name"])
64 results = override_missing_value(data, headers, missing_value="<EMPTY>")
65
66 assert expected == (list(results[0]), results[1])
67
68
69 @pytest.mark.skipif(not HAS_PYGMENTS, reason="requires the Pygments library")
70 def test_override_missing_value_with_style(TwoFiftySixColor):
71 """Test that *override_missing_value()* styles output."""
72
73 class NullStyle(Style):
74 styles = {Token.Output.Null: "#0f0"}
75
76 headers = ["h1", "h2"]
77 data = [[None, "2"], ["abc", None]]
78
79 expected_headers = ["h1", "h2"]
80 expected_data = [
81 ["\x1b[38;5;10m<null>\x1b[39m", "2"],
82 ["abc", "\x1b[38;5;10m<null>\x1b[39m"],
83 ]
84 results = override_missing_value(
85 data, headers, style=NullStyle, missing_value="<null>"
86 )
87
88 assert (expected_data, expected_headers) == (list(results[0]), results[1])
89
90
91 def test_override_tab_value():
92 """Test the override_tab_value() function."""
93 data = [[1, "\tJohn"], [2, "Jill"]]
94 headers = ["id", "name"]
95 expected = ([[1, " John"], [2, "Jill"]], ["id", "name"])
96 results = override_tab_value(data, headers)
97
98 assert expected == (list(results[0]), results[1])
99
100
101 def test_bytes_to_string():
102 """Test the bytes_to_string() function."""
103 data = [[1, "John"], [2, b"Jill"]]
104 headers = [0, "name"]
105 expected = ([[1, "John"], [2, "Jill"]], [0, "name"])
106 results = bytes_to_string(data, headers)
107
108 assert expected == (list(results[0]), results[1])
109
110
111 def test_align_decimals():
112 """Test the align_decimals() function."""
113 data = [[Decimal("200"), Decimal("1")], [Decimal("1.00002"), Decimal("1.0")]]
114 headers = ["num1", "num2"]
115 column_types = (float, float)
116 expected = ([["200", "1"], [" 1.00002", "1.0"]], ["num1", "num2"])
117 results = align_decimals(data, headers, column_types=column_types)
118
119 assert expected == (list(results[0]), results[1])
120
121
122 def test_align_decimals_empty_result():
123 """Test align_decimals() with no results."""
124 data = []
125 headers = ["num1", "num2"]
126 column_types = ()
127 expected = ([], ["num1", "num2"])
128 results = align_decimals(data, headers, column_types=column_types)
129
130 assert expected == (list(results[0]), results[1])
131
132
133 def test_align_decimals_non_decimals():
134 """Test align_decimals() with non-decimals."""
135 data = [[Decimal("200.000"), Decimal("1.000")], [None, None]]
136 headers = ["num1", "num2"]
137 column_types = (float, float)
138 expected = ([["200.000", "1.000"], [None, None]], ["num1", "num2"])
139 results = align_decimals(data, headers, column_types=column_types)
140
141 assert expected == (list(results[0]), results[1])
142
143
144 def test_quote_whitespaces():
145 """Test the quote_whitespaces() function."""
146 data = [[" before", "after "], [" both ", "none"]]
147 headers = ["h1", "h2"]
148 expected = ([["' before'", "'after '"], ["' both '", "'none'"]], ["h1", "h2"])
149 results = quote_whitespaces(data, headers)
150
151 assert expected == (list(results[0]), results[1])
152
153
154 def test_quote_whitespaces_empty_result():
155 """Test the quote_whitespaces() function with no results."""
156 data = []
157 headers = ["h1", "h2"]
158 expected = ([], ["h1", "h2"])
159 results = quote_whitespaces(data, headers)
160
161 assert expected == (list(results[0]), results[1])
162
163
164 def test_quote_whitespaces_non_spaces():
165 """Test the quote_whitespaces() function with non-spaces."""
166 data = [["\tbefore", "after \r"], ["\n both ", "none"]]
167 headers = ["h1", "h2"]
168 expected = ([["'\tbefore'", "'after \r'"], ["'\n both '", "'none'"]], ["h1", "h2"])
169 results = quote_whitespaces(data, headers)
170
171 assert expected == (list(results[0]), results[1])
172
173
174 @pytest.mark.skipif(not HAS_PYGMENTS, reason="requires the Pygments library")
175 def test_style_output_no_styles():
176 """Test that *style_output()* does not style without styles."""
177 headers = ["h1", "h2"]
178 data = [["1", "2"], ["a", "b"]]
179 results = style_output(data, headers)
180
181 assert (data, headers) == (list(results[0]), results[1])
182
183
184 @pytest.mark.skipif(HAS_PYGMENTS, reason="requires the Pygments library be missing")
185 def test_style_output_no_pygments():
186 """Test that *style_output()* does not try to style without Pygments."""
187 headers = ["h1", "h2"]
188 data = [["1", "2"], ["a", "b"]]
189 results = style_output(data, headers)
190
191 assert (data, headers) == (list(results[0]), results[1])
192
193
194 @pytest.mark.skipif(not HAS_PYGMENTS, reason="requires the Pygments library")
195 def test_style_output(TwoFiftySixColor):
196 """Test that *style_output()* styles output."""
197
198 class CliStyle(Style):
199 default_style = ""
200 styles = {
201 Token.Output.Header: "bold ansibrightred",
202 Token.Output.OddRow: "bg:#eee #111",
203 Token.Output.EvenRow: "#0f0",
204 }
205
206 headers = ["h1", "h2"]
207 data = [["观音", "2"], ["Ποσειδῶν", "b"]]
208
209 expected_headers = ["\x1b[91;01mh1\x1b[39;00m", "\x1b[91;01mh2\x1b[39;00m"]
210 # Pygments v2.19.2 and earlier
211 expected_data_old = [
212 ["\x1b[38;5;233;48;5;7m观音\x1b[39;49m", "\x1b[38;5;233;48;5;7m2\x1b[39;49m"],
213 ["\x1b[38;5;10mΠοσειδῶν\x1b[39m", "\x1b[38;5;10mb\x1b[39m"],
214 ]
215 # Pygments v2.20.0 and later
216 # it looks like the control sequences changed after https://github.com/pygments/pygments/pull/3043
217 expected_data_new = [
218 [
219 '\x1b[38;5;233;48;5;255m观音\x1b[39;49m',
220 '\x1b[38;5;233;48;5;255m2\x1b[39;49m',
221 ],
222 ['\x1b[38;5;10mΠοσειδῶν\x1b[39m', '\x1b[38;5;10mb\x1b[39m'],
223 ]
224 results = style_output(data, headers, style=CliStyle)
225
226 assert results[1] == expected_headers
227 assert list(results[0]) in [expected_data_old, expected_data_new]
228
229
230 @pytest.mark.skipif(not HAS_PYGMENTS, reason="requires the Pygments library")
231 def test_style_output_with_newlines(TwoFiftySixColor):
232 """Test that *style_output()* styles output with newlines in it."""
233
234 class CliStyle(Style):
235 default_style = ""
236 styles = {
237 Token.Output.Header: "bold ansibrightred",
238 Token.Output.OddRow: "bg:#eee #111",
239 Token.Output.EvenRow: "#0f0",
240 }
241
242 headers = ["h1", "h2"]
243 data = [["观音\nLine2", "Ποσειδῶν"]]
244
245 expected_headers = ["\x1b[91;01mh1\x1b[39;00m", "\x1b[91;01mh2\x1b[39;00m"]
246 # Pygments v2.19.2 and earlier
247 expected_data_old = [
248 [
249 "\x1b[38;5;233;48;5;7m观音\x1b[39;49m\n\x1b[38;5;233;48;5;7m"
250 "Line2\x1b[39;49m",
251 "\x1b[38;5;233;48;5;7mΠοσειδῶν\x1b[39;49m",
252 ]
253 ]
254 # Pygments v2.20.0 and later
255 # it looks like the control sequences changed after https://github.com/pygments/pygments/pull/3043
256 expected_data_new = [
257 [
258 '\x1b[38;5;233;48;5;255m观音\x1b[39;49m\n\x1b[38;5;233;48;5;255m'
259 'Line2\x1b[39;49m',
260 '\x1b[38;5;233;48;5;255mΠοσειδῶν\x1b[39;49m',
261 ]
262 ]
263 results = style_output(data, headers, style=CliStyle)
264
265 assert results[1] == expected_headers
266 assert list(results[0]) in [expected_data_old, expected_data_new]
267
268
269 @pytest.mark.skipif(not HAS_PYGMENTS, reason="requires the Pygments library")
270 def test_style_output_custom_tokens(TwoFiftySixColor):
271 """Test that *style_output()* styles output with custom token names."""
272
273 class CliStyle(Style):
274 default_style = ""
275 styles = {
276 Token.Results.Headers: "bold ansibrightred",
277 Token.Results.OddRows: "bg:#eee #111",
278 Token.Results.EvenRows: "#0f0",
279 }
280
281 headers = ["h1", "h2"]
282 data = [["1", "2"], ["a", "b"]]
283
284 expected_headers = ["\x1b[91;01mh1\x1b[39;00m", "\x1b[91;01mh2\x1b[39;00m"]
285 # Pygments v2.19.2 and earlier
286 expected_data_old = [
287 ["\x1b[38;5;233;48;5;7m1\x1b[39;49m", "\x1b[38;5;233;48;5;7m2\x1b[39;49m"],
288 ["\x1b[38;5;10ma\x1b[39m", "\x1b[38;5;10mb\x1b[39m"],
289 ]
290 # Pygments v2.20.0 and later
291 # it looks like the control sequences changed after https://github.com/pygments/pygments/pull/3043
292 expected_data_new = [
293 ['\x1b[38;5;233;48;5;255m1\x1b[39;49m', '\x1b[38;5;233;48;5;255m2\x1b[39;49m'],
294 ['\x1b[38;5;10ma\x1b[39m', '\x1b[38;5;10mb\x1b[39m'],
295 ]
296
297 output = style_output(
298 data,
299 headers,
300 style=CliStyle,
301 header_token=Token.Results.Headers,
302 odd_row_token=Token.Results.OddRows,
303 even_row_token=Token.Results.EvenRows,
304 )
305
306 assert output[1] == expected_headers
307 assert list(output[0]) in [expected_data_old, expected_data_new]
308
309
310 def test_format_integer():
311 """Test formatting for an INTEGER datatype."""
312 data = [[1], [1000], [1000000]]
313 headers = ["h1"]
314 result_data, result_headers = format_numbers(
315 data, headers, column_types=(int,), integer_format=",", float_format=","
316 )
317
318 expected = [["1"], ["1,000"], ["1,000,000"]]
319 assert expected == list(result_data)
320 assert headers == result_headers
321
322
323 def test_format_decimal():
324 """Test formatting for a DECIMAL(12, 4) datatype."""
325 data = [[Decimal("1.0000")], [Decimal("1000.0000")], [Decimal("1000000.0000")]]
326 headers = ["h1"]
327 result_data, result_headers = format_numbers(
328 data, headers, column_types=(float,), integer_format=",", float_format=","
329 )
330
331 expected = [["1.0000"], ["1,000.0000"], ["1,000,000.0000"]]
332 assert expected == list(result_data)
333 assert headers == result_headers
334
335
336 def test_format_float():
337 """Test formatting for a REAL datatype."""
338 data = [[1.0], [1000.0], [1000000.0]]
339 headers = ["h1"]
340 result_data, result_headers = format_numbers(
341 data, headers, column_types=(float,), integer_format=",", float_format=","
342 )
343 expected = [["1.0"], ["1,000.0"], ["1,000,000.0"]]
344 assert expected == list(result_data)
345 assert headers == result_headers
346
347
348 def test_format_integer_only():
349 """Test that providing one format string works."""
350 data = [[1, 1.0], [1000, 1000.0], [1000000, 1000000.0]]
351 headers = ["h1", "h2"]
352 result_data, result_headers = format_numbers(
353 data, headers, column_types=(int, float), integer_format=","
354 )
355
356 expected = [["1", 1.0], ["1,000", 1000.0], ["1,000,000", 1000000.0]]
357 assert expected == list(result_data)
358 assert headers == result_headers
359
360
361 def test_format_numbers_no_format_strings():
362 """Test that numbers aren't formatted without format strings."""
363 data = ((1), (1000), (1000000))
364 headers = ("h1",)
365 result_data, result_headers = format_numbers(data, headers, column_types=(int,))
366 assert list(data) == list(result_data)
367 assert headers == result_headers
368
369
370 def test_format_numbers_no_column_types():
371 """Test that numbers aren't formatted without column types."""
372 data = ((1), (1000), (1000000))
373 headers = ("h1",)
374 result_data, result_headers = format_numbers(
375 data, headers, integer_format=",", float_format=","
376 )
377 assert list(data) == list(result_data)
378 assert headers == result_headers
379
380
381 def test_enforce_iterable():
382 preprocessors = inspect.getmembers(
383 cli_helpers.tabular_output.preprocessors, inspect.isfunction
384 )
385 loremipsum = (
386 "lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod".split(
387 " "
388 )
389 )
390 for name, preprocessor in preprocessors:
391 preprocessed = preprocessor(zip(loremipsum), ["lorem"], column_types=(str,))
392 try:
393 first = next(preprocessed[0])
394 except StopIteration:
395 assert False, "{} gives no output with iterator data".format(name)
396 except TypeError:
397 assert False, "{} doesn't return iterable".format(name)
398 if isinstance(preprocessed[1], types.GeneratorType):
399 assert False, "{} returns headers as iterator".format(name)
400
401
402 def test_format_timestamps():
403 data = (
404 ("name1", "2024-12-13T18:32:22", "2024-12-13T19:32:22", "2024-12-13T20:32:22"),
405 ("name2", "2025-02-13T02:32:22", "2025-02-13T02:32:22", "2025-02-13T02:32:22"),
406 ("name3", None, "not-actually-timestamp", "2025-02-13T02:32:22"),
407 )
408 headers = ["name", "date_col", "datetime_col", "unchanged_col"]
409 column_date_formats = {
410 "date_col": "%Y-%m-%d",
411 "datetime_col": "%I:%M:%S %m/%d/%y",
412 }
413 result_data, result_headers = format_timestamps(data, headers, column_date_formats)
414
415 expected = [
416 ["name1", "2024-12-13", "07:32:22 12/13/24", "2024-12-13T20:32:22"],
417 ["name2", "2025-02-13", "02:32:22 02/13/25", "2025-02-13T02:32:22"],
418 ["name3", None, "not-actually-timestamp", "2025-02-13T02:32:22"],
419 ]
420 assert expected == list(result_data)
421 assert headers == result_headers