Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 117 additions & 8 deletions tests/slow/test_h2oai_arrow.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import gzip
import http.server
import math
import threading
import time

import pytest

Expand Down Expand Up @@ -194,8 +198,38 @@ def test_join(self, threads, function, large_data):
function(large_data)


DOWNLOAD_ATTEMPTS = 3


def _download(session, url, filepath, *, report, sleep=time.sleep) -> None:
"""Save the gzip file at `url` as `filepath`, byte for byte, fetching it again when what arrives is not gzip.

`report` is told what arrived each time it was not the file, so a run that recovers still shows it.
"""
for attempt in range(DOWNLOAD_ATTEMPTS):
with session.get(url, stream=True, timeout=(30, 60)) as r:
r.raise_for_status()
with filepath.open("wb") as f:
# Undecoded: under a Content-Encoding of gzip, requests would unpack the file into its CSV text.
for chunk in r.raw.stream(1 << 20, decode_content=False):
f.write(chunk)
with filepath.open("rb") as f:
start = f.read(64)
if start.startswith(b"\x1f\x8b"):
return
arrived = (
f"status {r.status_code}, {filepath.stat().st_size} bytes starting with {start!r}, "
f"headers {dict(r.headers)}"
)
report(f"{url} did not arrive as a gzip file (attempt {attempt + 1} of {DOWNLOAD_ATTEMPTS}): {arrived}")
if attempt + 1 < DOWNLOAD_ATTEMPTS:
sleep(2**attempt)
msg = f"{url} did not arrive as a gzip file in {DOWNLOAD_ATTEMPTS} attempts; the last one: {arrived}"
raise RuntimeError(msg)


@pytest.fixture(scope="module")
def arrow_dataset_register(tmp_path_factory):
def arrow_dataset_register(request, tmp_path_factory):
"""Single fixture to download files and register them on the given connection."""
session = requests.Session()
retries = urllib3_util.Retry(
Expand All @@ -217,15 +251,18 @@ def arrow_dataset_register(tmp_path_factory):
data_dir = tmp_path_factory.mktemp("h2oai")
saved_filepaths = set()

capture = request.config.pluginmanager.getplugin("capturemanager")

def _report(message) -> None:
# Past pytest's capture, which would show the line only if the test then fails.
with capture.global_and_fixture_disabled():
print(f"\n{message}", flush=True)

def _register(url, filename, con, tablename) -> None:
filepath = data_dir / filename
with session.get(url, stream=True, timeout=(30, 60)) as r:
r.raise_for_status()
# Recorded before the body streams, so a download that breaks halfway is still removed at teardown.
saved_filepaths.add(filepath)
with filepath.open("wb") as f:
for chunk in r.iter_content(chunk_size=1 << 20):
f.write(chunk)
# Recorded before the body streams, so a download that breaks halfway is still removed at teardown.
saved_filepaths.add(filepath)
_download(session, url, filepath, report=_report)
con.register(tablename, read_csv(filepath))

yield _register
Expand Down Expand Up @@ -277,3 +314,75 @@ def group_by_data(arrow_dataset_register):
)
yield con
con.close()


@pytest.fixture
def serve_bodies():
"""A local server that answers each GET with the next of the given bodies, the last one from then on."""
servers = []

def _serve(bodies, headers=()):
requested = []

class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self) -> None:
body = bodies[min(len(requested), len(bodies) - 1)]
requested.append(self.path)
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
for name, value in headers:
self.send_header(name, value)
self.end_headers()
self.wfile.write(body)

def log_message(self, *args) -> None:
pass

server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
servers.append(server)
return f"http://127.0.0.1:{server.server_port}/data.csv.gz", requested

yield _serve

for server in servers:
server.shutdown()
server.server_close()


class TestDownload:
def test_a_body_that_is_not_gzip_is_fetched_again(self, serve_bodies, tmp_path):
data = gzip.compress(b"a\n1\n")
url, requested = serve_bodies([b"<html>busy</html>", data])
reports, sleeps = [], []
with requests.Session() as session:
_download(session, url, tmp_path / "data.csv.gz", report=reports.append, sleep=sleeps.append)
assert (tmp_path / "data.csv.gz").read_bytes() == data
assert len(requested) == 2
assert sleeps == [1]
assert len(reports) == 1
assert "status 200, 17 bytes starting with b'<html>busy</html>'" in reports[0]

def test_a_body_that_never_arrives_as_gzip_raises_what_arrived(self, serve_bodies, tmp_path):
url, requested = serve_bodies([b"a,b\n1,2\n"])
reports, sleeps = [], []
with requests.Session() as session, pytest.raises(RuntimeError) as error:
_download(session, url, tmp_path / "data.csv.gz", report=reports.append, sleep=sleeps.append)
assert len(requested) == DOWNLOAD_ATTEMPTS
assert sleeps == [1, 2]
assert len(reports) == DOWNLOAD_ATTEMPTS
message = str(error.value)
assert message.startswith(f"{url} did not arrive as a gzip file in {DOWNLOAD_ATTEMPTS} attempts")
assert "status 200, 8 bytes starting with b'a,b\\n1,2\\n'" in message
assert "Content-Length" in message

@pytest.mark.parametrize("headers", [(), (("Content-Encoding", "gzip"),)], ids=["plain", "content_encoding_gzip"])
def test_a_gzip_body_is_saved_byte_for_byte(self, serve_bodies, tmp_path, headers):
data = gzip.compress(b"a\n1\n")
url, requested = serve_bodies([data], headers)
reports, sleeps = [], []
with requests.Session() as session:
_download(session, url, tmp_path / "data.csv.gz", report=reports.append, sleep=sleeps.append)
assert (tmp_path / "data.csv.gz").read_bytes() == data
assert read_csv(tmp_path / "data.csv.gz").to_pydict() == {"a": [1]}
assert (len(requested), reports, sleeps) == (1, [], [])
Loading