datapy 0.2.1__tar.gz → 0.2.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {datapy-0.2.1/datapy.egg-info → datapy-0.2.2}/PKG-INFO +2 -1
- {datapy-0.2.1 → datapy-0.2.2}/datapy/__init__.py +1 -1
- {datapy-0.2.1 → datapy-0.2.2}/datapy/_datafile.py +7 -0
- {datapy-0.2.1 → datapy-0.2.2}/datapy/_reader.py +30 -7
- {datapy-0.2.1 → datapy-0.2.2}/datapy/cli.py +69 -7
- {datapy-0.2.1 → datapy-0.2.2/datapy.egg-info}/PKG-INFO +2 -1
- {datapy-0.2.1 → datapy-0.2.2}/datapy.egg-info/requires.txt +1 -0
- {datapy-0.2.1 → datapy-0.2.2}/pyproject.toml +18 -1
- {datapy-0.2.1 → datapy-0.2.2}/tests/test_ci.py +16 -0
- {datapy-0.2.1 → datapy-0.2.2}/tests/test_cli.py +173 -9
- {datapy-0.2.1 → datapy-0.2.2}/tests/test_query.py +6 -0
- {datapy-0.2.1 → datapy-0.2.2}/tests/test_stream.py +11 -0
- {datapy-0.2.1 → datapy-0.2.2}/LICENSE.txt +0 -0
- {datapy-0.2.1 → datapy-0.2.2}/MANIFEST.in +0 -0
- {datapy-0.2.1 → datapy-0.2.2}/README.md +0 -0
- {datapy-0.2.1 → datapy-0.2.2}/datapy/__main__.py +0 -0
- {datapy-0.2.1 → datapy-0.2.2}/datapy/_errors.py +0 -0
- {datapy-0.2.1 → datapy-0.2.2}/datapy/_statement.py +0 -0
- {datapy-0.2.1 → datapy-0.2.2}/datapy.egg-info/SOURCES.txt +0 -0
- {datapy-0.2.1 → datapy-0.2.2}/datapy.egg-info/dependency_links.txt +0 -0
- {datapy-0.2.1 → datapy-0.2.2}/datapy.egg-info/entry_points.txt +0 -0
- {datapy-0.2.1 → datapy-0.2.2}/datapy.egg-info/top_level.txt +0 -0
- {datapy-0.2.1 → datapy-0.2.2}/setup.cfg +0 -0
- {datapy-0.2.1 → datapy-0.2.2}/tests/test_datafile.py +0 -0
- {datapy-0.2.1 → datapy-0.2.2}/tests/test_docs.py +0 -0
- {datapy-0.2.1 → datapy-0.2.2}/tests/test_entry_points.py +0 -0
- {datapy-0.2.1 → datapy-0.2.2}/tests/test_statement.py +0 -0
- {datapy-0.2.1 → datapy-0.2.2}/tests/test_style.py +0 -0
- {datapy-0.2.1 → datapy-0.2.2}/tests/test_values.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: datapy
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.2
|
|
4
4
|
Summary: An intuitive lightweight file based database and query tool.
|
|
5
5
|
Author-email: Corey McCarty <corey@mccarty.dev>
|
|
6
6
|
License-Expression: Apache-2.0
|
|
@@ -21,6 +21,7 @@ Description-Content-Type: text/markdown
|
|
|
21
21
|
License-File: LICENSE.txt
|
|
22
22
|
Provides-Extra: dev
|
|
23
23
|
Requires-Dist: pytest; extra == "dev"
|
|
24
|
+
Requires-Dist: pytest-cov; extra == "dev"
|
|
24
25
|
Requires-Dist: build; extra == "dev"
|
|
25
26
|
Requires-Dist: black<27,>=26; extra == "dev"
|
|
26
27
|
Dynamic: license-file
|
|
@@ -14,7 +14,7 @@ The command line entry point is `datapy.cli`, which uses only the names
|
|
|
14
14
|
exported here.
|
|
15
15
|
"""
|
|
16
16
|
|
|
17
|
-
__version__ = "0.2.
|
|
17
|
+
__version__ = "0.2.2"
|
|
18
18
|
|
|
19
19
|
from datapy._datafile import DataFile, Result, Stream, query, stream
|
|
20
20
|
from datapy._errors import DatapyError
|
|
@@ -68,6 +68,9 @@ class Stream:
|
|
|
68
68
|
- `streamed`: true when the file is being read as you iterate; false when
|
|
69
69
|
the statement needed the whole file to be loaded first (sorting,
|
|
70
70
|
grouping, counting and the like).
|
|
71
|
+
- `line_ending`: how lines end in the file, taken from its first line:
|
|
72
|
+
`"\\n"`, `"\\r\\n"` (Windows) or `"\\r"`. Write the rows out with
|
|
73
|
+
it to keep the file's own convention.
|
|
71
74
|
- `skipped`: with `skip_bad_rows`, how many rows have been left out so
|
|
72
75
|
far for having the wrong number of fields. Final once the last row has
|
|
73
76
|
been read.
|
|
@@ -84,6 +87,10 @@ class Stream:
|
|
|
84
87
|
def skipped(self) -> int:
|
|
85
88
|
return self._source.skipped
|
|
86
89
|
|
|
90
|
+
@property
|
|
91
|
+
def line_ending(self) -> str:
|
|
92
|
+
return self._source.line_ending
|
|
93
|
+
|
|
87
94
|
def __iter__(self) -> Stream:
|
|
88
95
|
return self
|
|
89
96
|
|
|
@@ -39,18 +39,37 @@ def _windows_1252(error: UnicodeError):
|
|
|
39
39
|
codecs.register_error("datapy-windows-1252", _windows_1252)
|
|
40
40
|
|
|
41
41
|
|
|
42
|
-
def
|
|
43
|
-
"""
|
|
42
|
+
def _first_line_ending(text: str) -> str:
|
|
43
|
+
"""The line ending that ends the first line of `text`; "\\n" if none does.
|
|
44
|
+
|
|
45
|
+
The first line is a header or a row of data, so a quoted line break
|
|
46
|
+
inside a field is very unlikely there.
|
|
47
|
+
"""
|
|
48
|
+
for index, character in enumerate(text):
|
|
49
|
+
if character == "\n":
|
|
50
|
+
return "\n"
|
|
51
|
+
if character == "\r":
|
|
52
|
+
return "\r\n" if text[index + 1 : index + 2] == "\n" else "\r"
|
|
53
|
+
return "\n"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def decoded(binary) -> tuple[io.TextIOWrapper, str]:
|
|
57
|
+
"""Wrap a binary stream as text, and say how its lines end.
|
|
44
58
|
|
|
45
59
|
UTF-8, with or without a byte-order mark, is the expected encoding. Bytes
|
|
46
60
|
that are not valid UTF-8 are read as Windows-1252 rather than refused, and
|
|
47
61
|
a UTF-16 byte-order mark (Excel's "Unicode Text") switches to UTF-16.
|
|
62
|
+
|
|
63
|
+
Both answers come from the bytes already waiting in the stream's buffer,
|
|
64
|
+
so nothing extra is read. The line ending is that of the first line.
|
|
48
65
|
"""
|
|
49
|
-
|
|
50
|
-
encoding = "utf-16" if
|
|
51
|
-
|
|
66
|
+
start = binary.peek(1)
|
|
67
|
+
encoding = "utf-16" if start[:2] in (b"\xff\xfe", b"\xfe\xff") else "utf-8-sig"
|
|
68
|
+
line_ending = _first_line_ending(start.decode(encoding, errors="ignore"))
|
|
69
|
+
text = io.TextIOWrapper(
|
|
52
70
|
binary, encoding=encoding, errors="datapy-windows-1252", newline=""
|
|
53
71
|
)
|
|
72
|
+
return text, line_ending
|
|
54
73
|
|
|
55
74
|
|
|
56
75
|
#: The type of a column of whole numbers too large for SQLite's 64-bit
|
|
@@ -130,13 +149,17 @@ class Source:
|
|
|
130
149
|
self.label = "standard input" if path == STDIN else path
|
|
131
150
|
self._handle = None
|
|
132
151
|
self._owned = path != STDIN
|
|
152
|
+
#: How lines end in the file, so that output can end them the same way.
|
|
153
|
+
self.line_ending = "\n"
|
|
133
154
|
try:
|
|
134
155
|
if self._owned:
|
|
135
|
-
handle
|
|
156
|
+
handle, self.line_ending = decoded(open(path, "rb"))
|
|
157
|
+
self._handle = handle
|
|
136
158
|
elif hasattr(sys.stdin, "buffer"):
|
|
137
159
|
# Read the bytes ourselves, so that a pipe is decoded exactly
|
|
138
160
|
# as a file is, whatever the locale says.
|
|
139
|
-
handle
|
|
161
|
+
handle, self.line_ending = decoded(sys.stdin.buffer)
|
|
162
|
+
self._handle = handle
|
|
140
163
|
else:
|
|
141
164
|
handle = sys.stdin # replaced with a text stream by the caller
|
|
142
165
|
except OSError as error:
|
|
@@ -15,6 +15,7 @@ from __future__ import annotations
|
|
|
15
15
|
|
|
16
16
|
import argparse
|
|
17
17
|
import csv
|
|
18
|
+
import errno
|
|
18
19
|
import os
|
|
19
20
|
import re
|
|
20
21
|
import sys
|
|
@@ -251,6 +252,14 @@ def build_statement(parser: argparse.ArgumentParser, args: argparse.Namespace) -
|
|
|
251
252
|
names = ["FILE"] if args.all else ["COLUMNS", "FILE"]
|
|
252
253
|
form = "-sa FILE" if args.all else "-s COLUMNS FILE"
|
|
253
254
|
if len(words) == len(names) - 1 and not sys.stdin.isatty():
|
|
255
|
+
if words and os.path.isfile(words[0]):
|
|
256
|
+
# In a script standard input is never a terminal, so a forgotten
|
|
257
|
+
# COLUMNS would otherwise be read as "this file's name is a
|
|
258
|
+
# column, and the data is piped in".
|
|
259
|
+
parser.error(
|
|
260
|
+
f"missing COLUMNS: {words[0]!r} is a file. Expected {form}, "
|
|
261
|
+
"or -sa FILE for every column"
|
|
262
|
+
)
|
|
254
263
|
words = words + ["-"] # FILE left out and input is piped in
|
|
255
264
|
if len(words) < len(names):
|
|
256
265
|
parser.error(f"missing {names[len(words)]}: expected {form}")
|
|
@@ -285,13 +294,68 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
285
294
|
args.query += literal
|
|
286
295
|
|
|
287
296
|
statement = build_statement(parser, args)
|
|
297
|
+
try:
|
|
298
|
+
return _write(statement, args)
|
|
299
|
+
except OSError as error:
|
|
300
|
+
if not _reader_went_away(error):
|
|
301
|
+
raise
|
|
302
|
+
# `datapy ... | head`: the reader has all it wants. Stop reading the
|
|
303
|
+
# file and exit quietly, as other tools do. Python would otherwise
|
|
304
|
+
# complain again when it flushes standard output on the way out.
|
|
305
|
+
try:
|
|
306
|
+
os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
|
|
307
|
+
except (OSError, ValueError):
|
|
308
|
+
pass # standard output is not a real file
|
|
309
|
+
return 0
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
class _LineEnding:
|
|
313
|
+
"""Writes what the csv module writes, ending lines with `ending` instead.
|
|
314
|
+
|
|
315
|
+
Before Python 3.11 the csv module quoted a field only if it held a
|
|
316
|
+
character of the line terminator, so with a terminator of "\\n" a field
|
|
317
|
+
holding a bare "\\r" was written unquoted, and with "\\r" one holding
|
|
318
|
+
"\\n" was: either way the output no longer read back as the same rows.
|
|
319
|
+
The writer is given "\\r\\n", which makes it quote both, and each row's
|
|
320
|
+
terminator is swapped for the ending wanted as the row is written.
|
|
321
|
+
"""
|
|
322
|
+
|
|
323
|
+
def __init__(self, out, ending: str):
|
|
324
|
+
self._out = out
|
|
325
|
+
self._ending = ending
|
|
326
|
+
|
|
327
|
+
def write(self, text: str):
|
|
328
|
+
if text.endswith("\r\n"):
|
|
329
|
+
text = text[:-2] + self._ending
|
|
330
|
+
return self._out.write(text)
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _csv_writer(out, delimiter: str, ending: str, legacy=sys.version_info < (3, 11)):
|
|
334
|
+
"""A csv writer that ends lines with `ending` and quotes line breaks."""
|
|
335
|
+
if legacy:
|
|
336
|
+
return csv.writer(
|
|
337
|
+
_LineEnding(out, ending), delimiter=delimiter, lineterminator="\r\n"
|
|
338
|
+
)
|
|
339
|
+
return csv.writer(out, delimiter=delimiter, lineterminator=ending)
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def _reader_went_away(error: OSError, windows: bool = os.name == "nt") -> bool:
|
|
343
|
+
"""Whether an error means whatever was reading our output has closed it."""
|
|
344
|
+
if isinstance(error, BrokenPipeError):
|
|
345
|
+
return True
|
|
346
|
+
# Windows reports a closed pipe as an invalid argument.
|
|
347
|
+
return windows and error.errno == errno.EINVAL
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def _write(statement: str, args: argparse.Namespace) -> int:
|
|
351
|
+
"""Run the statement and write its rows to standard output as csv."""
|
|
288
352
|
if hasattr(sys.stdout, "reconfigure"):
|
|
289
353
|
# Input is read as UTF-8 whatever the locale, so output is written
|
|
290
|
-
# the same way: what was read can always be written back.
|
|
291
|
-
|
|
354
|
+
# the same way: what was read can always be written back. Line
|
|
355
|
+
# endings are written as given, not translated (as Windows would).
|
|
356
|
+
sys.stdout.reconfigure(encoding="utf-8", newline="")
|
|
292
357
|
delimiter = "\t" if args.delimiter == "\\t" else args.delimiter
|
|
293
358
|
text = [name for value in args.text for name in value.split(",") if name.strip()]
|
|
294
|
-
writer = csv.writer(sys.stdout, delimiter=delimiter, lineterminator="\n")
|
|
295
359
|
try:
|
|
296
360
|
with stream(
|
|
297
361
|
statement,
|
|
@@ -300,6 +364,8 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
300
364
|
text=text,
|
|
301
365
|
skip_bad_rows=args.skip_bad_rows,
|
|
302
366
|
) as rows:
|
|
367
|
+
# Lines end the way they do in the file that was read.
|
|
368
|
+
writer = _csv_writer(sys.stdout, delimiter, rows.line_ending)
|
|
303
369
|
if not args.no_header:
|
|
304
370
|
writer.writerow(rows.columns)
|
|
305
371
|
for count, row in enumerate(rows, start=1):
|
|
@@ -318,8 +384,4 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
318
384
|
sys.stdout.flush()
|
|
319
385
|
print(f"datapy: error: {error}", file=sys.stderr)
|
|
320
386
|
return 1
|
|
321
|
-
except BrokenPipeError:
|
|
322
|
-
# The reader went away (e.g. `datapy ... | head`): stop reading the
|
|
323
|
-
# file and exit quietly.
|
|
324
|
-
os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
|
|
325
387
|
return 0
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: datapy
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.2
|
|
4
4
|
Summary: An intuitive lightweight file based database and query tool.
|
|
5
5
|
Author-email: Corey McCarty <corey@mccarty.dev>
|
|
6
6
|
License-Expression: Apache-2.0
|
|
@@ -21,6 +21,7 @@ Description-Content-Type: text/markdown
|
|
|
21
21
|
License-File: LICENSE.txt
|
|
22
22
|
Provides-Extra: dev
|
|
23
23
|
Requires-Dist: pytest; extra == "dev"
|
|
24
|
+
Requires-Dist: pytest-cov; extra == "dev"
|
|
24
25
|
Requires-Dist: build; extra == "dev"
|
|
25
26
|
Requires-Dist: black<27,>=26; extra == "dev"
|
|
26
27
|
Dynamic: license-file
|
|
@@ -24,7 +24,7 @@ classifiers = [
|
|
|
24
24
|
dependencies = []
|
|
25
25
|
|
|
26
26
|
[project.optional-dependencies]
|
|
27
|
-
dev = ["pytest", "build", "black>=26,<27"]
|
|
27
|
+
dev = ["pytest", "pytest-cov", "build", "black>=26,<27"]
|
|
28
28
|
|
|
29
29
|
[project.scripts]
|
|
30
30
|
datapy = "datapy.cli:main"
|
|
@@ -46,3 +46,20 @@ target-version = ["py310"]
|
|
|
46
46
|
|
|
47
47
|
[tool.pytest.ini_options]
|
|
48
48
|
testpaths = ["tests"]
|
|
49
|
+
# A test still running after this long gets every thread's stack written to
|
|
50
|
+
# standard error, so a hang shows where it is waiting.
|
|
51
|
+
faulthandler_timeout = 120
|
|
52
|
+
|
|
53
|
+
[tool.coverage.run]
|
|
54
|
+
source = ["datapy"]
|
|
55
|
+
branch = true
|
|
56
|
+
# The command line tests run datapy as a separate process; measure those too.
|
|
57
|
+
patch = ["subprocess"]
|
|
58
|
+
parallel = true
|
|
59
|
+
|
|
60
|
+
[tool.coverage.report]
|
|
61
|
+
# Just under what the suite reaches, so that new code without tests fails the
|
|
62
|
+
# build. Raise it when coverage rises; do not lower it to get a change in.
|
|
63
|
+
fail_under = 96
|
|
64
|
+
show_missing = true
|
|
65
|
+
skip_covered = true
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"""The rules the workflows apply: what counts as a release, and which version may follow."""
|
|
2
2
|
|
|
3
3
|
import pathlib
|
|
4
|
+
import re
|
|
4
5
|
import sys
|
|
5
6
|
|
|
6
7
|
import pytest
|
|
@@ -99,3 +100,18 @@ def test_reading_the_version(ci):
|
|
|
99
100
|
assert ci.read_version('"""doc"""\n\n__version__ = "1.2.3"\n') == "1.2.3"
|
|
100
101
|
assert ci.read_version("nothing here") is None
|
|
101
102
|
assert ci.parse(ci.current_version()) is not None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def test_the_summary_check_waits_for_every_other_check():
|
|
106
|
+
"""Branch protection requires only "All checks passed", so a job that it
|
|
107
|
+
does not wait for would not be enforced at all."""
|
|
108
|
+
workflow = (TOOLS.parent / ".github" / "workflows" / "pull-request.yml").read_text()
|
|
109
|
+
workflow = workflow[workflow.index("\njobs:\n") :]
|
|
110
|
+
jobs = re.findall(r"^ ([\w-]+):$", workflow, re.MULTILINE)
|
|
111
|
+
needs = re.search(
|
|
112
|
+
r"^ all-passed:\n(?: .*\n)*? needs: \[(.*)\]", workflow, re.M
|
|
113
|
+
)
|
|
114
|
+
assert "all-passed" in jobs and needs
|
|
115
|
+
assert {job.strip() for job in needs.group(1).split(",")} == set(jobs) - {
|
|
116
|
+
"all-passed"
|
|
117
|
+
}
|
|
@@ -1,11 +1,15 @@
|
|
|
1
|
+
import csv
|
|
2
|
+
import errno
|
|
1
3
|
import io
|
|
2
4
|
import os
|
|
3
5
|
import pathlib
|
|
4
6
|
import subprocess
|
|
5
7
|
import sys
|
|
8
|
+
import threading
|
|
6
9
|
|
|
7
10
|
import pytest
|
|
8
11
|
|
|
12
|
+
import datapy.cli
|
|
9
13
|
from datapy.cli import main
|
|
10
14
|
|
|
11
15
|
|
|
@@ -252,19 +256,57 @@ def test_bad_rows_stop_the_query_unless_skipped(tmp_path, capsys):
|
|
|
252
256
|
assert capsys.readouterr().err == ""
|
|
253
257
|
|
|
254
258
|
|
|
259
|
+
def test_forgotten_columns_are_not_taken_for_piped_input(people, monkeypatch, capsys):
|
|
260
|
+
# As in a script or a scheduled job: standard input is not a terminal.
|
|
261
|
+
monkeypatch.setattr("sys.stdin", io.StringIO("name,age\nAnn,49\n"))
|
|
262
|
+
with pytest.raises(SystemExit) as stopped:
|
|
263
|
+
main(["-s", people])
|
|
264
|
+
assert stopped.value.code == 2
|
|
265
|
+
error = capsys.readouterr().err
|
|
266
|
+
assert "missing COLUMNS" in error and "is a file" in error
|
|
267
|
+
# A column list that is not a file name still reads the piped input.
|
|
268
|
+
assert main(["-s", "name"]) == 0
|
|
269
|
+
assert capsys.readouterr().out == "name\nAnn\n"
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
@pytest.mark.parametrize("legacy", [None, True], ids=["this Python", "as before 3.11"])
|
|
273
|
+
@pytest.mark.parametrize("ending", ["\n", "\r\n", "\r"])
|
|
274
|
+
def test_fields_holding_a_line_break_are_quoted_whatever_the_ending(ending, legacy):
|
|
275
|
+
"""Python 3.10 quoted only the characters of the line terminator."""
|
|
276
|
+
out = io.StringIO()
|
|
277
|
+
rows = [["a", "b"], ["1", "two\nlines"], ["2", "bare\rreturn"], ["3", "x,y"]]
|
|
278
|
+
options = {} if legacy is None else {"legacy": legacy}
|
|
279
|
+
writer = datapy.cli._csv_writer(out, ",", ending, **options)
|
|
280
|
+
writer.writerows(rows)
|
|
281
|
+
assert out.getvalue() == ending.join(
|
|
282
|
+
["a,b", '1,"two\nlines"', '2,"bare\rreturn"', '3,"x,y"', ""]
|
|
283
|
+
)
|
|
284
|
+
# And it reads back as the same rows.
|
|
285
|
+
assert list(csv.reader(io.StringIO(out.getvalue(), newline=""))) == rows
|
|
286
|
+
|
|
287
|
+
|
|
255
288
|
def piped(data: bytes, *arguments, **environment):
|
|
256
289
|
"""Run the real command with bytes on standard input."""
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
290
|
+
try:
|
|
291
|
+
done = subprocess.run(
|
|
292
|
+
[sys.executable, "-m", "datapy", *arguments],
|
|
293
|
+
input=data,
|
|
294
|
+
capture_output=True,
|
|
295
|
+
cwd=pathlib.Path(__file__).resolve().parent.parent,
|
|
296
|
+
env={**os.environ, **environment},
|
|
297
|
+
timeout=60,
|
|
298
|
+
)
|
|
299
|
+
except subprocess.TimeoutExpired as hung:
|
|
300
|
+
# Fail with what the command did say, instead of waiting for it.
|
|
301
|
+
pytest.fail(
|
|
302
|
+
f"datapy {arguments} was still running after {hung.timeout} s;"
|
|
303
|
+
f" input={data!r}, stdout={hung.stdout!r}, stderr={hung.stderr!r}"
|
|
304
|
+
)
|
|
264
305
|
assert done.stderr == b"", done.stderr.decode()
|
|
265
306
|
return done.stdout
|
|
266
307
|
|
|
267
308
|
|
|
309
|
+
@pytest.mark.skipif(os.name == "nt", reason="Windows has no LC_ALL locales")
|
|
268
310
|
@pytest.mark.parametrize("locale", ["C.UTF-8", "C", "POSIX"])
|
|
269
311
|
def test_piped_bytes_are_read_like_a_file(locale):
|
|
270
312
|
expected = "name\ncafé €5\n".encode("utf-8")
|
|
@@ -277,5 +319,127 @@ def test_piped_bytes_are_read_like_a_file(locale):
|
|
|
277
319
|
|
|
278
320
|
|
|
279
321
|
def test_line_breaks_inside_a_piped_field_are_kept():
|
|
280
|
-
data = b'a,b\
|
|
281
|
-
assert piped(data, "-sa") ==
|
|
322
|
+
data = b'a,b\n"one\r\ntwo",1\n'
|
|
323
|
+
assert piped(data, "-sa") == data
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
@pytest.mark.parametrize("line_ending", ["\n", "\r\n", "\r"])
|
|
327
|
+
@pytest.mark.parametrize("encoding", ["utf-8", "utf-8-sig", "utf-16"])
|
|
328
|
+
@pytest.mark.parametrize("arguments", [["-sa"], ["-sa", "-o", "a"]])
|
|
329
|
+
def test_lines_end_as_they_do_in_the_input(tmp_path, line_ending, encoding, arguments):
|
|
330
|
+
text = line_ending.join(["a,b", "1,x", '2,"two\nlines"', ""])
|
|
331
|
+
expected = text.encode("utf-8")
|
|
332
|
+
assert piped(text.encode(encoding), *arguments) == expected
|
|
333
|
+
path = tmp_path / "t.csv"
|
|
334
|
+
path.write_bytes(text.encode(encoding))
|
|
335
|
+
assert piped(b"", arguments[0], str(path), *arguments[1:]) == expected
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def test_one_line_of_input_ends_with_a_plain_line_feed():
|
|
339
|
+
assert piped(b"a,b", "-sa") == b"a,b\n"
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def start(*arguments, **streams):
|
|
343
|
+
"""Start the real command without waiting for it."""
|
|
344
|
+
return subprocess.Popen(
|
|
345
|
+
[sys.executable, "-m", "datapy", *arguments],
|
|
346
|
+
stdout=subprocess.PIPE,
|
|
347
|
+
stderr=subprocess.PIPE,
|
|
348
|
+
cwd=pathlib.Path(__file__).resolve().parent.parent,
|
|
349
|
+
**streams,
|
|
350
|
+
)
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
@pytest.mark.parametrize(
|
|
354
|
+
"arguments, last_line",
|
|
355
|
+
[
|
|
356
|
+
(["-sa"], "5,5"), # written as the file is read
|
|
357
|
+
(["-sa", "-o", "n desc"], "5,5"), # written from the temporary database
|
|
358
|
+
(["-sa", "-w", "n < 3000"], "1,2,3"), # stops before the bad last row
|
|
359
|
+
],
|
|
360
|
+
)
|
|
361
|
+
def test_a_reader_that_stops_early_ends_the_command_quietly(
|
|
362
|
+
tmp_path, arguments, last_line
|
|
363
|
+
):
|
|
364
|
+
path = tmp_path / "big.csv"
|
|
365
|
+
lines = ["n,text"] + [f"{n},{'x' * 50}" for n in range(200_000)] + [last_line]
|
|
366
|
+
path.write_text("\n".join(lines) + "\n")
|
|
367
|
+
command = start(*arguments[:1], str(path), *arguments[1:])
|
|
368
|
+
assert command.stdout.readline() == b"n,text\n"
|
|
369
|
+
command.stdout.close() # what `| head -1` does
|
|
370
|
+
assert command.wait(timeout=60) == 0
|
|
371
|
+
assert command.stderr.read() == b""
|
|
372
|
+
command.stderr.close()
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
class ClosedPipe(io.StringIO):
|
|
376
|
+
"""Standard output whose reader has gone: nothing more can be flushed."""
|
|
377
|
+
|
|
378
|
+
def flush(self):
|
|
379
|
+
raise BrokenPipeError
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def test_an_error_found_after_the_reader_left_is_not_reported(
|
|
383
|
+
tmp_path, monkeypatch, capsys
|
|
384
|
+
):
|
|
385
|
+
path = tmp_path / "t.csv"
|
|
386
|
+
path.write_text("a,b\n1,2\n3,4,5\n")
|
|
387
|
+
with monkeypatch.context() as patched:
|
|
388
|
+
patched.setattr("sys.stdout", ClosedPipe())
|
|
389
|
+
assert main(["-sa", str(path)]) == 0
|
|
390
|
+
assert main(["-sa", str(path), "-k"]) == 0
|
|
391
|
+
assert capsys.readouterr().err == ""
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def test_what_counts_as_a_closed_pipe():
|
|
395
|
+
from datapy.cli import _reader_went_away
|
|
396
|
+
|
|
397
|
+
invalid = OSError(errno.EINVAL, "Invalid argument")
|
|
398
|
+
assert _reader_went_away(BrokenPipeError(), windows=False)
|
|
399
|
+
assert _reader_went_away(invalid, windows=True)
|
|
400
|
+
assert not _reader_went_away(invalid, windows=False)
|
|
401
|
+
assert not _reader_went_away(OSError(errno.ENOSPC, "disk full"), windows=True)
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def test_other_output_errors_are_not_hidden(tmp_path, monkeypatch):
|
|
405
|
+
class FullDisk(io.StringIO):
|
|
406
|
+
def flush(self):
|
|
407
|
+
raise OSError(errno.ENOSPC, "No space left on device")
|
|
408
|
+
|
|
409
|
+
path = tmp_path / "t.csv"
|
|
410
|
+
path.write_text("a\n1\n")
|
|
411
|
+
monkeypatch.setattr("sys.stdout", FullDisk())
|
|
412
|
+
with pytest.raises(OSError, match="No space left"):
|
|
413
|
+
main(["-sa", str(path)])
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def test_rows_are_written_before_the_input_ends():
|
|
417
|
+
command = start("-sa", "-w", "n >= 0", stdin=subprocess.PIPE)
|
|
418
|
+
data = b"n\n" + b"".join(b"%d\n" % n for n in range(20_000))
|
|
419
|
+
ended = threading.Event()
|
|
420
|
+
|
|
421
|
+
def feed():
|
|
422
|
+
# Written from a thread: a pipe holds only a few kilobytes on Windows,
|
|
423
|
+
# so the command waits for this test to read its output while this
|
|
424
|
+
# test waits for the command to read its input.
|
|
425
|
+
command.stdin.write(data)
|
|
426
|
+
command.stdin.flush() # more could follow: the pipe is still open
|
|
427
|
+
ended.wait(timeout=60)
|
|
428
|
+
command.stdin.close()
|
|
429
|
+
|
|
430
|
+
first = []
|
|
431
|
+
feeder = threading.Thread(target=feed)
|
|
432
|
+
reader = threading.Thread(target=lambda: first.append(command.stdout.readline()))
|
|
433
|
+
feeder.start()
|
|
434
|
+
reader.start()
|
|
435
|
+
reader.join(timeout=30)
|
|
436
|
+
arrived = list(first)
|
|
437
|
+
ended.set()
|
|
438
|
+
reader.join()
|
|
439
|
+
rest = command.stdout.read() # let it finish writing
|
|
440
|
+
feeder.join()
|
|
441
|
+
assert command.wait(timeout=60) == 0
|
|
442
|
+
command.stdout.close()
|
|
443
|
+
command.stderr.close()
|
|
444
|
+
assert arrived == [b"n\n"]
|
|
445
|
+
assert rest.count(b"\n") == 20_000
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import pytest
|
|
2
2
|
|
|
3
|
+
import sqlite3
|
|
4
|
+
|
|
3
5
|
import datapy
|
|
4
6
|
from datapy import DatapyError, query
|
|
5
7
|
|
|
@@ -137,6 +139,10 @@ def test_query_cannot_write_files(people, tmp_path):
|
|
|
137
139
|
assert not target.exists()
|
|
138
140
|
|
|
139
141
|
|
|
142
|
+
@pytest.mark.skipif(
|
|
143
|
+
sqlite3.sqlite_version_info < (3, 39, 0),
|
|
144
|
+
reason="'is distinct from' arrived in SQLite 3.39",
|
|
145
|
+
)
|
|
140
146
|
def test_from_is_only_a_file_in_a_from_clause(tmp_path):
|
|
141
147
|
path = tmp_path / "t.csv"
|
|
142
148
|
path.write_text("a,b\n1,1\n2,\n")
|
|
@@ -103,6 +103,17 @@ def test_a_stream_is_closed_when_exhausted_or_left_early(people):
|
|
|
103
103
|
assert list(result) == []
|
|
104
104
|
|
|
105
105
|
|
|
106
|
+
def test_line_ending_is_taken_from_the_first_line(tmp_path):
|
|
107
|
+
for ending in ("\n", "\r\n", "\r"):
|
|
108
|
+
path = tmp_path / "t.csv"
|
|
109
|
+
path.write_bytes(f"a,b{ending}1,2{ending}".encode())
|
|
110
|
+
with datapy.stream(f"select * from {path}") as result:
|
|
111
|
+
assert result.line_ending == ending
|
|
112
|
+
assert rows(result) == [("1", "2")]
|
|
113
|
+
with datapy.open(path) as data:
|
|
114
|
+
assert data.stream("select * from t").line_ending == ending
|
|
115
|
+
|
|
116
|
+
|
|
106
117
|
def test_datafile_stream(people):
|
|
107
118
|
with datapy.open("people.csv") as loaded:
|
|
108
119
|
result = loaded.stream("select name from people order by name limit 2")
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|