From 4bea1aeb33f016ce52fe079952ace3b8a5c253d9 Mon Sep 17 00:00:00 2001 From: Evert Lammerts Date: Tue, 1 Dec 2026 13:48:38 +0000 Subject: [PATCH] Save the h2oai test data as the bytes the server sent --- tests/slow/test_h2oai_arrow.py | 125 ++++++++++++++++++++++++++++++--- 1 file changed, 117 insertions(+), 8 deletions(-) diff --git a/tests/slow/test_h2oai_arrow.py b/tests/slow/test_h2oai_arrow.py index 195f04fed..180cce2f1 100644 --- a/tests/slow/test_h2oai_arrow.py +++ b/tests/slow/test_h2oai_arrow.py @@ -1,4 +1,8 @@ +import gzip +import http.server import math +import threading +import time import pytest @@ -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( @@ -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 @@ -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"busy", 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'busy'" 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, [], [])