test: delete slow, timing-based and redundant tests

This commit is contained in:
imSp4rky
2026-12-05 15:20:05 -07:00
parent 783a2fc185
commit 3a0a74e694
292 changed files with 153 additions and 15174 deletions
@@ -1,14 +1,9 @@
import itertools
import math
import sys
import threading
import time
import types
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
import requests as rq
from rich import filesize
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.downloaders.requests import download
@@ -96,13 +91,3 @@ def test_a_cut_body_bounds_the_following_requests(tmp_path, server):
assert spans and all(int(end) - int(start) + 1 <= CHUNK for start, end in spans)
# the bounded requests are cheap because they share one pooled connection
assert server.connections < len(server.ranges)
def test_each_speed_line_is_the_window_rate_rounded_up(tmp_path, server, monkeypatch):
clock = itertools.count(step=11.0)
monkeypatch.setattr(downloader, "time", types.SimpleNamespace(**{**vars(time), "monotonic": lambda: next(clock)}))
events = list(download(url=server.url, save_path=tmp_path / "0.mp4", session=rq.Session()))
pairs = [(events[i - 1]["advance"], e["downloaded"]) for i, e in enumerate(events) if "downloaded" in e]
assert any(n % 11 for n, _ in pairs)
assert all(text == f"{filesize.decimal(math.ceil(n / 11))}/s" for n, text in pairs)
@@ -17,7 +17,6 @@ Pins three teardown-safety invariants:
import importlib
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
@@ -125,32 +124,6 @@ def test_dispatch_parts_does_not_finalize_on_global_cancel(server, tmp_path):
assert save_path.with_name(f"{save_path.name}.!dev").exists()
def test_backoff_wait_exits_promptly_on_batch_abort(server, tmp_path, monkeypatch):
server.always_status = 503
monkeypatch.setattr(dl, "retry_sleep", lambda exc, attempts: 30.0)
abort = threading.Event()
def consume() -> None:
for _ in dl.download(
url=url(server),
save_path=tmp_path / "seg.bin",
session=Session(),
segmented=True,
abort=abort,
):
pass
worker = threading.Thread(target=consume)
start = time.monotonic()
worker.start()
time.sleep(0.5) # let the first attempt fail and enter the backoff wait
abort.set()
worker.join(timeout=10)
assert not worker.is_alive()
# generous bound: far below the 30s nap, so the wait was interrupted, not slept out
assert time.monotonic() - start < 10
@pytest.mark.parametrize("adaptive", [False, True])
def test_cancelled_batch_raises_instead_of_finishing_or_hanging(server, tmp_path, adaptive):
dl.DOWNLOAD_CANCELLED.set()
@@ -116,16 +116,6 @@ def test_range_item_ignored_by_server_fails_not_corrupts(server, tmp_path, monke
assert not list(tmp_path.glob("seg_*.bin"))
def test_range_item_spanning_whole_resource_accepts_200(server, tmp_path):
# RFC 9110 lets a server ignore Range and answer 200 with the whole resource; when the
# slice spans that resource the body is byte-identical to the 206 and must be kept
server.honor_range = False
urls = [{"url": url(server), "headers": {"Range": f"bytes=0-{len(PARENT) - 1}"}}]
files = run(server, tmp_path, urls, max_workers=1)
assert files[0].read_bytes() == PARENT
assert len(server.requests) == 1
def test_range_item_retry_rewrites_slice(server, tmp_path, monkeypatch):
server.truncate_first = True
monkeypatch.setattr(dl, "RETRY_WAIT", 0.01)
@@ -138,22 +128,12 @@ def test_range_item_retry_rewrites_slice(server, tmp_path, monkeypatch):
assert len(ranges) >= 2
def test_segment_requests_ask_identity_encoding(server, tmp_path):
run(server, tmp_path, [{"url": url(server)}], max_workers=1)
assert all(r.get("Accept-Encoding") == "identity" for r in server.requests)
def exc_with_headers(headers):
exc = Exception("boom")
exc.response = SimpleNamespace(headers=headers)
return exc
def test_retry_sleep_honors_numeric_retry_after():
assert dl.retry_sleep(exc_with_headers({"Retry-After": "3"}), 1) == 3.0
assert dl.retry_sleep(exc_with_headers({"Retry-After": "9999"}), 1) == 60.0 # session.MAX_BACKOFF cap
def test_retry_sleep_honors_http_date_retry_after():
when = format_datetime(datetime.now(UTC) + timedelta(seconds=10), usegmt=True)
assert 5 <= dl.retry_sleep(exc_with_headers({"Retry-After": when}), 1) <= 10
@@ -166,25 +146,6 @@ def test_retry_sleep_exponential_backoff_with_jitter():
assert dl.retry_sleep(Exception("reset"), 30) == 60.0 # capped
def test_retry_sleep_invalid_retry_after_falls_back():
v = dl.retry_sleep(exc_with_headers({"Retry-After": "soon"}), 1)
assert dl.RETRY_WAIT <= v <= dl.RETRY_WAIT * 1.1
def test_retry_sleep_naive_http_date_treated_as_utc():
# "-0000" makes parsedate_to_datetime return a naive datetime; must clamp, not raise
when = format_datetime(datetime.now(UTC).replace(tzinfo=None) + timedelta(seconds=10))
assert when.endswith("-0000")
v = dl.retry_sleep(exc_with_headers({"Retry-After": when}), 1)
assert 5 <= v <= 10
def test_retry_sleep_nan_retry_after_falls_back():
# float("nan") parses; a non-finite wait must fall back to the exponential path
v = dl.retry_sleep(exc_with_headers({"Retry-After": "nan"}), 1)
assert dl.RETRY_WAIT <= v <= dl.RETRY_WAIT * 1.1
def test_retry_sleep_honors_retry_after_on_wrapped_cause():
# RnetSession raises MaxRetriesError whose __cause__ HTTPError carries the response
exc = Exception("max retries exceeded")
-110
View File
@@ -1,110 +0,0 @@
"""A bounded sub-range that returns no bytes must fail, not spin.
After a cut, the sequential path asks for bounded sub-ranges and treats a whole
sub-range as progress rather than a retry. A response with an empty body of
unknown length (a chunked 206, a 204, a 304) makes no progress, so it must
raise and spend an attempt, or the same request repeats forever.
"""
import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
import requests as rq
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.downloaders.requests import download
# the package re-exports the `requests` function, shadowing the module of the same name
downloader = sys.modules[download.__module__]
BODY = bytes(range(256)) * 256 # 64 KiB
CUT_AFTER = 10 * 1024
CHUNK = 16 * 1024
DEADLINE = 30
class _EmptyRangeServer(ThreadingHTTPServer):
"""Cuts the first body, then answers every bounded range with an empty chunked 206."""
allow_reuse_address = True
daemon_threads = True
def __init__(self):
self.ranges: list[str] = []
super().__init__(("127.0.0.1", 0), _EmptyRangeHandler)
self.url = f"http://127.0.0.1:{self.server_address[1]}/seg.mp4"
def handle_error(self, request, client_address): # the client hanging up is expected here
pass
class _EmptyRangeHandler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *_):
pass
def do_GET(self):
header = self.headers.get("Range")
self.server.ranges.append(header)
start, end, bounded = 0, len(BODY) - 1, False
if header:
start_s, _, end_s = header.removeprefix("bytes=").partition("-")
start, end = int(start_s), (int(end_s) if end_s else len(BODY) - 1)
bounded = bool(end_s)
if bounded:
# a valid response: the chunked terminator closes a zero-length body, so requests raises nothing
self.send_response(206)
self.send_header("Content-Range", f"bytes {start}-{end}/{len(BODY)}")
self.send_header("Transfer-Encoding", "chunked")
self.end_headers()
self.wfile.write(b"0\r\n\r\n")
return
body = BODY[start : end + 1]
self.send_response(206 if header else 200)
if header:
self.send_header("Content-Range", f"bytes {start}-{end}/{len(BODY)}")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
# the cut teaches the downloader to bound the requests that follow
self.wfile.write(body[:CUT_AFTER])
self.close_connection = True
@pytest.fixture
def server(monkeypatch):
DOWNLOAD_CANCELLED.clear()
monkeypatch.setattr(downloader, "RETRY_WAIT", 0)
monkeypatch.setattr(downloader, "REQUEST_CHUNK_SIZE", CHUNK)
monkeypatch.setattr(downloader, "MIN_REQUEST_CHUNK", 4 * 1024)
monkeypatch.setattr(downloader, "MIN_RESUME_PROGRESS", 1024)
server = _EmptyRangeServer()
threading.Thread(target=server.serve_forever, daemon=True).start()
yield server
server.shutdown()
server.server_close()
DOWNLOAD_CANCELLED.clear()
def test_empty_sub_range_fails_instead_of_looping(tmp_path, server):
save_path = tmp_path / "0.mp4"
result: list[BaseException] = []
def run() -> None:
try:
list(download(url=server.url, save_path=save_path, session=rq.Session()))
except BaseException as exc:
result.append(exc)
# a hard deadline: a regression hangs this thread, and the suite must fail, not stall
worker = threading.Thread(target=run, daemon=True)
worker.start()
worker.join(timeout=DEADLINE)
assert not worker.is_alive(), f"download still running after {DEADLINE}s ({len(server.ranges)} requests)"
assert result and isinstance(result[0], IOError), f"expected an IOError, got {result!r}"
assert "no bytes" in str(result[0])
assert len(server.ranges) <= downloader.MAX_ATTEMPTS + 1
assert not save_path.exists()
@@ -208,21 +208,6 @@ def test_slice_segment_rejects_a_206_for_the_wrong_range(tmp_path, server):
assert len(server.requests) == downloader.MAX_ATTEMPTS
@pytest.mark.parametrize("server", ["range_clamped_206"], indirect=True)
def test_slice_segment_accepts_a_206_clamped_to_the_last_byte(tmp_path, server):
# some manifests author a range end past the resource; the clamped 206 is the whole slice
save_path = tmp_path / "0.mp4"
list(
download(
url=server.url,
save_path=save_path,
session=rq.Session(),
headers={"Range": f"bytes=0-{len(BODY)}"},
)
)
assert save_path.read_bytes() == BODY
@pytest.mark.parametrize("server", ["range_capped_206"], indirect=True)
def test_slice_segment_rejects_a_206_capped_short_of_the_requested_end(tmp_path, server):
# the body is a valid prefix of the slice, so only the Content-Range end catches it;
@@ -276,26 +261,3 @@ def test_failed_segment_fails_the_batch(tmp_path, server):
)
)
assert sorted(p.name for p in tmp_path.iterdir() if p.suffix == ".mp4") == []
@pytest.mark.parametrize("server", ["ok"], indirect=True)
def test_batch_larger_than_the_queue_window_downloads_every_segment(tmp_path, server):
# a broken top-up livelocks the drain loop instead of erroring, so consume on a thread and
# let the timeout fail the test
urls = [server.url] * 6
advanced = 0
def consume():
nonlocal advanced
advanced = sum(
event["advance"]
for event in requests_downloader(urls=urls, output_dir=tmp_path, filename="{i:02}.mp4", max_workers=1)
if "advance" in event
)
consumer = threading.Thread(target=consume, daemon=True)
consumer.start()
consumer.join(timeout=30)
assert not consumer.is_alive(), "downloader never finished the batch"
assert advanced == len(urls)
assert sorted(p.name for p in tmp_path.iterdir() if p.suffix == ".mp4") == [f"{i:02}.mp4" for i in range(6)]
-111
View File
@@ -1,111 +0,0 @@
"""Hedged segment racers must release their file handles before the batch completes.
A superseded loser that keeps its .!dev handle open makes the manifest merge's
stray sweep raise PermissionError (WinError 32) on Windows. This test forces a
hedge with a trickling first response and checks the invariant at the exact
moment merge would run.
"""
import importlib
import os
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import pytest
from unshackle.core.constants import DOWNLOAD_CANCELLED
# the downloaders package re-exports the requests() function, shadowing the submodule
dl = importlib.import_module("unshackle.core.downloaders.requests")
SEGMENTS = 10
SLOW_INDEX = 4
FAST_BODY = b"F" * 4096
SLOW_BODY = b"S" * 40960
TRICKLE_CHUNK = 2048
TRICKLE_DELAY = 0.5
class _Handler(BaseHTTPRequestHandler):
def do_GET(self):
with self.server.count_lock:
self.server.counts[self.path] = self.server.counts.get(self.path, 0) + 1
nth = self.server.counts[self.path]
slow_path = self.path == f"/seg/{SLOW_INDEX}"
body = SLOW_BODY if slow_path else FAST_BODY
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
if slow_path and nth == 1:
# trickle only the first attempt so the hedge retry wins instantly
for i in range(0, len(body), TRICKLE_CHUNK):
try:
self.wfile.write(body[i : i + TRICKLE_CHUNK])
self.wfile.flush()
except (BrokenPipeError, ConnectionResetError):
return
time.sleep(TRICKLE_DELAY)
else:
self.wfile.write(body)
def log_message(self, *args):
pass
@pytest.fixture
def trickle_server():
server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
server.counts = {}
server.count_lock = threading.Lock()
threading.Thread(target=server.serve_forever, daemon=True).start()
yield server
server.shutdown()
@pytest.mark.unit
def test_hedge_loser_releases_handles_before_merge(tmp_path, trickle_server, monkeypatch):
monkeypatch.setattr(dl, "HEDGE_MIN_WAIT", 0.3)
monkeypatch.setattr(dl, "RETRY_WAIT", 0.1)
DOWNLOAD_CANCELLED.clear()
threads_before = {t.ident for t in threading.enumerate()}
port = trickle_server.server_address[1]
urls = [f"http://127.0.0.1:{port}/seg/{i}" for i in range(SEGMENTS)]
start = time.monotonic()
for _event in dl.requests(urls=urls, output_dir=tmp_path, filename="{i:02}.mp4", max_workers=4):
pass
wall = time.monotonic() - start
with trickle_server.count_lock:
slow_hits = trickle_server.counts[f"/seg/{SLOW_INDEX}"]
assert slow_hits == 2, "hedge never fired; the race under test was not exercised"
# the batch must not stall draining the loser's stream (trickle alone takes ~10s)
assert wall < 5
for i in range(SEGMENTS):
expected = SLOW_BODY if i == SLOW_INDEX else FAST_BODY
assert (tmp_path / f"{i:02}.mp4").read_bytes() == expected
strays = list(tmp_path.glob("*.!dev"))
fd_dir = Path("/proc/self/fd")
if fd_dir.exists():
open_targets = set()
for fd in fd_dir.iterdir():
try:
open_targets.add(os.readlink(fd))
except OSError:
continue
held = [s.name for s in strays if str(s) in open_targets]
assert not held, f"racer still holds open handles at completion: {held}"
for stray in strays:
stray.unlink() # raises PermissionError (WinError 32) on Windows if a handle is open
leaked = [
t.name
for t in threading.enumerate()
if t.ident not in threads_before and t.name.startswith("ThreadPoolExecutor")
]
assert not leaked, f"racer threads still alive at completion: {leaked}"
-98
View File
@@ -19,8 +19,6 @@ real spawns stay fast.
"""
import importlib
import multiprocessing
import os
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
@@ -30,9 +28,7 @@ from requests import Session
from tests.downloaders.test_outage_budget import _FullDisk
from unshackle.core.api.errors import categorize_exception
from unshackle.core.constants import DownloadCancelled
from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.utils.sslciphers import SSLCiphers
dl = importlib.import_module("unshackle.core.downloaders.requests")
@@ -102,10 +98,6 @@ def clear_cancel():
dl.DOWNLOAD_CANCELLED.clear()
def die_without_result(queue, kwargs):
os._exit(3)
def full_disk_worker(queue, kwargs):
dl.open = _FullDisk
dl.mp_worker(queue, kwargs)
@@ -150,18 +142,6 @@ def test_multiprocess_stride_downloads_all_segments_correctly(server, tmp_path):
assert total_advance == n
def test_multiprocess_child_crash_raises(server, tmp_path):
# download_multiprocess has no MP_MIN_SEGMENTS gate, so drive it directly with 2 urls.
# a dict url without "url" raises KeyError while requests() builds the save path (before
# any retry loop), so the child sends __mp_error__ fast; the sibling downloads normally.
good = {"url": url(server, "/seg/0.bin")}
bad = {"nourl": True}
with pytest.raises(RuntimeError) as raised:
run_mp([good, bad], tmp_path)
assert not hasattr(raised.value, "error_code")
def test_a_full_disk_in_a_child_keeps_its_download_error_code(server, tmp_path, monkeypatch):
monkeypatch.setattr(dl, "mp_worker", full_disk_worker)
with pytest.raises(RuntimeError) as raised:
@@ -171,51 +151,6 @@ def test_a_full_disk_in_a_child_keeps_its_download_error_code(server, tmp_path,
assert categorize_exception(raised.value).error_code == APIErrorCode.DOWNLOAD_ERROR
def test_multiprocess_child_death_raises(tmp_path, monkeypatch):
monkeypatch.setattr(dl, "mp_worker", die_without_result)
raised: list[BaseException] = []
def drive():
try:
run_mp([{"url": "http://127.0.0.1:1/a"}, {"url": "http://127.0.0.1:1/b"}], tmp_path)
except BaseException as exc:
raised.append(exc)
thread = threading.Thread(target=drive, daemon=True)
thread.start()
thread.join(timeout=30)
assert not thread.is_alive()
assert len(raised) == 1 and isinstance(raised[0], RuntimeError)
assert "died without result" in str(raised[0])
def test_multiprocess_cancel_terminates_children(server, tmp_path):
server.delay = 0.5 # slow segments so cancel lands well before the batch could finish
n = dl.MP_MIN_SEGMENTS
urls = [{"url": url(server, f"/seg/{i}.bin")} for i in range(n)]
baseline = len(multiprocessing.active_children())
start = time.time()
progressed = 0
with pytest.raises(DownloadCancelled):
for event in dl.requests(urls, output_dir=tmp_path, filename="seg_{i:04}.bin", max_workers=4, processes=2):
if event.get("advance") or event.get("written"):
progressed += 1
if progressed >= 2:
dl.DOWNLOAD_CANCELLED.set() # sibling-track cancel: parent must tear the children down
elapsed = time.time() - start
# cancel stopped the work: nowhere near all segments finished, and no hang
assert len(list(tmp_path.glob("seg_*.bin"))) < n
assert elapsed < 15
# the finally-block join reaps the spawned children promptly
deadline = time.time() + 5
while time.time() < deadline and len(multiprocessing.active_children()) > baseline:
time.sleep(0.05)
assert len(multiprocessing.active_children()) <= baseline
def test_speed_limit_forces_single_process(server, tmp_path, monkeypatch):
"""A set speed limit must keep the batch in-process: spawned children re-import the
module and would run with no TokenBucket, silently ignoring the configured cap."""
@@ -253,36 +188,3 @@ def test_children_carry_session_params(server, tmp_path):
assert len(files) == n
for f in files:
assert f.read_bytes() == seg_body(int(f.stem.split("_")[1]))
def test_service_mounted_adapter_forces_single_process(server, tmp_path, monkeypatch):
"""A child mounts a plain adapter, so a session carrying SSLCiphers has to stay in this process."""
def no_mp(**kwargs):
raise AssertionError("multiprocess fan-out engaged for a session with a service-mounted adapter")
monkeypatch.setattr(dl, "download_multiprocess", no_mp)
session = Session()
session.mount("https://", SSLCiphers(security_level=2))
n = dl.MP_MIN_SEGMENTS
urls = [{"url": url(server, f"/seg/{i}.bin")} for i in range(n)]
for _ in dl.requests(
urls, output_dir=tmp_path, filename="seg_{i:04}.bin", session=session, max_workers=4, processes=2
):
pass
assert len(list(tmp_path.glob("seg_*.bin"))) == n
def test_multiprocess_skips_the_held_indices_and_counts_them_done(server, tmp_path):
n = dl.MP_MIN_SEGMENTS
urls = [{"url": url(server, f"/seg/{i}.bin")} for i in range(n)]
skip = frozenset(range(0, n, 3))
events = list(
dl.requests(urls, tmp_path, "seg_{i:04}.bin", session=Session(), max_workers=4, processes=2, skip=skip)
)
assert sum(e.get("advance", 0) for e in events) == n
assert sorted(p.name for p in tmp_path.iterdir()) == [f"seg_{i:04}.bin" for i in range(n) if i not in skip]
@@ -36,20 +36,3 @@ def test_view_shares_the_pools_it_was_copied_from() -> None:
assert twin is not adapter, "the view must be its own adapter, or Retry(0) lands on the caller"
assert twin.poolmanager is adapter.poolmanager
assert twin.proxy_manager is adapter.proxy_manager
def test_view_never_retries_and_leaves_the_caller_retrying() -> None:
session = pooled_session(total=5)
view = no_retry_session(session)
assert view.adapters["https://"].max_retries.total == 0
assert session.adapters["https://"].max_retries.total == 5, "the caller's retry policy must survive"
def test_repeated_views_keep_reusing_one_pool() -> None:
"""``download()`` rebuilds the view per segment; every rebuild must land on the same pool."""
session = pooled_session()
origin = session.adapters["https://"].poolmanager
for _ in range(3):
assert no_retry_session(session).adapters["https://"].poolmanager is origin
-53
View File
@@ -10,13 +10,10 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
import requests as rq
import rnet
from tests.downloaders.test_content_encoding import _FakeRnetResponse
from tests.downloaders.test_rnet_session_paths import SESSIONS
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.session import MaxRetriesError
from unshackle.core.utilities import get_free_port
dl = importlib.import_module("unshackle.core.downloaders.requests")
@@ -128,53 +125,3 @@ def test_status_failure_keeps_the_normal_budget(tmp_path, serve):
assert server.requests == dl.MAX_ATTEMPTS
assert not hasattr(raised.value, "error_code")
@pytest.mark.parametrize("make_session", SESSIONS)
def test_malformed_url_keeps_the_normal_budget(tmp_path, make_session):
retried: list[Exception] = []
with pytest.raises(Exception) as raised:
list(
dl.download(
url="htp://127.0.0.1/a",
save_path=tmp_path / "a.bin",
session=make_session(),
on_retry=retried.append,
)
)
assert len(retried) == dl.MAX_ATTEMPTS - 1
assert any(f"gave up after {dl.MAX_ATTEMPTS} failed attempts" in note for note in raised.value.__notes__)
class _StatusError(Exception):
def __init__(self, response):
super().__init__(f"HTTP {response.status_code}")
self.response = response
class _RecoveringSession:
"""Refuses six connections, answers one 503, then serves the body."""
def __init__(self):
self.calls = 0
def get(self, url, stream=True, **kwargs):
self.calls += 1
if self.calls <= 6:
raise MaxRetriesError("GET 127.0.0.1 failed", cause=rnet.ConnectionError("connection refused"))
if self.calls == 7:
raise _StatusError(_FakeRnetResponse(503, {}, b""))
return _FakeRnetResponse(200, {}, b"body-bytes")
def test_outage_does_not_spend_the_status_budget(tmp_path, monkeypatch):
monkeypatch.setattr(dl, "retry_sleep", lambda exc, attempts: 0)
session = _RecoveringSession()
save_path = tmp_path / "a.bin"
list(dl.download(url="http://127.0.0.1:1/a", save_path=save_path, session=dl.RnetTransport(session)))
assert save_path.read_bytes() == b"body-bytes"
assert session.calls == 8
-44
View File
@@ -22,7 +22,6 @@ only to decide not to use it.
import importlib
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
@@ -155,33 +154,6 @@ def test_probe_reuses_the_pooled_connection(server):
assert server.connections == 1
def test_probe_does_not_drain_a_200_body(server):
server.mode = "ignores_range"
session = Session()
assert dl.probe_ranged(url(server), session) == (0, False)
for _ in range(50):
with server.lock:
if server.broke or server.written >= len(BIG):
break
time.sleep(0.1)
with server.lock:
assert server.written < len(BIG)
def test_probe_asks_for_identity_encoding(server):
server.mode = "encode_unless_identity"
session = Session()
assert dl.probe_ranged(url(server), session) == (len(PAYLOAD), True)
assert server.requests[-1][1] == "identity"
# a caller that names its own encoding still wins
assert dl.probe_ranged(url(server), session, headers={"Accept-Encoding": "gzip"}) == (0, False)
assert server.requests[-1][1] == "gzip"
def test_probe_uses_the_url_items_headers(server, tmp_path, monkeypatch):
server.mode = "needs_auth"
monkeypatch.setattr(dl, "RANGE_PARALLEL_MIN_SIZE", 8 * 1024)
@@ -196,19 +168,3 @@ def test_probe_uses_the_url_items_headers(server, tmp_path, monkeypatch):
assert probes and all(r[2] == AUTH for r in probes)
# the probe was answered, so the ranged path ran instead of one sequential connection
assert [r for r in server.requests if r[0] and r[0] != "bytes=0-0"]
def test_probe_does_not_drain_a_fat_206_body(server):
"""A 206 carrying the whole resource must not be read to decide whether to use ranges."""
server.mode = "fat_206"
session = Session()
assert dl.probe_ranged(url(server), session) == (len(BIG), True)
for _ in range(50):
with server.lock:
if server.broke or server.written >= len(BIG):
break
time.sleep(0.1)
with server.lock:
assert server.written < len(BIG)
-64
View File
@@ -221,46 +221,6 @@ def test_permanent_status_unwraps_causes():
BIG = bytes((i * 13 + 7) % 256 for i in range(8 * 1024 * 1024))
class _BigHandler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def do_GET(self):
srv = self.server
rng = self.headers.get("Range")
with srv.lock:
srv.requests.append(rng)
if not rng:
self.send_response(200)
self.send_header("Content-Length", str(len(BIG)))
self.end_headers()
self.wfile.write(BIG)
return
start_s, _, end_s = rng.removeprefix("bytes=").partition("-")
start = int(start_s)
end = int(end_s) if end_s else len(BIG) - 1
body = BIG[start : end + 1]
self.send_response(206)
self.send_header("Content-Range", f"bytes {start}-{end}/{len(BIG)}")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
@pytest.fixture
def big_server():
srv = ThreadingHTTPServer(("127.0.0.1", 0), _BigHandler)
srv.lock = threading.Lock()
srv.requests = []
thread = threading.Thread(target=srv.serve_forever, daemon=True)
thread.start()
yield srv
srv.shutdown()
thread.join(timeout=5)
_REAL_SPLIT = dl.split_ranges
@@ -291,32 +251,8 @@ def plan_split(monkeypatch, tmp_path, total_size, max_workers):
return record[0]
def test_part_count_matches_worker_count(tmp_path, monkeypatch):
_, _, _, parts = plan_split(monkeypatch, tmp_path, 64 * 1024 * 1024, 16)
assert len(parts) == 16
_, _, _, parts = plan_split(monkeypatch, tmp_path, 16 * 1024 * 1024, 4)
assert len(parts) == 4
def test_part_floor_caps_sliver_count(tmp_path, monkeypatch):
# below the 4 MiB floor a part's handshake costs more than its transfer
_, _, target, parts = plan_split(monkeypatch, tmp_path, 16 * 1024 * 1024, 64)
assert target == 4 * 1024 * 1024
assert len(parts) == 4
def test_worker_driven_parts_merge_byte_identical(big_server, tmp_path):
save_path = tmp_path / "big.bin"
for _ in dl.dispatch_parts(
url=url(big_server, "/big.bin"),
save_path=save_path,
session=Session(),
total_size=len(BIG),
max_workers=2,
):
pass
assert save_path.read_bytes() == BIG
assert len({r for r in big_server.requests if r}) == 2
assert not save_path.with_name(save_path.name + ".!dev").exists()
@@ -1,88 +0,0 @@
"""The workers of a ranged single-file download share fixed-size parts from one queue.
A connection that the host holds keeps one part, and the other worker completes the rest.
"""
import importlib
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from requests import Session
from unshackle.core.constants import DOWNLOAD_CANCELLED
dl = importlib.import_module("unshackle.core.downloaders.requests")
BODY = bytes(range(256)) * 256
class _Server(ThreadingHTTPServer):
daemon_threads = True
def __init__(self):
self.lock = threading.Lock()
self.served: list[str] = []
self.held: str | None = None
self.release = threading.Event()
self.others_done_at_release = -1
super().__init__(("127.0.0.1", 0), _Handler)
self.url = f"http://127.0.0.1:{self.server_address[1]}/big.bin"
def handle_error(self, request, client_address):
pass
class _Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *_):
pass
def do_GET(self):
server = self.server
header = self.headers.get("Range")
start, end = 0, len(BODY) - 1
if header:
start_s, _, end_s = header.removeprefix("bytes=").partition("-")
start, end = int(start_s), (int(end_s) if end_s else len(BODY) - 1)
body = BODY[start : end + 1]
with server.lock:
held = server.held is None
if held:
server.held = header
if held:
server.release.wait(5)
with server.lock:
server.others_done_at_release = len(server.served)
with server.lock:
server.served.append(header)
if not held and len(server.served) == 7:
server.release.set()
self.send_response(206)
self.send_header("Content-Range", f"bytes {start}-{end}/{len(BODY)}")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def test_fast_connection_takes_the_parts_a_held_connection_cannot(tmp_path, monkeypatch):
monkeypatch.setattr(dl, "RANGE_PARALLEL_PART_SIZE", 8 * 1024)
monkeypatch.setattr(dl, "RANGE_PARALLEL_MIN_PART_SIZE", 2 * 1024)
DOWNLOAD_CANCELLED.clear()
server = _Server()
threading.Thread(target=server.serve_forever, daemon=True).start()
save_path = tmp_path / "big.bin"
try:
for _ in dl.dispatch_parts(
url=server.url, save_path=save_path, session=Session(), total_size=len(BODY), max_workers=2
):
pass
finally:
server.release.set()
server.shutdown()
server.server_close()
DOWNLOAD_CANCELLED.clear()
assert save_path.read_bytes() == BODY
assert len(set(server.served)) == 8
assert server.others_done_at_release == 7
+1 -16
View File
@@ -2,7 +2,7 @@
import pytest
from unshackle.core.downloaders.ranges import Answer, Mode, Verdict, has_range_header, range_answer
from unshackle.core.downloaders.ranges import Answer, Mode, Verdict, range_answer
pytestmark = pytest.mark.unit
@@ -13,21 +13,6 @@ def rng(value: str | None) -> dict[str, str]:
return {} if value is None else {"Range": value}
@pytest.mark.parametrize(
("item", "expected"),
[
({}, False),
({"headers": None}, False),
({"headers": {}}, False),
({"headers": {"Accept": "*/*"}}, False),
({"headers": {"Range": "bytes=0-127"}}, True),
({"headers": {"range": "bytes=0-127"}}, True),
],
)
def test_has_range_header(item, expected):
assert has_range_header(item) is expected
@pytest.mark.parametrize(
("requested", "status", "content_range", "known", "kwargs", "expected"),
[
@@ -1,51 +0,0 @@
"""Segment requests on rnet carry network.read_timeout from the config, or READ_TIMEOUT when it is unset.
A per-request read_timeout overrides the one on the rnet client, so the downloader must pass the configured value.
"""
import importlib
import pytest
from tests.downloaders.test_content_encoding import _FakeRnetResponse
from unshackle.core.config import config
dl = importlib.import_module("unshackle.core.downloaders.requests")
class FakeSession:
def __init__(self):
self.calls: list[dict] = []
def get(self, url, stream=True, **kwargs):
self.calls.append(kwargs)
return _FakeRnetResponse(200, {}, b"body-bytes")
@pytest.fixture
def session():
return FakeSession()
@pytest.mark.parametrize(
"network, module_default, kwargs, expected",
[
pytest.param({"read_timeout": 7}, None, {}, 7, id="configured"),
pytest.param({}, None, {}, dl.READ_TIMEOUT, id="unset"),
pytest.param({}, 2, {}, 2, id="patched-default"),
pytest.param({"read_timeout": 7}, None, {"read_timeout": 3}, 3, id="caller-wins"),
],
)
def test_segment_request_read_timeout(tmp_path, session, monkeypatch, network, module_default, kwargs, expected):
monkeypatch.setattr(config, "network", network)
if module_default is not None:
monkeypatch.setattr(dl, "READ_TIMEOUT", module_default)
transport = dl.RnetTransport(session)
list(dl.download(url="http://127.0.0.1:1/a", save_path=tmp_path / "a.bin", session=transport, **kwargs))
assert session.calls[0]["read_timeout"] == expected
def test_probe_uses_the_configured_read_timeout(session, monkeypatch):
monkeypatch.setattr(config, "network", {"read_timeout": 7})
dl.probe_ranged("http://127.0.0.1:1/a", dl.RnetTransport(session))
assert session.calls[0]["read_timeout"] == 7
@@ -96,15 +96,6 @@ def server(monkeypatch):
DOWNLOAD_CANCELLED.clear()
@pytest.mark.parametrize("make_session", SESSIONS)
def test_plain_body_arrives_whole(tmp_path, server, make_session):
save_path = tmp_path / "0.mp4"
list(dl.download(url=f"{server.url}/plain", save_path=save_path, session=make_session()))
assert save_path.read_bytes() == BODY
assert len(server.hits) == 1
@pytest.mark.parametrize("make_session", SESSIONS)
def test_cut_body_resumes_with_range(tmp_path, server, make_session):
save_path = tmp_path / "0.mp4"
@@ -134,17 +125,6 @@ def test_retry_after_header_sets_the_wait(tmp_path, server, make_session, monkey
assert waits == [1.0]
@pytest.mark.parametrize("make_session", SESSIONS)
def test_stalled_body_times_out_and_retries(tmp_path, server, make_session, monkeypatch):
monkeypatch.setattr(dl, "READ_TIMEOUT", 1)
monkeypatch.setattr("unshackle.core.config.config.network", {})
save_path = tmp_path / "0.mp4"
list(dl.download(url=f"{server.url}/stall", save_path=save_path, session=make_session()))
assert save_path.read_bytes() == BODY
assert len(server.hits) == 2
@pytest.mark.parametrize("make_session", SESSIONS)
def test_transport_body_reads_headers_in_any_case(server, make_session):
body = dl.transport_for(make_session()).get(f"{server.url}/plain", headers={"Range": "bytes=0-9"})
-77
View File
@@ -16,7 +16,6 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
from requests import Session
from requests.adapters import HTTPAdapter
from requests.auth import HTTPBasicAuth
from tests.core.test_session_verify import self_signed_url as self_signed_url
@@ -55,30 +54,6 @@ def test_rnet_spec_round_trips_cookie_domains() -> None:
assert rebuilt.cookies.get_dict(domain="localhost") == {}
def test_rnet_spec_keeps_dict_set_cookies() -> None:
ns = rnet_session_with_cookies()
spec = build_session_spec(ns)
assert spec is not None
rebuilt = rebuild_session(spec, 1)
assert rebuilt is not None
assert rebuilt.cookies["loose"] == "ghi"
def test_rnet_spec_cookies_carry_domain_information() -> None:
ns = rnet_session_with_cookies()
spec = build_session_spec(ns)
assert spec is not None
assert {(c.domain, c.path, c.name, c.value) for c in spec["cookies"]} == {
("cdn.example.com", "/", "cdn_token", "abc"),
("api.example.com", "/", "api_token", "def"),
("", "/", "loose", "ghi"),
}
def test_rnet_spec_keeps_same_name_cookies_on_their_paths() -> None:
"""Same-name cookies on two paths must reach a child apart, or a stale one goes to every path."""
ns = make_session("Chrome131")
@@ -94,20 +69,6 @@ def test_rnet_spec_keeps_same_name_cookies_on_their_paths() -> None:
assert rebuilt.cookies.get("hdntl", path="/t/2") == "two"
def test_rnet_spec_is_picklable() -> None:
spec = build_session_spec(rnet_session_with_cookies())
assert spec is not None
loaded = pickle.loads(pickle.dumps(spec))
# stdlib Cookie has no __eq__, so compare the cookies by their fields
assert [vars(c) for c in loaded.pop("cookies")] == [vars(c) for c in spec.pop("cookies")]
assert loaded == spec
def test_rnet_spec_without_impersonate_is_not_rebuildable() -> None:
assert build_session_spec(RnetSession()) is None
class _CookieHandler(BaseHTTPRequestHandler):
"""Sets one cookie on /set and echoes the Cookie header it receives on /echo."""
@@ -168,22 +129,6 @@ def test_rebuilt_requests_session_pool_is_sized_to_worker_count() -> None:
assert adapter.poolmanager.connection_pool_kw["maxsize"] == 24
def test_rebuilt_rnet_session_has_no_adapters() -> None:
"""rnet pools internally; the sizing fix must not reach into that path."""
spec = build_session_spec(rnet_session_with_cookies())
assert spec is not None
rebuilt = rebuild_session(spec, 24)
assert rebuilt is not None
assert not isinstance(rebuilt, Session)
assert not hasattr(rebuilt, "adapters")
def test_unrebuildable_spec_stays_none() -> None:
assert rebuild_session({"kind": "none"}, 24) is None
def test_requests_spec_round_trips_cookie_domains() -> None:
rs = Session()
rs.cookies.set("cdn_token", "abc", domain="cdn.example.com")
@@ -270,18 +215,6 @@ def test_requests_spec_carries_cert_and_auth() -> None:
assert rebuilt.auth == HTTPBasicAuth("user", "pass")
def test_requests_spec_is_picklable() -> None:
rs = Session()
rs.verify = False
rs.params = {"at": "auth-token"}
rs.cookies.set("cdn_token", "abc", domain="cdn.example.com")
spec = build_session_spec(rs)
assert spec is not None
assert pickle.loads(pickle.dumps(spec))["params"] == {"at": "auth-token"}
def test_requests_spec_with_unpicklable_auth_is_not_rebuildable() -> None:
"""auth takes any callable. One that spawn cannot pickle has to fall back, not kill the child."""
rs = Session()
@@ -303,13 +236,3 @@ def test_mounted_ssl_ciphers_is_not_rebuildable() -> None:
rs.mount("https://cdn.example.com", SSLCiphers(security_level=2))
assert build_session_spec(rs) is None
def test_rebuilt_requests_session_mounts_a_plain_adapter() -> None:
"""The spec only ever describes a plain adapter, so the child must not appear to hold more than that."""
spec = build_session_spec(Session())
assert spec is not None
rebuilt = rebuild_session(spec, 4)
assert rebuilt is not None
assert type(rebuilt.get_adapter("https://example.com")) is HTTPAdapter
+1 -60
View File
@@ -1,13 +1,10 @@
import importlib
import inspect
import threading
import time
from types import SimpleNamespace
import pytest
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.downloaders.requests import TokenBucket, format_speed, parse_speed_limit
from unshackle.core.downloaders.requests import TokenBucket, parse_speed_limit
requests_downloader = importlib.import_module("unshackle.core.downloaders.requests")
@@ -69,50 +66,6 @@ def test_parse_speed_limit_rejects(value):
parse_speed_limit(value)
@pytest.mark.parametrize(
("rate", "expected"),
[
(500, "500 bytes/s"),
(999.2, "1.0 kB/s"),
(512_000, "512.0 kB/s"),
(39 * 1024**2, "40.9 MB/s"),
(1.5 * 1024**3, "1.6 GB/s"),
],
)
def test_format_speed(rate, expected):
assert format_speed(rate) == expected
def test_result_accepts_a_missing_speed_limit():
"""The API/serve path calls dl.result() by keyword without speed_limit."""
from unshackle.commands.dl import dl
assert inspect.signature(dl.result).parameters["speed_limit"].default is None
def test_bucket_holds_aggregate_rate_across_threads():
rate = 10_000_000
bucket = TokenBucket(rate)
chunk = 100_000
totals = [0, 0, 0, 0]
start = time.monotonic()
stop = start + 1.0
def worker(i: int) -> None:
while time.monotonic() < stop:
bucket.consume(chunk)
totals[i] += chunk
threads = [threading.Thread(target=worker, args=(i,)) for i in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
achieved = sum(totals) / (time.monotonic() - start)
# exceeding the limit is a real failure; undershoot is scheduler noise on a loaded box, so no lower bound
assert achieved <= rate * 1.1
def test_bucket_refills_at_the_rate(monkeypatch):
"""On a simulated clock the throughput is exact, so a slow refill fails like a fast one."""
clock = [0.0]
@@ -135,15 +88,3 @@ def test_bucket_chunk_larger_than_capacity_does_not_deadlock(monkeypatch):
bucket.consume(1_100_000)
assert len(waits) == 1
assert 1.0 < waits[0] < 2.0
def test_bucket_wait_aborts_on_cancellation():
"""Debt sleeps grow with thread count; cancelling must not wait them out."""
bucket = TokenBucket(1_000)
DOWNLOAD_CANCELLED.set()
try:
start = time.monotonic()
bucket.consume(1_000_000)
assert time.monotonic() - start < 1.0
finally:
DOWNLOAD_CANCELLED.clear()
-13
View File
@@ -22,22 +22,9 @@ def test_first_report_is_the_since_start_average():
assert win.rate(2.5, 25_000_000) == pytest.approx(10_000_000)
def test_zero_span_returns_none():
win = SpeedWindow(0.0)
assert win.rate(0.0, 1_000_000) is None
def test_stall_returns_none():
"""Once the seed ages out, a total that stops growing has no delta to report."""
win = SpeedWindow(0.0)
for t in range(0, SPEED_ROLLING_WINDOW + 6):
rate = win.rate(float(t), 1_000_000)
assert rate is None
def test_window_drops_old_samples():
win = SpeedWindow(0.0)
for t in range(0, 3 * SPEED_ROLLING_WINDOW):
win.rate(float(t), t * 1_000_000)
assert win.samples[0][0] >= 2 * SPEED_ROLLING_WINDOW - 1
assert len(win.samples) == SPEED_ROLLING_WINDOW + 1
-105
View File
@@ -1,105 +0,0 @@
"""Submission-window invariants for the segmented drain loop.
Segments are not all submitted up front: that convoys on the pool's global lock and starves
the event drain. The loop meters submission through a window it tops up. The window must hold
two segments for every worker, so a worker that finishes one finds the next already staged
instead of idling until the next drain cycle. Fixed and adaptive mode must agree on that
ratio; adaptive sizes it from its live target instead of from ``max_workers``.
The test stalls every response, so no future can complete and the queue settles at exactly
the window. Counting ``pool.submit`` calls makes the queue depth observable: a blocked
server only ever sees ``max_workers`` requests, whatever is staged behind them.
"""
import importlib
import threading
import time
from concurrent.futures.thread import ThreadPoolExecutor
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
dl = importlib.import_module("unshackle.core.downloaders.requests")
BODY = b"segment-body" * 64
MAX_WORKERS = 4
SEG_COUNT = 20 # more than the window, so queue depth is the only bound
pytestmark = pytest.mark.unit
class _Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.server.release.wait(timeout=10)
self.send_response(200)
self.send_header("Content-Length", str(len(BODY)))
self.end_headers()
self.wfile.write(BODY)
def log_message(self, *args):
pass
@pytest.fixture
def server():
srv = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
srv.release = threading.Event()
thread = threading.Thread(target=srv.serve_forever, daemon=True)
thread.start()
yield srv
srv.release.set()
srv.shutdown()
thread.join(timeout=5)
@pytest.fixture(autouse=True)
def clean_cancel():
dl.DOWNLOAD_CANCELLED.clear()
yield
dl.DOWNLOAD_CANCELLED.clear()
@pytest.fixture
def submissions(monkeypatch):
counter: list[int] = []
class _CountingPool(ThreadPoolExecutor):
def submit(self, fn, /, *args, **kwargs):
counter.append(1) # list.append is atomic, so no lock is needed here
return super().submit(fn, *args, **kwargs)
monkeypatch.setattr(dl, "ThreadPoolExecutor", _CountingPool)
return counter
@pytest.mark.parametrize("adaptive", [False, True])
def test_queue_holds_two_segments_per_worker(server, submissions, tmp_path, adaptive):
urls = [{"url": f"http://127.0.0.1:{server.server_address[1]}/seg{i}.bin"} for i in range(SEG_COUNT)]
events: list[dict] = []
def run():
events.extend(
dl.requests(
urls,
output_dir=tmp_path,
filename="seg_{i:04}.bin",
max_workers=MAX_WORKERS,
adaptive=adaptive,
)
)
worker = threading.Thread(target=run, daemon=True)
worker.start()
try:
deadline = time.time() + 3.0
while time.time() < deadline and len(submissions) < 2 * MAX_WORKERS:
time.sleep(0.02)
time.sleep(0.2) # settle, so an over-filled window is caught as well as an under-filled one
assert len(submissions) == 2 * MAX_WORKERS
finally:
server.release.set()
worker.join(timeout=30)
assert not worker.is_alive()
assert sum(event.get("advance", 0) for event in events) == SEG_COUNT
assert len(sorted(tmp_path.glob("seg_*.bin"))) == SEG_COUNT
-33
View File
@@ -156,20 +156,6 @@ def test_tail_boost_split_produces_byte_identical_segment(server, tmp_path):
assert not list(tmp_path.glob("*.tp.!dev"))
def test_tail_boost_finalize_last_part_wins(server, tmp_path):
files, _ = run(server, tmp_path, seg_urls(server))
assert boost_engaged(server), "tail boost never engaged; finalize path untested"
assert len(files) == SEG_COUNT
# last part wins: the pre-truncated .tp.!dev is os.replace'd into save_path, leaving no target
assert not list(tmp_path.glob("*.tp.!dev"))
for path in ranged_counts(server):
i = int(path.removeprefix("/seg").removesuffix(".bin"))
save_path = tmp_path / f"seg_{i:04}.bin"
assert save_path.exists()
assert not save_path.with_name(f"{save_path.name}.tp.!dev").exists()
def test_tail_boost_part_failure_falls_back_to_normal_path(server, tmp_path, monkeypatch):
server.break_offset_ranges = True # every part window past the first fails, but not for good
monkeypatch.setattr(dl, "RETRY_WAIT", 0.01)
@@ -187,25 +173,6 @@ def test_tail_boost_part_failure_falls_back_to_normal_path(server, tmp_path, mon
assert not list(tmp_path.glob("*.tp.!dev"))
def test_tail_boost_failure_does_not_abort_sibling_segments(server, tmp_path, monkeypatch):
server.break_offset_ranges = True
monkeypatch.setattr(dl, "RETRY_WAIT", 0.01)
files, _ = run(server, tmp_path, seg_urls(server))
assert boost_engaged(server), "tail boost never engaged; the fallback path is untested"
# the parts of one segment share an abort of their own: setting the batch-wide one would
# strand every other in-flight worker and end the batch with segments missing
assert len(files) == SEG_COUNT
with server.lock:
reqs = list(server.requests)
boosted_paths = {path for path, rng in reqs if rng and rng != "bytes=0-0"}
assert boosted_paths
# each boosted segment went back on the normal path: a plain unranged GET for it
plain = {path for path, rng in reqs if rng is None}
assert boosted_paths <= plain
def test_tail_boost_permanent_part_failure_still_fails_the_batch(server, tmp_path, monkeypatch):
server.deny_offset_ranges = True # every part window past the first is a 403
monkeypatch.setattr(dl, "RETRY_WAIT", 0.01)
-60
View File
@@ -3,7 +3,6 @@
import importlib
import io
import pytest
import requests as rq
from unshackle.core.session import RnetSession
@@ -60,57 +59,6 @@ def test_each_session_kind_gets_its_transport():
assert dl.transport_for(transport) is transport
def test_requests_transport_has_no_retries_and_no_record():
session = rq.Session()
view = dl.transport_for(session).session
assert view is not session
assert view.record_request is False
assert all(adapter.max_retries.total == 0 for adapter in view.adapters.values())
class _RnetSession(RnetSession):
def __init__(self):
super().__init__()
self.calls: list[dict] = []
def get(self, url, **kwargs):
self.calls.append(kwargs)
return _Response()
def test_rnet_transport_turns_retries_and_record_off():
session = _RnetSession()
dl.transport_for(session).get("http://127.0.0.1:1/a")
assert session.calls[0]["max_retries"] == 0
assert session.calls[0]["record_request"] is False
assert session.calls[0]["stream"] is True
def test_requests_body_reads_raw_and_read1_only_while_racing():
response = _Response({"Content-Length": "6"})
body = dl.RequestsBody(response, raw=True)
racing = iter([True, False, False])
assert b"".join(body.chunks(2, lambda: next(racing))) == b"abcdef"
assert response.raw.calls == ["read1", "read", "read"]
class _Transport(dl.Transport):
def __init__(self):
self.response = _Response({"Content-Length": "6"})
def get(self, url, **kwargs):
return dl.RequestsBody(self.response, raw=True)
@pytest.mark.parametrize("claimed, expected", [(None, {"read"}), (lambda: False, {"read1"})])
def test_download_reads_read1_only_for_a_claimable_segment(tmp_path, claimed, expected):
transport = _Transport()
events = dl.download("http://127.0.0.1:1/a", tmp_path / "a.bin", transport, claimed=claimed, racing=lambda: True)
list(events)
assert (tmp_path / "a.bin").read_bytes() == b"abcdef"
assert set(transport.response.raw.calls) == expected
def test_an_encoded_body_goes_through_iter_content():
response = _Response({"content-encoding": "gzip", "Content-Length": "6"})
body = dl.RequestsBody(response, raw=True)
@@ -118,11 +66,3 @@ def test_an_encoded_body_goes_through_iter_content():
assert body.content_length == 0
assert list(body.chunks(2, None)) == [b"abcdef"]
assert response.raw.calls == []
def test_another_session_kind_is_read_with_iter_content_and_a_timeout():
session = _Session()
transport = dl.transport_for(session)
assert transport.session is session
assert list(transport.get("http://127.0.0.1:1/a").chunks(2, None)) == [b"abcdef"]
assert session.calls[0]["timeout"] == (dl.CONNECT_TIMEOUT, dl.READ_TIMEOUT)