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 TestMarkdownLayout:
91 def test_pipe_table(self, result_set: ResultSetFactory) -> None:
92 result = result_set(
93 "select * from (values (1, 'alice'), (22, 'bob')) t(id, name)"
94 )
95 assert render(result, "markdown") == (
96 "| id | name |\n"
97 "| --- | ----- |\n"
98 "| 1 | alice |\n"
99 "| 22 | bob |\n"
100 "\n"
101 "_(2 rows)_\n"
102 )
103
104 def test_a_cell_cannot_escape_its_column(
105 self, result_set: ResultSetFactory
106 ) -> None:
107 """A `|` or a newline in a value doesn't make a table hard to read; it
108 makes it a different table."""
109 result = result_set("select 'a|b' as piped, 'one\ntwo' as multiline")
110 rendered = render(result, "markdown", LayoutOptions(footer=False))
111 assert "a\\|b" in rendered
112 assert "one<br>two" in rendered
113 assert len(rendered.splitlines()) == 3
114
115 def test_a_null_string_cannot_escape_its_column(
116 self, result_set: ResultSetFactory
117 ) -> None:
118 """The null string is printed like any other value, so a `|` or a
119 newline in it breaks the table the same way."""
120 result = result_set("select null as x, 1 as y")
121 rendered = render(
122 result,
123 "markdown",
124 LayoutOptions(footer=False, null_string="a|b\nc"),
125 )
126 assert "a\\|b<br>c" in rendered
127 assert len(rendered.splitlines()) == 3
128
129 def test_columns_are_at_least_three_wide(
130 self, result_set: ResultSetFactory
131 ) -> None:
132 """`---` is the shortest delimiter row GFM accepts."""
133 result = result_set("select 1 as a")
134 assert render(result, "markdown", LayoutOptions(footer=False)) == (
135 "| a |\n| --- |\n| 1 |\n"
136 )
137
138
139 class TestVerticalLayout:
140 def test_one_column_per_line(self, result_set: ResultSetFactory) -> None:
141 result = result_set(
142 "select * from (values (1, 'alice'), (22, 'bob')) t(id, name)"
143 )
144 assert render(result, "vertical") == (
145 "-[ RECORD 1 ]-\n"
146 "id | 1\n"
147 "name | alice\n"
148 "-[ RECORD 2 ]-\n"
149 "id | 22\n"
150 "name | bob\n"
151 "(2 rows)\n"
152 )
153
154 def test_the_record_rule_is_one_width(self, result_set: ResultSetFactory) -> None:
155 """A rule that changed length from record to record would read as
156 raggedness rather than as structure."""
157 result = result_set(
158 "select * from (values ('x'), ('a much longer value')) t(v)"
159 )
160 rules = [
161 line for line in render(result, "vertical").splitlines() if "RECORD" in line
162 ]
163 assert len(rules) == 2
164 assert len({len(rule) for rule in rules}) == 1
165
166 def test_without_a_header_records_are_blank_line_separated(
167 self, result_set: ResultSetFactory
168 ) -> None:
169 result = result_set("select * from (values (1), (2)) t(a)")
170 assert render(
171 result, "vertical", LayoutOptions(header=False, footer=False)
172 ) == ("a | 1\n\na | 2\n")
173
174
175 class TestWidth:
176 """Columns are measured in terminal cells, not characters.
177
178 A CJK ideograph is one character and two cells; an emoji is one and two; a
179 combining mark is one and none. Measured with `len()`, a column holding any
180 of them lines up for nobody whose data isn't Latin.
181 """
182
183 @staticmethod
184 def separator_columns(rendered: str) -> set[tuple[int, ...]]:
185 """Where each line's separators fall, measured in terminal cells.
186
187 Deliberately not the character index -- that the two differ is the
188 whole point. Measured here with wcswidth directly, rather than through
189 the helper under test.
190 """
191 return {
192 tuple(wcswidth(line[:i]) for i, c in enumerate(line) if c in "|+")
193 for line in rendered.splitlines()
194 }
195
196 @pytest.mark.parametrize(
197 "value",
198 # the combining mark stays an escape: composed, it is invisible here.
199 ["東京", "🎉", "cafe\u0301", "full"],
200 ids=["cjk", "emoji", "combining mark", "fullwidth latin"],
201 )
202 def test_a_column_lines_up_whatever_it_holds(
203 self, result_set: ResultSetFactory, value: str
204 ) -> None:
205 result = result_set(
206 f"select * from (values ('{value}', 1), ('ascii', 22)) t(v, n)"
207 )
208 rendered = render(result, options=LayoutOptions(footer=False))
209 assert len(self.separator_columns(rendered)) == 1
210
211 def test_a_wide_glyph_is_two_cells(self, result_set: ResultSetFactory) -> None:
212 """東京 is 2 characters and 4 cells, so it is exactly as wide as `wxyz`
213 and takes no padding beside it -- where `len()` would have added two
214 spaces and pushed the next column out.
215
216 Two columns, because the last one is never padded: a single-column
217 result would pass this either way.
218 """
219 result = result_set(
220 "select * from (values ('東京', 'x'), ('wxyz', 'y')) t(v, w)"
221 )
222 assert render(result, options=LayoutOptions(header=False, footer=False)) == (
223 " 東京 | x\n wxyz | y\n"
224 )
225
226 def test_a_combining_mark_is_no_cells(self, result_set: ResultSetFactory) -> None:
227 """`cafe` followed by U+0301 is 5 characters and 4 cells."""
228 result = result_set(
229 "select * from (values ('cafe\u0301', 'x'), ('wxyz', 'y')) t(v, w)"
230 )
231 assert render(result, options=LayoutOptions(header=False, footer=False)) == (
232 " cafe\u0301 | x\n wxyz | y\n"
233 )
234
235 def test_a_control_character_does_not_crash_the_measurement(
236 self, result_set: ResultSetFactory
237 ) -> None:
238 """wcswidth reports -1 for a string it cannot measure. That row is
239 misaligned by the control character whatever we do; it must still
240 render, and every other row must still line up."""
241 result = result_set("select * from (values ('a\bb'), ('wxyz')) t(v)")
242 rendered = render(result, options=LayoutOptions(footer=False))
243 assert "a\bb" in rendered
244 assert rendered.splitlines()[-1] == " wxyz"
245
246
247 class TestNulls:
248 def test_a_null_is_not_an_empty_string(self, result_set: ResultSetFactory) -> None:
249 result = result_set("select null as a, '' as b")
250 assert render(result, options=LayoutOptions(footer=False)) == (
251 " a | b\n------+---\n NULL | \n"
252 )
253
254 @pytest.mark.parametrize("name", ["table", "markdown", "vertical"])
255 def test_the_null_string_is_the_callers_choice(
256 self, result_set: ResultSetFactory, name: str
257 ) -> None:
258 result = result_set("select null as a")
259 rendered = render(result, name, LayoutOptions(null_string="∅", footer=False))
260 assert "∅" in rendered
261 assert "NULL" not in rendered
262
263 def test_an_empty_null_string_is_honored(
264 self, result_set: ResultSetFactory
265 ) -> None:
266 result = result_set("select null as a, 1 as b")
267 assert render(
268 result, options=LayoutOptions(null_string="", header=False, footer=False)
269 ) == (" | 1\n")
270
271 def test_the_literal_string_null_is_not_a_null(
272 self, result_set: ResultSetFactory
273 ) -> None:
274 result = result_set("select 'NULL' as a, null as b")
275 assert render(
276 result, options=LayoutOptions(null_string="~", header=False, footer=False)
277 ) == (" NULL | ~\n")
278
279
280 class TestFooter:
281 def test_one_row_is_singular(self, result_set: ResultSetFactory) -> None:
282 assert render(result_set("select 1")).endswith("(1 row)\n")
283
284 def test_a_truncated_result_never_claims_a_total(
285 self, result_set: ResultSetFactory
286 ) -> None:
287 """Not fetching the rest is the point of a hard limit, so the total is
288 unknowable and the footer must not invent one."""
289 limit = RowLimit(max_rows=2, detect_overflow=True)
290 result = result_set("select * from range(10)", limit=limit)
291 assert render(result).endswith("(2 of >2 rows)\n")
292
293 def test_one_truncated_row_is_plural(self, result_set: ResultSetFactory) -> None:
294 """The noun agrees with the total, not with what was kept.
295
296 A truncated result has a row the limit+1 fetch found and did not keep,
297 so the total is at least two whatever the count says.
298 """
299 limit = RowLimit(max_rows=1, detect_overflow=True)
300 result = result_set("select * from range(10)", limit=limit)
301 assert render(result).endswith("(1 of >1 rows)\n")
302
303 @pytest.mark.parametrize("name", ["table", "markdown", "vertical"])
304 def test_every_layout_reports_truncation(
305 self, result_set: ResultSetFactory, name: str
306 ) -> None:
307 limit = RowLimit(max_rows=2, detect_overflow=True)
308 result = result_set("select * from range(10)", limit=limit)
309 assert "(2 of >2 rows)" in render(result, name)
310
311 def test_a_capped_result_counts_every_row_it_holds(
312 self, result_set: ResultSetFactory
313 ) -> None:
314 """The rows were fetched, so this total is exact, unlike a truncated
315 one -- and the footer is the only thing that says they exist."""
316 result = result_set("select * from range(10)")
317 assert render(result, options=LayoutOptions(max_rows=3)).endswith(
318 "(3 of 10 rows)\n"
319 )
320
321 def test_a_capped_and_truncated_result_reports_both(
322 self, result_set: ResultSetFactory
323 ) -> None:
324 limit = RowLimit(max_rows=5, detect_overflow=True)
325 result = result_set("select * from range(10)", limit=limit)
326 assert render(result, options=LayoutOptions(max_rows=3)).endswith(
327 "(3 of >5 rows)\n"
328 )
329
330
331 class TestRowCap:
332 def test_each_layout_declares_its_own_default(self) -> None:
333 assert default_max_rows("table") == 40
334 assert default_max_rows("markdown") == default_max_rows("md") == 40
335 assert default_max_rows("vertical") == 10
336
337 def test_an_unknown_name_has_no_default(self) -> None:
338 with pytest.raises(ValueError):
339 default_max_rows("yaml")
340
341 def test_nothing_is_capped_by_default(self, result_set: ResultSetFactory) -> None:
342 """The layouts print what they are given; the cap is the caller's."""
343 result = result_set("select * from range(100)")
344 assert render(result).count("\n") == 103 # header, rule, 100 rows, footer
345
346 @pytest.mark.parametrize("name", ["table", "markdown", "vertical"])
347 def test_every_layout_honors_the_cap(
348 self, result_set: ResultSetFactory, name: str
349 ) -> None:
350 result = result_set("select * from range(100)")
351 rendered = render(result, name, options=LayoutOptions(max_rows=2))
352 assert "99" not in rendered
353 assert "(2 of 100 rows)" in rendered
354
355 def test_the_cap_sets_the_column_widths(self, result_set: ResultSetFactory) -> None:
356 """A value in a row nobody sees should not pad the rows they do."""
357 result = result_set(
358 "select 'a' as v union all select 'a considerably wider value' order by v"
359 )
360 rendered = render(
361 result, options=LayoutOptions(max_rows=1, footer=False, header=False)
362 )
363 assert rendered == " a\n"
364
365
366 class TestColor:
367 def test_off_by_default(self, result_set: ResultSetFactory) -> None:
368 assert "\x1b" not in render(result_set("select null as a"))
369
370 def test_styles_the_header_and_nulls_only(
371 self, result_set: ResultSetFactory
372 ) -> None:
373 result = result_set("select null as a, 'x' as b")
374 rendered = render(result, options=LayoutOptions(color=True, footer=False))
375 assert "\x1b[1ma\x1b[0m" in rendered
376 assert "\x1b[2mNULL\x1b[0m" in rendered
377 assert "\x1b[" not in rendered.split("| ")[-1]
378
379 @pytest.mark.parametrize("name", ["table", "markdown", "vertical"])
380 def test_color_does_not_move_a_column(
381 self, result_set: ResultSetFactory, name: str
382 ) -> None:
383 """Styling is applied inside a cell's padding, so stripping the escapes
384 gets the uncolored layout back exactly."""
385 result = result_set(
386 "select * from (values (1, null), (22, 'a value')) t(id, note)"
387 )
388 colored = render(result, name, LayoutOptions(color=True))
389 for escape in ("\x1b[1m", "\x1b[2m", "\x1b[0m"):
390 colored = colored.replace(escape, "")
391 assert colored == render(result, name)
392
393
394 class TestLocale:
395 def test_numbers_are_not_grouped(self, result_set: ResultSetFactory) -> None:
396 """The data table's cell formatter renders numbers with `f"{n:n}"`,
397 which is locale-aware. A layout that reached for it would print
398 `1,234,567` on one machine and `1.234.567` on another."""
399 result = result_set("select 1234567 as n, 1234567.89::double as d")
400 rendered = render(result, options=LayoutOptions(header=False, footer=False))
401 assert rendered == " 1234567 | 1234567.89\n"