Debian Codegraph @

tests/tabular_output/test_output_formatter.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """Test the generic output formatter interface."""
3
4 from __future__ import unicode_literals
5 from decimal import Decimal
6 from textwrap import dedent
7
8 import pytest
9
10 from cli_helpers.tabular_output import format_output, TabularOutputFormatter
11 from cli_helpers.compat import binary_type, text_type
12 from cli_helpers.utils import strip_ansi
13
14
15 def test_tabular_output_formatter():
16 """Test the TabularOutputFormatter class."""
17 headers = ["text", "numeric"]
18 data = [
19 ["abc", Decimal(1)],
20 ["defg", Decimal("11.1")],
21 ["hi", Decimal("1.1")],
22 ["Pablo\rß\n", 0],
23 ]
24 expected = dedent(
25 """\
26 +-------+---------+
27 | text | numeric |
28 +-------+---------+
29 | abc | 1 |
30 | defg | 11.1 |
31 | hi | 1.1 |
32 | Pablo | 0 |
33 | ß | |
34 +-------+---------+"""
35 )
36
37 print(expected)
38 print(
39 "\n".join(
40 TabularOutputFormatter().format_output(
41 iter(data), headers, format_name="ascii"
42 )
43 )
44 )
45 assert expected == "\n".join(
46 TabularOutputFormatter().format_output(iter(data), headers, format_name="ascii")
47 )
48
49
50 def test_tabular_output_escaped():
51 """Test the ascii_escaped output format."""
52 headers = ["text", "numeric"]
53 data = [
54 ["abc", Decimal(1)],
55 ["defg", Decimal("11.1")],
56 ["hi", Decimal("1.1")],
57 ["Pablo\rß\n", 0],
58 ]
59 expected = dedent(
60 """\
61 +------------+---------+
62 | text | numeric |
63 +------------+---------+
64 | abc | 1 |
65 | defg | 11.1 |
66 | hi | 1.1 |
67 | Pablo\\rß\\n | 0 |
68 +------------+---------+"""
69 )
70
71 print(expected)
72 print(
73 "\n".join(
74 TabularOutputFormatter().format_output(
75 iter(data), headers, format_name="ascii_escaped"
76 )
77 )
78 )
79 assert expected == "\n".join(
80 TabularOutputFormatter().format_output(
81 iter(data), headers, format_name="ascii_escaped"
82 )
83 )
84
85
86 def test_tabular_output_mysql():
87 """Test the mysql output format."""
88 headers = ["text", "numeric"]
89 data = [
90 ["abc", Decimal(1)],
91 ["defg", Decimal("11.1")],
92 ["hi", Decimal("1.1")],
93 ["Pablo\rß\n", 0],
94 ]
95 expected = dedent(
96 """\
97 +-------+---------+
98 | text | numeric |
99 +-------+---------+
100 | abc | 1 |
101 | defg | 11.1 |
102 | hi | 1.1 |
103 | Pablo | 0 |
104 | ß | |
105 +-------+---------+"""
106 )
107
108 print(expected)
109 print(
110 "\n".join(
111 TabularOutputFormatter().format_output(
112 iter(data), headers, format_name="mysql"
113 )
114 )
115 )
116 assert expected == "\n".join(
117 TabularOutputFormatter().format_output(iter(data), headers, format_name="mysql")
118 )
119
120
121 def test_tabular_output_mysql_unicode():
122 """Test the mysql_unicode output format."""
123 headers = ["text", "numeric"]
124 data = [
125 ["abc", Decimal(1)],
126 ["defg", Decimal("11.1")],
127 ["hi", Decimal("1.1")],
128 ["Pablo\rß\n", 0],
129 ]
130 expected = dedent(
131 """\
132 ┌───────┬─────────┐
133 │ text │ numeric │
134 ├───────┼─────────┤
135 │ abc │ 1 │
136 │ defg │ 11.1 │
137 │ hi │ 1.1 │
138 │ Pablo │ 0 │
139 │ ß │ │
140 └───────┴─────────┘"""
141 )
142
143 print(expected)
144 print(
145 "\n".join(
146 TabularOutputFormatter().format_output(
147 iter(data), headers, format_name="mysql_unicode"
148 )
149 )
150 )
151 assert expected == "\n".join(
152 TabularOutputFormatter().format_output(
153 iter(data), headers, format_name="mysql_unicode"
154 )
155 )
156
157
158 def test_tabular_format_output_wrapper():
159 """Test the format_output wrapper."""
160 data = [["1", None], ["2", "Sam"], ["3", "Joe"]]
161 headers = ["id", "name"]
162 expected = dedent(
163 """\
164 +----+------+
165 | id | name |
166 +----+------+
167 | 1 | N/A |
168 | 2 | Sam |
169 | 3 | Joe |
170 +----+------+"""
171 )
172
173 assert expected == "\n".join(
174 format_output(iter(data), headers, format_name="ascii", missing_value="N/A")
175 )
176
177
178 def test_additional_preprocessors():
179 """Test that additional preprocessors are run."""
180
181 def hello_world(data, headers, **_):
182 def hello_world_data(data):
183 for row in data:
184 for i, value in enumerate(row):
185 if value == "hello":
186 row[i] = "{}, world".format(value)
187 yield row
188
189 return hello_world_data(data), headers
190
191 data = [["foo", None], ["hello!", "hello"]]
192 headers = "ab"
193
194 expected = dedent(
195 """\
196 +--------+--------------+
197 | a | b |
198 +--------+--------------+
199 | foo | hello |
200 | hello! | hello, world |
201 +--------+--------------+"""
202 )
203
204 assert expected == "\n".join(
205 TabularOutputFormatter().format_output(
206 iter(data),
207 headers,
208 format_name="ascii",
209 preprocessors=(hello_world,),
210 missing_value="hello",
211 )
212 )
213
214
215 def test_format_name_attribute():
216 """Test the the format_name attribute be set and retrieved."""
217 formatter = TabularOutputFormatter(format_name="plain")
218 assert formatter.format_name == "plain"
219 formatter.format_name = "simple"
220 assert formatter.format_name == "simple"
221
222 with pytest.raises(ValueError):
223 formatter.format_name = "foobar"
224
225
226 def test_headless_tabulate_format():
227 """Test that a headless formatter doesn't display headers"""
228 formatter = TabularOutputFormatter(format_name="minimal")
229 headers = ["text", "numeric"]
230 data = [["a"], ["b"], ["c"]]
231 expected = "a\nb\nc"
232 assert expected == "\n".join(
233 TabularOutputFormatter().format_output(
234 iter(data),
235 headers,
236 format_name="minimal",
237 )
238 )
239
240
241 def test_unsupported_format():
242 """Test that TabularOutputFormatter rejects unknown formats."""
243 formatter = TabularOutputFormatter()
244
245 with pytest.raises(ValueError):
246 formatter.format_name = "foobar"
247
248 with pytest.raises(ValueError):
249 formatter.format_output((), (), format_name="foobar")
250
251
252 def test_supported_json_formats():
253 """Test that the JSONl formats are known."""
254 formatter = TabularOutputFormatter()
255 assert "jsonl" in formatter.supported_formats
256 assert "jsonl_escaped" in formatter.supported_formats
257
258
259 def test_tabulate_ansi_escape_in_default_value():
260 """Test that ANSI escape codes work with tabulate."""
261
262 data = [["1", None], ["2", "Sam"], ["3", "Joe"]]
263 headers = ["id", "name"]
264
265 styled = format_output(
266 iter(data),
267 headers,
268 format_name="psql",
269 missing_value="\x1b[38;5;10mNULL\x1b[39m",
270 )
271 unstyled = format_output(
272 iter(data), headers, format_name="psql", missing_value="NULL"
273 )
274
275 stripped_styled = [strip_ansi(s) for s in styled]
276
277 assert list(unstyled) == stripped_styled
278
279
280 def test_get_type():
281 """Test that _get_type returns the expected type."""
282 formatter = TabularOutputFormatter()
283
284 tests = (
285 (1, int),
286 (2.0, float),
287 (b"binary", binary_type),
288 ("text", text_type),
289 (None, type(None)),
290 ((), text_type),
291 )
292
293 for value, data_type in tests:
294 assert data_type is formatter._get_type(value)
295
296
297 def test_provide_column_types():
298 """Test that provided column types are passed to preprocessors."""
299 expected_column_types = (bool, float)
300 data = ((1, 1.0), (0, 2))
301 headers = ("a", "b")
302
303 def preprocessor(data, headers, column_types=(), **_):
304 assert expected_column_types == column_types
305 return data, headers
306
307 format_output(
308 data,
309 headers,
310 "csv",
311 column_types=expected_column_types,
312 preprocessors=(preprocessor,),
313 )
314
315
316 def test_enforce_iterable():
317 """Test that all output formatters accept iterable"""
318 formatter = TabularOutputFormatter()
319 loremipsum = (
320 "lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod".split(
321 " "
322 )
323 )
324
325 for format_name in formatter.supported_formats:
326 formatter.format_name = format_name
327 try:
328 formatted = next(formatter.format_output(zip(loremipsum), ["lorem"]))
329 except TypeError:
330 assert False, "{0} doesn't return iterable".format(format_name)
331
332
333 @pytest.mark.parametrize(
334 "extra_kwargs",
335 [
336 {},
337 {"style": "default"},
338 {"style": "colorful"},
339 ],
340 )
341 def test_all_text_type(extra_kwargs):
342 """Test the TabularOutputFormatter class."""
343 data = [[1, "", None, Decimal(2)]]
344 headers = ["col1", "col2", "col3", "col4"]
345 output_formatter = TabularOutputFormatter()
346 for format_name in output_formatter.supported_formats:
347 for row in output_formatter.format_output(
348 iter(data), headers, format_name=format_name, **extra_kwargs
349 ):
350 assert isinstance(row, text_type), "not unicode for {}".format(format_name)