Debian Codegraph @

tests/unit_tests/test_export.py

raw
1 from __future__ import annotations
2
3 import datetime as dt
4 import io
5 import sys
6 from pathlib import Path
7 from typing import Any
8
9 import pyarrow as pa
10 import pyarrow.feather as pf
11 import pyarrow.orc as po
12 import pyarrow.parquet as pq
13 import pytest
14 from textual_fastdatatable.backend import create_backend
15
16 from harlequin.copy_formats import HARLEQUIN_COPY_FORMATS
17 from harlequin.exception import HarlequinCopyError
18 from harlequin.export import (
19 _deduplicate_column_names,
20 file_format_names,
21 file_suffix,
22 names_a_directory,
23 write_file,
24 write_stream,
25 )
26 from harlequin.layout import layout_suffix
27 from harlequin.options import HarlequinCopyFormat, SelectOption
28
29 TEXT_FORMATS = ["csv", "tsv", "json", "jsonl", "ndjson"]
30 BINARY_FORMATS = ["parquet", "orc", "feather", "arrow"]
31 GZIP_MAGIC = b"\x1f\x8b"
32 FEATHER_V1_MAGIC = b"FEA1"
33 FEATHER_V2_MAGIC = b"ARROW1"
34
35 FEATHER_DIALOG = {
36 option.name: getattr(option, "default", None)
37 for fmt in HARLEQUIN_COPY_FORMATS
38 if fmt.name == "feather"
39 for option in fmt.options
40 }
41 """Every Feather option the copy dialog declares, at the value an untouched
42 widget holds. The dialog sends all of them, touched or not."""
43
44 NEEDS_ORC_READER = pytest.mark.skipif(
45 sys.platform == "win32",
46 reason=(
47 "pyarrow's ORC reader wants the IANA time zone database, which the "
48 "Windows runners do not have. Writing ORC there is fine, and the tests "
49 "that only write are not skipped."
50 ),
51 )
52
53
54 @pytest.fixture
55 def data() -> pa.Table:
56 return pa.table({"a": [1, 2], "b": ["x,y", None]})
57
58
59 @pytest.fixture
60 def dated() -> pa.Table:
61 """A date and a timestamp, so the format options have something to format."""
62 return pa.table(
63 {
64 "d": pa.array([dt.date(2024, 3, 1), None], type=pa.date32()),
65 "ts": pa.array(
66 [dt.datetime(2024, 3, 1, 12, 30, 5), None], type=pa.timestamp("us")
67 ),
68 }
69 )
70
71
72 def to_bytes(data: pa.Table, format_name: str, options: dict | None = None) -> bytes:
73 out = io.BytesIO()
74 write_stream(data, out, format_name, options)
75 return out.getvalue()
76
77
78 class TestFormatNames:
79 def test_every_name_writes_something(self, data: pa.Table, tmp_path: Path) -> None:
80 for name in file_format_names():
81 path = tmp_path / f"out.{name}"
82 write_file(data, path, name)
83 assert path.stat().st_size > 0
84
85 def test_an_unknown_format_names_the_known_ones(self, data: pa.Table) -> None:
86 with pytest.raises(HarlequinCopyError, match="csv, tsv, json"):
87 write_file(data, Path("out.yaml"), "yaml")
88
89
90 class TestVariants:
91 """`tsv` and `jsonl` are the csv and json writers under other defaults, not
92 new writers -- so what they get right is exactly what csv and json got
93 right, quoting and type rendering included."""
94
95 def test_tsv_is_csv_with_a_tab(self, data: pa.Table) -> None:
96 assert to_bytes(data, "tsv") == to_bytes(data, "csv", {"sep": "\t"})
97
98 def test_json_is_an_array_of_row_objects(self, data: pa.Table) -> None:
99 assert to_bytes(data, "json") == (
100 b'[\n\t{"a":1,"b":"x,y"},\n\t{"a":2,"b":null}\n]\n'
101 )
102
103 def test_jsonl_is_one_object_per_line(self, data: pa.Table) -> None:
104 assert to_bytes(data, "jsonl") == b'{"a":1,"b":"x,y"}\n{"a":2,"b":null}\n'
105
106 def test_ndjson_is_jsonl(self, data: pa.Table) -> None:
107 assert to_bytes(data, "ndjson") == to_bytes(data, "jsonl")
108
109 def test_arrow_is_feather(self, data: pa.Table) -> None:
110 assert to_bytes(data, "arrow") == to_bytes(data, "feather")
111
112
113 class TestOptionPrecedence:
114 def test_an_explicit_option_beats_the_formats_default(self, data: pa.Table) -> None:
115 """The copy dialog passes every option of a format, set or not, and its
116 array flag defaults off -- so `json` must not force an array on it."""
117 assert to_bytes(data, "json", {"array": False}) == to_bytes(data, "jsonl")
118 assert to_bytes(data, "jsonl", {"array": True}) == to_bytes(data, "json")
119
120 def test_false_is_a_value_and_empty_is_not(self, data: pa.Table) -> None:
121 """`header=False` has to reach the writer; a text option the user never
122 typed into arrives as "" and must not."""
123 assert to_bytes(data, "csv", {"header": False}) == b'1,"x,y"\n2,\n'
124 assert to_bytes(data, "csv", {"sep": ""}) == to_bytes(data, "csv")
125
126
127 class TestCsvOptions:
128 """Every option the csv format declares, at a non-default value.
129
130 csv and tsv share a writer, so this covers both.
131 """
132
133 def test_header(self, data: pa.Table) -> None:
134 assert to_bytes(data, "csv").startswith(b"a,b\n")
135 assert to_bytes(data, "csv", {"header": False}) == b'1,"x,y"\n2,\n'
136
137 def test_sep(self, data: pa.Table) -> None:
138 assert to_bytes(data, "csv", {"sep": "|"}) == b"a|b\n1|x,y\n2|\n"
139
140 def test_quoting(self, data: pa.Table) -> None:
141 assert to_bytes(data, "csv", {"quoting": True}).startswith(b'"a","b"\n')
142 assert to_bytes(data, "csv", {"quoting": False}) == to_bytes(data, "csv")
143
144 def test_quotechar(self, data: pa.Table) -> None:
145 assert to_bytes(data, "csv", {"quotechar": "'"}) == b"a,b\n1,'x,y'\n2,\n"
146
147 def test_escapechar(self, data: pa.Table) -> None:
148 quoted = pa.table({"a": ['say "hi"']})
149 assert to_bytes(quoted, "csv", {"escapechar": "\\"}) == b'a\n"say \\"hi\\""\n'
150
151 def test_na_rep(self, data: pa.Table) -> None:
152 assert to_bytes(data, "csv", {"na_rep": "\\N"}) == b'a,b\n1,"x,y"\n2,\\N\n'
153
154 def test_date_format(self, dated: pa.Table) -> None:
155 assert to_bytes(dated, "csv", {"date_format": "%m/%d/%Y"}).startswith(
156 b"d,ts\n03/01/2024,"
157 )
158
159 def test_timestamp_format(self, dated: pa.Table) -> None:
160 assert b",12:30\n" in to_bytes(dated, "csv", {"timestamp_format": "%H:%M"})
161
162 def test_compression(self, data: pa.Table) -> None:
163 assert to_bytes(data, "csv", {"compression": "gzip"}).startswith(GZIP_MAGIC)
164 assert to_bytes(data, "csv", {"compression": "none"}) == to_bytes(data, "csv")
165
166 def test_encoding(self, data: pa.Table) -> None:
167 """Only UTF8 is supported, but it must still be accepted."""
168 assert to_bytes(data, "csv", {"encoding": "UTF8"}) == to_bytes(data, "csv")
169
170
171 class TestJsonOptions:
172 """Every option the json format declares. `jsonl` shares this writer."""
173
174 def test_array(self, data: pa.Table) -> None:
175 assert to_bytes(data, "json", {"array": True}).startswith(b"[\n")
176 assert not to_bytes(data, "json", {"array": False}).startswith(b"[\n")
177
178 def test_date_format(self, dated: pa.Table) -> None:
179 assert b'"d":"03/01/2024"' in to_bytes(
180 dated, "json", {"date_format": "%m/%d/%Y"}
181 )
182
183 def test_timestamp_format(self, dated: pa.Table) -> None:
184 """This option was read under the wrong key and silently did nothing."""
185 assert b'"ts":"12:30"' in to_bytes(dated, "json", {"timestamp_format": "%H:%M"})
186
187 def test_compression(self, data: pa.Table) -> None:
188 assert to_bytes(data, "json", {"compression": "gzip"}).startswith(GZIP_MAGIC)
189 assert to_bytes(data, "json", {"compression": "uncompressed"}) == to_bytes(
190 data, "json"
191 )
192
193 @pytest.mark.parametrize(
194 ("option_name", "value", "expected"),
195 [
196 ("date_format", "'%Y'", b'"d":"\'2024\'"'),
197 ("timestamp_format", "'%H:%M'", b'"ts":"\'12:30\'"'),
198 ],
199 ids=["date_format", "timestamp_format"],
200 )
201 def test_a_quote_in_a_format_string_is_part_of_the_format(
202 self, dated: pa.Table, option_name: str, value: str, expected: bytes
203 ) -> None:
204 """These two are free text the copy dialog sends verbatim, and this is
205 the writer that reaches duckdb as SQL text."""
206 assert expected in to_bytes(dated, "json", {option_name: value})
207
208
209 class TestParquetOptions:
210 @pytest.mark.parametrize(
211 "codec", ["snappy", "gzip", "zstd", "uncompressed"], ids=lambda c: str(c)
212 )
213 def test_compression(self, data: pa.Table, tmp_path: Path, codec: str) -> None:
214 path = tmp_path / "out.parquet"
215 write_file(data, path, "parquet", {"compression": codec})
216 written = pq.ParquetFile(str(path))
217 assert written.metadata.row_group(0).column(0).compression == codec.upper()
218 assert written.read().to_pydict() == data.to_pydict()
219
220
221 class TestOrcOptions:
222 @NEEDS_ORC_READER
223 @pytest.mark.parametrize("codec", ["UNCOMPRESSED", "SNAPPY", "ZLIB", "LZ4", "zstd"])
224 def test_compression(self, data: pa.Table, tmp_path: Path, codec: str) -> None:
225 path = tmp_path / "out.orc"
226 write_file(data, path, "orc", {"compression": codec})
227 assert po.read_table(str(path)).to_pydict() == data.to_pydict()
228
229 def test_a_number_that_is_not_one_is_an_error(
230 self, data: pa.Table, tmp_path: Path
231 ) -> None:
232 """This one never reaches pyarrow, so it runs everywhere."""
233 with pytest.raises(HarlequinCopyError):
234 write_file(data, tmp_path / "out.orc", "orc", {"batch_size": "lots"})
235
236 @NEEDS_ORC_READER
237 def test_a_rejected_bloom_filter_column_is_an_error(
238 self, data: pa.Table, tmp_path: Path
239 ) -> None:
240 """pyarrow refuses every column name here, and does it with a
241 ValueError -- which the export dialog does not catch, so before this
242 was wrapped it took the app down rather than opening an error modal.
243
244 Skipped where ORC needs a time zone database it doesn't have: the error
245 raised there is that one, not the one under test, and the assertion
246 would pass for the wrong reason.
247 """
248 with pytest.raises(HarlequinCopyError):
249 write_file(data, tmp_path / "out.orc", "orc", {"bloom_filter_columns": "a"})
250
251
252 class TestFeatherOptions:
253 @pytest.mark.parametrize("codec", ["uncompressed", "lz4", "zstd"])
254 def test_compression(self, data: pa.Table, tmp_path: Path, codec: str) -> None:
255 path = tmp_path / "out.feather"
256 write_file(data, path, "feather", {"compression": codec})
257 assert pf.read_table(str(path)).to_pydict() == data.to_pydict()
258
259 def test_compression_level_and_chunksize(
260 self, data: pa.Table, tmp_path: Path
261 ) -> None:
262 path = tmp_path / "out.feather"
263 write_file(
264 data,
265 path,
266 "feather",
267 {"compression": "zstd", "compression_level": "3", "chunksize": "1"},
268 )
269 assert pf.read_table(str(path)).to_pydict() == data.to_pydict()
270
271 @pytest.mark.parametrize("version", ["1", "2"])
272 def test_version(self, data: pa.Table, tmp_path: Path, version: str) -> None:
273 path = tmp_path / "out.feather"
274 write_file(data, path, "feather", {"version": int(version)})
275 assert pf.read_table(str(path)).to_pydict() == data.to_pydict()
276
277 @pytest.mark.parametrize(
278 ("version", "magic"), [("1", FEATHER_V1_MAGIC), ("2", FEATHER_V2_MAGIC)]
279 )
280 def test_the_version_the_dialog_sends_is_the_version_written(
281 self, data: pa.Table, tmp_path: Path, version: str, magic: bytes
282 ) -> None:
283 """The dialog's Select holds its choices as text, and pyarrow writes the
284 legacy V1 format for any `version` that is not the integer 2."""
285 path = tmp_path / "out.feather"
286 write_file(data, path, "feather", {**FEATHER_DIALOG, "version": version})
287 assert path.read_bytes().startswith(magic)
288 assert pf.read_table(str(path)).to_pydict() == data.to_pydict()
289
290 @pytest.mark.parametrize("codec", ["lz4", "zstd"])
291 def test_the_compression_the_dialog_sends_changes_the_file(
292 self, data: pa.Table, tmp_path: Path, codec: str
293 ) -> None:
294 """Compression is a V2 feature, so a write that fell back to V1 drops it,
295 and drops it silently: pyarrow only refuses the keyword when it knows it
296 is writing V1."""
297 plain = tmp_path / "plain.feather"
298 compressed = tmp_path / f"{codec}.feather"
299 write_file(data, plain, "feather", FEATHER_DIALOG)
300 write_file(
301 data, compressed, "feather", {**FEATHER_DIALOG, "compression": codec}
302 )
303 assert compressed.read_bytes() != plain.read_bytes()
304 assert pf.read_table(str(compressed)).to_pydict() == data.to_pydict()
305
306 def test_a_number_that_is_not_one_is_an_error(
307 self, data: pa.Table, tmp_path: Path
308 ) -> None:
309 with pytest.raises(HarlequinCopyError):
310 write_file(
311 data, tmp_path / "out.feather", "feather", {"compression_level": "high"}
312 )
313
314
315 class TestDeclaredOptions:
316 """Whatever the copy dialog can send, the writer has to accept.
317
318 The dialog renders every option a format declares and passes all of them,
319 touched or not, so an option the writer has no name for is a silent no-op
320 -- which is exactly how the JSON timestamp format did nothing at all.
321 """
322
323 @pytest.mark.parametrize("fmt", HARLEQUIN_COPY_FORMATS, ids=lambda f: str(f.name))
324 def test_the_declared_defaults_are_accepted(
325 self, data: pa.Table, tmp_path: Path, fmt: HarlequinCopyFormat
326 ) -> None:
327 """This also covers the numeric options arriving as strings.
328
329 ORC and Feather declare theirs as text, so `"1024"` is what the dialog
330 sends and what the writer has to turn into an int. Passing the declared
331 defaults rather than invented values keeps this from failing on a
332 pyarrow that has an opinion about, say, block sizes being a multiple of
333 something.
334 """
335 # `default` is declared on the concrete option types, not the ABC.
336 defaults: dict[str, Any] = {
337 option.name: getattr(option, "default", None) for option in fmt.options
338 }
339 path = tmp_path / f"out.{fmt.name}"
340 write_file(data, path, fmt.name, defaults)
341 assert path.stat().st_size > 0
342
343 @pytest.mark.parametrize(
344 ("fmt", "option"),
345 [
346 (fmt, option)
347 for fmt in HARLEQUIN_COPY_FORMATS
348 for option in fmt.options
349 if isinstance(option, SelectOption)
350 ],
351 ids=lambda p: str(getattr(p, "name", p)),
352 )
353 def test_every_choice_a_select_offers_is_accepted(
354 self,
355 data: pa.Table,
356 tmp_path: Path,
357 fmt: HarlequinCopyFormat,
358 option: SelectOption,
359 ) -> None:
360 for choice in option.choices:
361 value = choice if isinstance(choice, str) else choice[1]
362 path = tmp_path / f"out-{value}.{fmt.name}"
363 write_file(data, path, fmt.name, {option.name: value})
364 assert path.stat().st_size > 0
365
366
367 class TestColumnNames:
368 def test_duplicate_names_are_made_unique(self) -> None:
369 """`select 1 as a, 2 as a` is legal SQL and a legal Arrow table. It is
370 not something duckdb will export, or that a csv header can say."""
371 data = pa.Table.from_arrays(
372 [pa.array([1]), pa.array([2]), pa.array([3])], names=["a", "a", "a"]
373 )
374 assert to_bytes(data, "csv") == b"a,a0,a01\n1,2,3\n"
375
376 @pytest.mark.parametrize(
377 "names",
378 [
379 ["a", "a"],
380 ["a", "a", "a"],
381 ["a", "a0", "a"],
382 ["b", "a", "a", "b"],
383 ["a_0", "a", "a"],
384 ],
385 ids=lambda n: ",".join(n),
386 )
387 def test_it_de_duplicates_exactly_as_the_backend_does(
388 self, names: list[str]
389 ) -> None:
390 """Two things de-duplicate, and they must not disagree.
391
392 The app exports `source_data`, which still holds the duplicates, so
393 `write_file()` resolves them. A headless caller exports rows that have
394 already been through `create_backend()`, which resolved them first. The
395 same query has to produce the same header either way.
396
397 Asserted against what the backend actually does rather than against a
398 copy of its algorithm, so this fails if upstream changes the scheme --
399 at which point Harlequin follows it, rather than forking.
400 """
401 table = pa.Table.from_arrays([pa.array([1]) for _ in names], names=names)
402 assert (
403 _deduplicate_column_names(table).column_names
404 == create_backend(table).data.column_names
405 )
406
407 def test_names_that_are_already_unique_are_left_alone(self, data: pa.Table) -> None:
408 assert to_bytes(data, "csv").startswith(b"a,b\n")
409
410
411 class TestEmptyResults:
412 """Zero rows is not an error: an empty file is how "the query matched
413 nothing" is told apart from "the query failed"."""
414
415 @pytest.fixture
416 def empty(self) -> pa.Table:
417 return pa.table({"a": pa.array([], type=pa.int64())})
418
419 def test_csv_keeps_its_header(self, empty: pa.Table) -> None:
420 assert to_bytes(empty, "csv") == b"a\n"
421
422 def test_jsonl_is_empty(self, empty: pa.Table) -> None:
423 assert to_bytes(empty, "jsonl") == b""
424
425 @pytest.mark.parametrize("format_name", TEXT_FORMATS + BINARY_FORMATS)
426 def test_no_format_raises(
427 self, empty: pa.Table, tmp_path: Path, format_name: str
428 ) -> None:
429 write_file(empty, tmp_path / "out", format_name)
430
431
432 class TestStream:
433 @pytest.mark.parametrize("format_name", TEXT_FORMATS + BINARY_FORMATS)
434 def test_a_stream_and_a_file_are_the_same_bytes(
435 self, data: pa.Table, tmp_path: Path, format_name: str
436 ) -> None:
437 """`hsql -o out.csv` and `hsql > out.csv` have to produce the same file,
438 and the temp-file copy is the one thing that could get that wrong."""
439 path = tmp_path / "out"
440 write_file(data, path, format_name)
441 assert to_bytes(data, format_name) == path.read_bytes()
442
443 @pytest.mark.parametrize("format_name", TEXT_FORMATS)
444 def test_newlines_are_not_translated(
445 self, data: pa.Table, format_name: str
446 ) -> None:
447 """duckdb writes \\n. The copy out is binary so that Python's text-mode
448 translation cannot turn it into \\r\\n on Windows."""
449 assert b"\r\n" not in to_bytes(data, format_name)
450
451
452 class TestDestinationPaths:
453 """What a `-o` value names, which both commands ask before writing."""
454
455 @pytest.mark.parametrize(
456 "destination", ["exports", "exports/", "~/exports", ".harlequin"]
457 )
458 def test_a_path_with_no_extension_is_a_directory(self, destination: str) -> None:
459 assert names_a_directory(destination)
460
461 @pytest.mark.parametrize("destination", ["out.csv", "exports/out.parquet"])
462 def test_a_path_with_an_extension_is_a_file(self, destination: str) -> None:
463 assert not names_a_directory(destination)
464
465 def test_an_existing_directory_is_one_whatever_it_is_called(
466 self, tmp_path: Path
467 ) -> None:
468 dotted = tmp_path / "exports.old"
469 dotted.mkdir()
470 assert names_a_directory(dotted)
471
472 def test_an_existing_file_is_one_whatever_it_is_called(
473 self, tmp_path: Path
474 ) -> None:
475 extensionless = tmp_path / "exports"
476 extensionless.write_text("")
477 assert not names_a_directory(extensionless)
478
479 def test_a_missing_parent_is_created(self, data: pa.Table, tmp_path: Path) -> None:
480 """A caller who names a folder to export into names one that may not
481 exist yet."""
482 path = tmp_path / "exports" / "nested" / "out.csv"
483 write_file(data, path, "csv")
484 assert path.is_file()
485
486 @pytest.mark.parametrize("format_name", TEXT_FORMATS + BINARY_FORMATS)
487 def test_a_quote_in_the_path_is_part_of_the_name(
488 self, data: pa.Table, tmp_path: Path, format_name: str
489 ) -> None:
490 """`Bob's exports` is a folder, and every writer can write into it.
491
492 Every format is here because the path is a value to all of them: what a
493 file may be called is not something two formats get to disagree about.
494 """
495 path = tmp_path / "Bob's exports" / f"out.{format_name}"
496 write_file(data, path, format_name)
497 assert path.stat().st_size > 0
498
499
500 class TestSuffixes:
501 @pytest.mark.parametrize("format_name", TEXT_FORMATS + BINARY_FORMATS)
502 def test_every_file_format_names_its_extension(self, format_name: str) -> None:
503 assert file_suffix(format_name).lstrip(".") == format_name
504
505 def test_a_layout_names_one_too(self) -> None:
506 assert layout_suffix("table") == ".txt"
507 assert layout_suffix("markdown") == ".md"
508
509 def test_an_unknown_layout_raises(self) -> None:
510 with pytest.raises(ValueError):
511 layout_suffix("csv")