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