Debian Codegraph @

tests/unit_tests/test_layout.py

raw
1 from __future__ import annotations
2
3 import io
4 from typing import Callable
5
6 import pytest
7 from wcwidth import wcswidth
8
9 from harlequin.layout import (
10 LayoutOptions,
11 default_max_rows,
12 get_layout,
13 layout_names,
14 )
15 from harlequin.query import ResultSet, RowLimit
16
17 ResultSetFactory = Callable[..., ResultSet]
18
19
20 def render(
21 result: ResultSet, name: str = "table", options: LayoutOptions | None = None
22 ) -> str:
23 out = io.StringIO()
24 get_layout(name, options).write(result, out)
25 return out.getvalue()
26
27
28 class TestGetLayout:
29 def test_every_name_resolves(self) -> None:
30 assert layout_names() == ["table", "markdown", "md", "vertical"]
31 for name in layout_names():
32 assert get_layout(name) is not None
33
34 def test_md_is_markdown(self, result_set: ResultSetFactory) -> None:
35 result = result_set("select 1 as a")
36 assert render(result, "md") == render(result, "markdown")
37
38 def test_an_unknown_name_names_the_known_ones(self) -> None:
39 with pytest.raises(ValueError, match="table, markdown, md, vertical"):
40 get_layout("yaml")
41
42
43 class TestTableLayout:
44 def test_aligned_columns(self, result_set: ResultSetFactory) -> None:
45 result = result_set(
46 "select * from (values (1, 'alice'), (22, 'bob')) t(id, name)"
47 )
48 assert render(result) == (
49 " id | name\n----+-------\n 1 | alice\n 22 | bob\n(2 rows)\n"
50 )
51
52 def test_tuples_only_drops_the_chrome(self, result_set: ResultSetFactory) -> None:
53 result = result_set("select 1 as a, 'x' as b")
54 assert render(result, options=LayoutOptions(header=False, footer=False)) == (
55 " 1 | x\n"
56 )
57
58 def test_unaligned_is_pipe_delimited(self, result_set: ResultSetFactory) -> None:
59 result = result_set("select 1 as a, 'x' as b")
60 assert render(result, options=LayoutOptions(aligned=False)) == (
61 "a|b\n1|x\n(1 row)\n"
62 )
63
64 def test_the_scalar_idiom(self, result_set: ResultSetFactory) -> None:
65 """`hsql -tAc "select count(*)"` is the first thing a scripting
66 audience will try, and it has to return a bare number."""
67 result = result_set("select count(*) from range(41)")
68 assert (
69 render(
70 result,
71 options=LayoutOptions(header=False, footer=False, aligned=False),
72 )
73 == "41\n"
74 )
75
76 def test_zero_rows_keeps_its_header(self, result_set: ResultSetFactory) -> None:
77 """Zero rows is not an error, and must not read like one."""
78 result = result_set("select 1 as a, 'x' as b where false")
79 assert render(result) == " a | b\n---+---\n(0 rows)\n"
80
81 def test_the_last_column_is_not_padded(self, result_set: ResultSetFactory) -> None:
82 """A value may legitimately end in a space, so the line cannot be
83 rstripped -- the padding just isn't written."""
84 result = result_set("select * from (values ('trailing '), ('x')) t(padded)")
85 assert render(result, options=LayoutOptions(footer=False)) == (
86 " padded\n------------\n trailing \n x\n"
87 )
88
89
90 class TestMultiLineValues:
91 """A value holding a newline, laid out the way psql lays one out.
92
93 Asserted against psql 16's own output for the same data, byte for byte
94 inside the table: the cell spans physical lines, `+` in the separator marks
95 each one that continues, and the columns beside it go blank. Flattening it
96 instead would be the layout deciding what a value is.
97 """
98
99 QUERY = (
100 "select * from (values "
101 r"(1, 'ok', E'select\n o.id,\n o.total\nfrom orders o'), "
102 "(2, 'err', 'select 1')"
103 ") t(n, status, sql)"
104 )
105
106 def test_the_table_wraps_the_cell(self, result_set: ResultSetFactory) -> None:
107 result = result_set(self.QUERY)
108 assert render(result) == (
109 " n | status | sql\n"
110 "---+--------+---------------\n"
111 " 1 | ok | select +\n"
112 " | | o.id, +\n"
113 " | | o.total +\n"
114 " | | from orders o\n"
115 " 2 | err | select 1\n"
116 "(2 rows)\n"
117 )
118
119 def test_the_column_is_as_wide_as_its_widest_line(
120 self, result_set: ResultSetFactory
121 ) -> None:
122 """Not as wide as the whole value, which would pad every other row to
123 the length of a query nobody can read on one line anyway."""
124 result = result_set(self.QUERY)
125 assert render(result).splitlines()[1] == "---+--------+---------------"
126
127 def test_vertical_wraps_the_field(self, result_set: ResultSetFactory) -> None:
128 result = result_set(self.QUERY)
129 assert render(result, "vertical") == (
130 "-[ RECORD 1 ]---------\n"
131 "n | 1\n"
132 "status | ok\n"
133 "sql | select +\n"
134 " | o.id, +\n"
135 " | o.total +\n"
136 " | from orders o\n"
137 "-[ RECORD 2 ]---------\n"
138 "n | 2\n"
139 "status | err\n"
140 "sql | select 1\n"
141 "(2 rows)\n"
142 )
143
144 def test_unaligned_writes_the_value_as_it_stands(
145 self, result_set: ResultSetFactory
146 ) -> None:
147 """psql's answer too: `-tA` is a delimited stream, and a caller whose
148 data holds newlines wants a format that frames them."""
149 result = result_set(self.QUERY)
150 assert render(
151 result, options=LayoutOptions(header=False, footer=False, aligned=False)
152 ) == ("1|ok|select\n o.id,\n o.total\nfrom orders o\n2|err|select 1\n")
153
154 def test_markdown_keeps_the_row_on_one_line(
155 self, result_set: ResultSetFactory
156 ) -> None:
157 """A newline would end the row, so the one layout that escapes what it
158 prints escapes this too."""
159 rendered = render(
160 result_set(self.QUERY), "markdown", LayoutOptions(footer=False)
161 )
162 assert "<br>" in rendered
163 assert len(rendered.splitlines()) == 4
164
165 def test_a_value_that_ends_in_a_newline(self, result_set: ResultSetFactory) -> None:
166 """Its last line is empty, and the line before it still says it
167 continues."""
168 result = result_set(r"select E'a\nb\n' as v, 1 as n")
169 assert render(result, options=LayoutOptions(footer=False)) == (
170 " v | n\n---+---\n a+| 1\n b+| \n | \n"
171 )
172
173
174 class TestMarkdownLayout:
175 def test_pipe_table(self, result_set: ResultSetFactory) -> None:
176 result = result_set(
177 "select * from (values (1, 'alice'), (22, 'bob')) t(id, name)"
178 )
179 assert render(result, "markdown") == (
180 "| id | name |\n"
181 "| --- | ----- |\n"
182 "| 1 | alice |\n"
183 "| 22 | bob |\n"
184 "\n"
185 "_(2 rows)_\n"
186 )
187
188 def test_a_cell_cannot_escape_its_column(
189 self, result_set: ResultSetFactory
190 ) -> None:
191 """A `|` or a newline in a value doesn't make a table hard to read; it
192 makes it a different table."""
193 result = result_set("select 'a|b' as piped, 'one\ntwo' as multiline")
194 rendered = render(result, "markdown", LayoutOptions(footer=False))
195 assert "a\\|b" in rendered
196 assert "one<br>two" in rendered
197 assert len(rendered.splitlines()) == 3
198
199 def test_a_null_string_cannot_escape_its_column(
200 self, result_set: ResultSetFactory
201 ) -> None:
202 """The null string is printed like any other value, so a `|` or a
203 newline in it breaks the table the same way."""
204 result = result_set("select null as x, 1 as y")
205 rendered = render(
206 result,
207 "markdown",
208 LayoutOptions(footer=False, null_string="a|b\nc"),
209 )
210 assert "a\\|b<br>c" in rendered
211 assert len(rendered.splitlines()) == 3
212
213 def test_columns_are_at_least_three_wide(
214 self, result_set: ResultSetFactory
215 ) -> None:
216 """`---` is the shortest delimiter row GFM accepts."""
217 result = result_set("select 1 as a")
218 assert render(result, "markdown", LayoutOptions(footer=False)) == (
219 "| a |\n| --- |\n| 1 |\n"
220 )
221
222
223 class TestVerticalLayout:
224 def test_one_column_per_line(self, result_set: ResultSetFactory) -> None:
225 result = result_set(
226 "select * from (values (1, 'alice'), (22, 'bob')) t(id, name)"
227 )
228 assert render(result, "vertical") == (
229 "-[ RECORD 1 ]-\n"
230 "id | 1\n"
231 "name | alice\n"
232 "-[ RECORD 2 ]-\n"
233 "id | 22\n"
234 "name | bob\n"
235 "(2 rows)\n"
236 )
237
238 def test_the_record_rule_is_one_width(self, result_set: ResultSetFactory) -> None:
239 """A rule that changed length from record to record would read as
240 raggedness rather than as structure."""
241 result = result_set(
242 "select * from (values ('x'), ('a much longer value')) t(v)"
243 )
244 rules = [
245 line for line in render(result, "vertical").splitlines() if "RECORD" in line
246 ]
247 assert len(rules) == 2
248 assert len({len(rule) for rule in rules}) == 1
249
250 def test_without_a_header_records_are_blank_line_separated(
251 self, result_set: ResultSetFactory
252 ) -> None:
253 result = result_set("select * from (values (1), (2)) t(a)")
254 assert render(
255 result, "vertical", LayoutOptions(header=False, footer=False)
256 ) == ("a | 1\n\na | 2\n")
257
258
259 class TestWidth:
260 """Columns are measured in terminal cells, not characters.
261
262 A CJK ideograph is one character and two cells; an emoji is one and two; a
263 combining mark is one and none. Measured with `len()`, a column holding any
264 of them lines up for nobody whose data isn't Latin.
265 """
266
267 @staticmethod
268 def separator_columns(rendered: str) -> set[tuple[int, ...]]:
269 """Where each line's separators fall, measured in terminal cells.
270
271 Deliberately not the character index -- that the two differ is the
272 whole point. Measured here with wcswidth directly, rather than through
273 the helper under test.
274 """
275 return {
276 tuple(wcswidth(line[:i]) for i, c in enumerate(line) if c in "|+")
277 for line in rendered.splitlines()
278 }
279
280 @pytest.mark.parametrize(
281 "value",
282 # the combining mark stays an escape: composed, it is invisible here.
283 ["東京", "🎉", "cafe\u0301", "full"],
284 ids=["cjk", "emoji", "combining mark", "fullwidth latin"],
285 )
286 def test_a_column_lines_up_whatever_it_holds(
287 self, result_set: ResultSetFactory, value: str
288 ) -> None:
289 result = result_set(
290 f"select * from (values ('{value}', 1), ('ascii', 22)) t(v, n)"
291 )
292 rendered = render(result, options=LayoutOptions(footer=False))
293 assert len(self.separator_columns(rendered)) == 1
294
295 def test_a_wide_glyph_is_two_cells(self, result_set: ResultSetFactory) -> None:
296 """東京 is 2 characters and 4 cells, so it is exactly as wide as `wxyz`
297 and takes no padding beside it -- where `len()` would have added two
298 spaces and pushed the next column out.
299
300 Two columns, because the last one is never padded: a single-column
301 result would pass this either way.
302 """
303 result = result_set(
304 "select * from (values ('東京', 'x'), ('wxyz', 'y')) t(v, w)"
305 )
306 assert render(result, options=LayoutOptions(header=False, footer=False)) == (
307 " 東京 | x\n wxyz | y\n"
308 )
309
310 def test_a_combining_mark_is_no_cells(self, result_set: ResultSetFactory) -> None:
311 """`cafe` followed by U+0301 is 5 characters and 4 cells."""
312 result = result_set(
313 "select * from (values ('cafe\u0301', 'x'), ('wxyz', 'y')) t(v, w)"
314 )
315 assert render(result, options=LayoutOptions(header=False, footer=False)) == (
316 " cafe\u0301 | x\n wxyz | y\n"
317 )
318
319 def test_a_control_character_does_not_crash_the_measurement(
320 self, result_set: ResultSetFactory
321 ) -> None:
322 """wcswidth reports -1 for a string it cannot measure. That row is
323 misaligned by the control character whatever we do; it must still
324 render, and every other row must still line up."""
325 result = result_set("select * from (values ('a\bb'), ('wxyz')) t(v)")
326 rendered = render(result, options=LayoutOptions(footer=False))
327 assert "a\bb" in rendered
328 assert rendered.splitlines()[-1] == " wxyz"
329
330
331 class TestNulls:
332 def test_a_null_is_not_an_empty_string(self, result_set: ResultSetFactory) -> None:
333 result = result_set("select null as a, '' as b")
334 assert render(result, options=LayoutOptions(footer=False)) == (
335 " a | b\n------+---\n NULL | \n"
336 )
337
338 @pytest.mark.parametrize("name", ["table", "markdown", "vertical"])
339 def test_the_null_string_is_the_callers_choice(
340 self, result_set: ResultSetFactory, name: str
341 ) -> None:
342 result = result_set("select null as a")
343 rendered = render(result, name, LayoutOptions(null_string="∅", footer=False))
344 assert "∅" in rendered
345 assert "NULL" not in rendered
346
347 def test_an_empty_null_string_is_honored(
348 self, result_set: ResultSetFactory
349 ) -> None:
350 result = result_set("select null as a, 1 as b")
351 assert render(
352 result, options=LayoutOptions(null_string="", header=False, footer=False)
353 ) == (" | 1\n")
354
355 def test_the_literal_string_null_is_not_a_null(
356 self, result_set: ResultSetFactory
357 ) -> None:
358 result = result_set("select 'NULL' as a, null as b")
359 assert render(
360 result, options=LayoutOptions(null_string="~", header=False, footer=False)
361 ) == (" NULL | ~\n")
362
363
364 class TestFooter:
365 def test_one_row_is_singular(self, result_set: ResultSetFactory) -> None:
366 assert render(result_set("select 1")).endswith("(1 row)\n")
367
368 def test_a_truncated_result_never_claims_a_total(
369 self, result_set: ResultSetFactory
370 ) -> None:
371 """Not fetching the rest is the point of a hard limit, so the total is
372 unknowable and the footer must not invent one."""
373 limit = RowLimit(max_rows=2, detect_overflow=True)
374 result = result_set("select * from range(10)", limit=limit)
375 assert render(result).endswith("(2 of >2 rows)\n")
376
377 def test_one_truncated_row_is_plural(self, result_set: ResultSetFactory) -> None:
378 """The noun agrees with the total, not with what was kept.
379
380 A truncated result has a row the limit+1 fetch found and did not keep,
381 so the total is at least two whatever the count says.
382 """
383 limit = RowLimit(max_rows=1, detect_overflow=True)
384 result = result_set("select * from range(10)", limit=limit)
385 assert render(result).endswith("(1 of >1 rows)\n")
386
387 @pytest.mark.parametrize("name", ["table", "markdown", "vertical"])
388 def test_every_layout_reports_truncation(
389 self, result_set: ResultSetFactory, name: str
390 ) -> None:
391 limit = RowLimit(max_rows=2, detect_overflow=True)
392 result = result_set("select * from range(10)", limit=limit)
393 assert "(2 of >2 rows)" in render(result, name)
394
395 def test_a_capped_result_counts_every_row_it_holds(
396 self, result_set: ResultSetFactory
397 ) -> None:
398 """The rows were fetched, so this total is exact, unlike a truncated
399 one -- and the footer is the only thing that says they exist."""
400 result = result_set("select * from range(10)")
401 assert render(result, options=LayoutOptions(max_rows=3)).endswith(
402 "(3 of 10 rows)\n"
403 )
404
405 def test_a_capped_and_truncated_result_reports_both(
406 self, result_set: ResultSetFactory
407 ) -> None:
408 limit = RowLimit(max_rows=5, detect_overflow=True)
409 result = result_set("select * from range(10)", limit=limit)
410 assert render(result, options=LayoutOptions(max_rows=3)).endswith(
411 "(3 of >5 rows)\n"
412 )
413
414
415 class TestRowCap:
416 def test_each_layout_declares_its_own_default(self) -> None:
417 assert default_max_rows("table") == 40
418 assert default_max_rows("markdown") == default_max_rows("md") == 40
419 assert default_max_rows("vertical") == 10
420
421 def test_an_unknown_name_has_no_default(self) -> None:
422 with pytest.raises(ValueError):
423 default_max_rows("yaml")
424
425 def test_nothing_is_capped_by_default(self, result_set: ResultSetFactory) -> None:
426 """The layouts print what they are given; the cap is the caller's."""
427 result = result_set("select * from range(100)")
428 assert render(result).count("\n") == 103 # header, rule, 100 rows, footer
429
430 @pytest.mark.parametrize("name", ["table", "markdown", "vertical"])
431 def test_every_layout_honors_the_cap(
432 self, result_set: ResultSetFactory, name: str
433 ) -> None:
434 result = result_set("select * from range(100)")
435 rendered = render(result, name, options=LayoutOptions(max_rows=2))
436 assert "99" not in rendered
437 assert "(2 of 100 rows)" in rendered
438
439 def test_the_cap_sets_the_column_widths(self, result_set: ResultSetFactory) -> None:
440 """A value in a row nobody sees should not pad the rows they do."""
441 result = result_set(
442 "select 'a' as v union all select 'a considerably wider value' order by v"
443 )
444 rendered = render(
445 result, options=LayoutOptions(max_rows=1, footer=False, header=False)
446 )
447 assert rendered == " a\n"
448
449
450 class TestColor:
451 def test_off_by_default(self, result_set: ResultSetFactory) -> None:
452 assert "\x1b" not in render(result_set("select null as a"))
453
454 def test_styles_the_header_and_nulls_only(
455 self, result_set: ResultSetFactory
456 ) -> None:
457 result = result_set("select null as a, 'x' as b")
458 rendered = render(result, options=LayoutOptions(color=True, footer=False))
459 assert "\x1b[1ma\x1b[0m" in rendered
460 assert "\x1b[2mNULL\x1b[0m" in rendered
461 assert "\x1b[" not in rendered.split("| ")[-1]
462
463 @pytest.mark.parametrize("name", ["table", "markdown", "vertical"])
464 def test_color_does_not_move_a_column(
465 self, result_set: ResultSetFactory, name: str
466 ) -> None:
467 """Styling is applied inside a cell's padding, so stripping the escapes
468 gets the uncolored layout back exactly."""
469 result = result_set(
470 "select * from (values (1, null), (22, 'a value')) t(id, note)"
471 )
472 colored = render(result, name, LayoutOptions(color=True))
473 for escape in ("\x1b[1m", "\x1b[2m", "\x1b[0m"):
474 colored = colored.replace(escape, "")
475 assert colored == render(result, name)
476
477
478 class TestLocale:
479 def test_numbers_are_not_grouped(self, result_set: ResultSetFactory) -> None:
480 """The data table's cell formatter renders numbers with `f"{n:n}"`,
481 which is locale-aware. A layout that reached for it would print
482 `1,234,567` on one machine and `1.234.567` on another."""
483 result = result_set("select 1234567 as n, 1234567.89::double as d")
484 rendered = render(result, options=LayoutOptions(header=False, footer=False))
485 assert rendered == " 1234567 | 1234567.89\n"