mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-27 11:25:08 +00:00
chore(release): promote 661be3ee to main
This commit is contained in:
@@ -104,7 +104,8 @@ def test_encoded_body_is_decoded_on_disk(tmp_path, encoding_server):
|
||||
assert save_path.read_bytes() == PLAIN
|
||||
|
||||
|
||||
def test_encoded_body_discards_a_partial_instead_of_range_resuming(tmp_path, encoding_server):
|
||||
def test_encoded_body_discards_a_partial_instead_of_range_resuming(tmp_path, encoding_server, monkeypatch):
|
||||
monkeypatch.setattr(importlib.import_module("unshackle.core.downloaders.requests"), "RETRY_WAIT", 0)
|
||||
save_path = tmp_path / "sub.vtt"
|
||||
save_path.with_name("sub.vtt.!dev").write_bytes(PLAIN[:5000])
|
||||
list(download(url=encoding_server.url, save_path=save_path, session=rq.Session()))
|
||||
@@ -147,6 +148,7 @@ class _FakeRnetSession:
|
||||
def test_rnet_encoded_body_discards_a_partial_instead_of_range_resuming(tmp_path, monkeypatch):
|
||||
dl = importlib.import_module("unshackle.core.downloaders.requests")
|
||||
monkeypatch.setattr(dl, "is_rnet_session", lambda s: isinstance(s, _FakeRnetSession))
|
||||
monkeypatch.setattr(dl, "RETRY_WAIT", 0)
|
||||
session = _FakeRnetSession(PLAIN)
|
||||
save_path = tmp_path / "sub.vtt"
|
||||
save_path.with_name("sub.vtt.!dev").write_bytes(PLAIN[:5000])
|
||||
|
||||
@@ -24,7 +24,7 @@ SLOW_INDEX = 4
|
||||
FAST_BODY = b"F" * 4096
|
||||
SLOW_BODY = b"S" * 40960
|
||||
TRICKLE_CHUNK = 2048
|
||||
TRICKLE_DELAY = 0.05
|
||||
TRICKLE_DELAY = 0.5
|
||||
|
||||
|
||||
class _Handler(BaseHTTPRequestHandler):
|
||||
|
||||
@@ -20,6 +20,7 @@ real spawns stay fast.
|
||||
|
||||
import importlib
|
||||
import multiprocessing
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
@@ -96,6 +97,27 @@ def clear_cancel():
|
||||
dl.DOWNLOAD_CANCELLED.clear()
|
||||
|
||||
|
||||
def die_without_result(queue, kwargs):
|
||||
os._exit(3)
|
||||
|
||||
|
||||
def run_mp(urls, tmp_path):
|
||||
for _ in dl.download_multiprocess(
|
||||
urls=urls,
|
||||
output_dir=tmp_path,
|
||||
filename="seg_{i:04}.bin",
|
||||
headers=None,
|
||||
cookies=None,
|
||||
proxy=None,
|
||||
max_workers=2,
|
||||
adaptive=False,
|
||||
spec={"kind": "none"},
|
||||
processes=2,
|
||||
debug_logger=None,
|
||||
):
|
||||
pass
|
||||
|
||||
|
||||
def url(srv, path):
|
||||
return f"http://127.0.0.1:{srv.server_address[1]}{path}"
|
||||
|
||||
@@ -120,20 +142,26 @@ def test_multiprocess_child_crash_raises(server, tmp_path):
|
||||
good = {"url": url(server, "/seg/0.bin")}
|
||||
bad = {"nourl": True}
|
||||
with pytest.raises(RuntimeError):
|
||||
for _ in dl.download_multiprocess(
|
||||
urls=[good, bad],
|
||||
output_dir=tmp_path,
|
||||
filename="seg_{i:04}.bin",
|
||||
headers=None,
|
||||
cookies=None,
|
||||
proxy=None,
|
||||
max_workers=2,
|
||||
adaptive=False,
|
||||
spec={"kind": "none"},
|
||||
processes=2,
|
||||
debug_logger=None,
|
||||
):
|
||||
pass
|
||||
run_mp([good, bad], tmp_path)
|
||||
|
||||
|
||||
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):
|
||||
@@ -171,11 +199,8 @@ def test_speed_limit_forces_single_process(server, tmp_path, monkeypatch):
|
||||
n = dl.MP_MIN_SEGMENTS
|
||||
urls = [{"url": url(server, f"/seg/{i}.bin")} for i in range(n)]
|
||||
dl.set_speed_limit(1_000_000_000)
|
||||
try:
|
||||
for _ in dl.requests(urls, output_dir=tmp_path, filename="seg_{i:04}.bin", max_workers=4, processes=2):
|
||||
pass
|
||||
finally:
|
||||
dl.set_speed_limit(None)
|
||||
for _ in dl.requests(urls, output_dir=tmp_path, filename="seg_{i:04}.bin", max_workers=4, processes=2):
|
||||
pass
|
||||
|
||||
files = sorted(tmp_path.glob("seg_*.bin"))
|
||||
assert len(files) == n
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
"""A failure with no HTTP response gets the longer outage budget, and a full disk fails on the first attempt.
|
||||
|
||||
A failure that carries an HTTP response keeps the normal MAX_ATTEMPTS budget.
|
||||
"""
|
||||
|
||||
import errno
|
||||
import importlib
|
||||
import threading
|
||||
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.session import MaxRetriesError
|
||||
from unshackle.core.utilities import get_free_port
|
||||
|
||||
dl = importlib.import_module("unshackle.core.downloaders.requests")
|
||||
|
||||
BODY = b"\0" * 4096
|
||||
|
||||
|
||||
class _Server(ThreadingHTTPServer):
|
||||
daemon_threads = True
|
||||
|
||||
def __init__(self, status):
|
||||
self.status = status
|
||||
self.requests = 0
|
||||
super().__init__(("127.0.0.1", 0), _Handler)
|
||||
self.url = f"http://127.0.0.1:{self.server_address[1]}/a"
|
||||
|
||||
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):
|
||||
self.server.requests += 1
|
||||
body = BODY if self.server.status == 200 else b""
|
||||
self.send_response(self.server.status)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def fast_retries(monkeypatch):
|
||||
DOWNLOAD_CANCELLED.clear()
|
||||
monkeypatch.setattr(dl, "RETRY_WAIT", 0)
|
||||
yield
|
||||
DOWNLOAD_CANCELLED.clear()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def serve():
|
||||
servers: list[_Server] = []
|
||||
|
||||
def start(status):
|
||||
server = _Server(status)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
servers.append(server)
|
||||
return server
|
||||
|
||||
yield start
|
||||
for server in servers:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("make_session", SESSIONS)
|
||||
def test_no_response_failure_gets_the_outage_budget(tmp_path, make_session):
|
||||
port = get_free_port()
|
||||
retried: list[Exception] = []
|
||||
|
||||
with pytest.raises(Exception) as raised:
|
||||
list(
|
||||
dl.download(
|
||||
url=f"http://127.0.0.1:{port}/a",
|
||||
save_path=tmp_path / "a.bin",
|
||||
session=make_session(),
|
||||
on_retry=retried.append,
|
||||
)
|
||||
)
|
||||
|
||||
assert len(retried) == dl.OUTAGE_ATTEMPTS - 1
|
||||
assert any(f"gave up after {dl.OUTAGE_ATTEMPTS} failed attempts" in note for note in raised.value.__notes__)
|
||||
|
||||
|
||||
class _FullDisk:
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.file = open(*args, **kwargs)
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
self.file.close()
|
||||
|
||||
def write(self, data):
|
||||
raise OSError(errno.ENOSPC, "No space left on device")
|
||||
|
||||
|
||||
def test_disk_full_is_not_retried(tmp_path, monkeypatch, serve):
|
||||
server = serve(200)
|
||||
monkeypatch.setattr(dl, "open", _FullDisk, raising=False)
|
||||
with pytest.raises(OSError) as raised:
|
||||
list(dl.download(url=server.url, save_path=tmp_path / "a.bin", session=rq.Session()))
|
||||
|
||||
assert raised.value.errno == errno.ENOSPC
|
||||
assert server.requests == 1
|
||||
assert dl.retries_exhausted(raised.value)
|
||||
|
||||
|
||||
def test_status_failure_keeps_the_normal_budget(tmp_path, serve):
|
||||
server = serve(503)
|
||||
with pytest.raises(Exception):
|
||||
list(dl.download(url=server.url, save_path=tmp_path / "a.bin", session=rq.Session()))
|
||||
|
||||
assert server.requests == dl.MAX_ATTEMPTS
|
||||
|
||||
|
||||
@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, "is_rnet_session", lambda s: isinstance(s, _RecoveringSession))
|
||||
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=session))
|
||||
|
||||
assert save_path.read_bytes() == b"body-bytes"
|
||||
assert session.calls == 8
|
||||
@@ -0,0 +1,88 @@
|
||||
"""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)
|
||||
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)
|
||||
with server.lock:
|
||||
server.served.append(header)
|
||||
if not held and len(server.served) == 7:
|
||||
server.release.set()
|
||||
|
||||
|
||||
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
|
||||
@@ -0,0 +1,51 @@
|
||||
"""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(monkeypatch):
|
||||
monkeypatch.setattr(dl, "is_rnet_session", lambda s: isinstance(s, FakeSession))
|
||||
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)
|
||||
list(dl.download(url="http://127.0.0.1:1/a", save_path=tmp_path / "a.bin", session=session, **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", session)
|
||||
assert session.calls[0]["read_timeout"] == 7
|
||||
@@ -0,0 +1,50 @@
|
||||
"""A segment that fails every attempt reports the attempts and the cause, without the signed URL."""
|
||||
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core.downloaders.requests import download, retries_exhausted
|
||||
from unshackle.core.session import MaxRetriesError, RnetSession, failure_reason
|
||||
|
||||
downloader = sys.modules[download.__module__]
|
||||
|
||||
SIGNED_URL = "https://cdn.example.invalid/dvt2=exp=1~hmac=deadbeef/seg/40_000.mp4a"
|
||||
RNET_BROKEN_PIPE = (
|
||||
f'is_request error: wreq::Error {{ kind: Request, url: "{SIGNED_URL}", source: hyper::Error(Io, '
|
||||
'Custom { kind: BrokenPipe, error: "stream closed because of a broken pipe" }) }'
|
||||
)
|
||||
|
||||
|
||||
class RequestError(Exception):
|
||||
"""Stands in for rnet.RequestError, which carries the URL in its text."""
|
||||
|
||||
|
||||
def test_failure_reason_keeps_the_rnet_error_text_and_drops_the_url():
|
||||
reason = failure_reason(MaxRetriesError("m", cause=RequestError(RNET_BROKEN_PIPE)))
|
||||
|
||||
assert reason == "RequestError (stream closed because of a broken pipe)"
|
||||
|
||||
|
||||
def test_spent_retries_report_one_line_without_the_url(monkeypatch, tmp_path):
|
||||
session = RnetSession()
|
||||
calls = []
|
||||
|
||||
def get(url, **kwargs):
|
||||
calls.append(kwargs.get("max_retries"))
|
||||
raise MaxRetriesError("GET cdn.example.invalid failed: x", cause=RequestError(RNET_BROKEN_PIPE))
|
||||
|
||||
monkeypatch.setattr(session, "get", get)
|
||||
monkeypatch.setattr(downloader, "retry_sleep", lambda exc, attempts: 0)
|
||||
|
||||
with pytest.raises(MaxRetriesError) as raised:
|
||||
for _ in download(url=SIGNED_URL, save_path=tmp_path / "seg", session=session):
|
||||
pass
|
||||
|
||||
assert calls == [0] * downloader.MAX_ATTEMPTS
|
||||
assert retries_exhausted(raised.value)
|
||||
assert not retries_exhausted(ValueError("boom"))
|
||||
header, line = dl.failure_lines(raised.value)
|
||||
assert f"gave up after {downloader.MAX_ATTEMPTS} failed attempts" in line
|
||||
assert "hmac" not in line
|
||||
@@ -0,0 +1,167 @@
|
||||
"""Downloader transport tests that send real requests through both session types.
|
||||
|
||||
Each case runs against a loopback server with a plain requests.Session and with a real RnetSession, so an rnet
|
||||
upgrade that changes how a cut body, a read timeout or a Retry-After header surfaces fails here.
|
||||
"""
|
||||
|
||||
import importlib
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
import pytest
|
||||
import requests as rq
|
||||
|
||||
from unshackle.core.constants import DOWNLOAD_CANCELLED
|
||||
from unshackle.core.session import RnetSession
|
||||
|
||||
dl = importlib.import_module("unshackle.core.downloaders.requests")
|
||||
|
||||
BODY = bytes(range(256)) * 256
|
||||
CUT_AFTER = 10 * 1024
|
||||
CHUNK = 16 * 1024
|
||||
SESSIONS = [pytest.param(rq.Session, id="requests"), pytest.param(RnetSession, id="rnet")]
|
||||
|
||||
|
||||
class _Server(ThreadingHTTPServer):
|
||||
allow_reuse_address = True
|
||||
daemon_threads = True
|
||||
|
||||
def __init__(self):
|
||||
self.hits: list[tuple[str, str | None]] = []
|
||||
self.release = threading.Event()
|
||||
self.lock = threading.Lock()
|
||||
super().__init__(("127.0.0.1", 0), _Handler)
|
||||
self.url = f"http://127.0.0.1:{self.server_address[1]}"
|
||||
|
||||
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):
|
||||
header = self.headers.get("Range")
|
||||
with self.server.lock:
|
||||
first = not any(path == self.path for path, _ in self.server.hits)
|
||||
self.server.hits.append((self.path, header))
|
||||
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]
|
||||
|
||||
if self.path == "/busy" and first:
|
||||
self.send_response(503)
|
||||
self.send_header("Retry-After", "1")
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
return
|
||||
|
||||
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()
|
||||
|
||||
if self.path == "/cut" and len(body) > CUT_AFTER:
|
||||
self.wfile.write(body[:CUT_AFTER])
|
||||
self.close_connection = True
|
||||
return
|
||||
if self.path == "/stall" and first:
|
||||
self.wfile.write(body[:1000])
|
||||
self.wfile.flush()
|
||||
self.server.release.wait(10)
|
||||
self.close_connection = True
|
||||
return
|
||||
self.wfile.write(body)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def server(monkeypatch):
|
||||
DOWNLOAD_CANCELLED.clear()
|
||||
monkeypatch.setattr(dl, "RETRY_WAIT", 0)
|
||||
monkeypatch.setattr(dl, "REQUEST_CHUNK_SIZE", CHUNK)
|
||||
monkeypatch.setattr(dl, "MIN_REQUEST_CHUNK", 4 * 1024)
|
||||
monkeypatch.setattr(dl, "MIN_RESUME_PROGRESS", 1024)
|
||||
server = _Server()
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
yield server
|
||||
server.release.set()
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
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"
|
||||
list(dl.download(url=f"{server.url}/cut", save_path=save_path, session=make_session()))
|
||||
|
||||
assert save_path.read_bytes() == BODY
|
||||
assert server.hits[0][1] is None
|
||||
assert len(server.hits) > 1
|
||||
assert all(r is not None and r.startswith("bytes=") for _, r in server.hits[1:])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("make_session", SESSIONS)
|
||||
def test_retry_after_header_sets_the_wait(tmp_path, server, make_session, monkeypatch):
|
||||
real = dl.retry_sleep
|
||||
waits: list[float] = []
|
||||
|
||||
def spy(exc, attempts):
|
||||
waits.append(real(exc, attempts))
|
||||
return 0
|
||||
|
||||
monkeypatch.setattr(dl, "retry_sleep", spy)
|
||||
save_path = tmp_path / "0.mp4"
|
||||
list(dl.download(url=f"{server.url}/busy", save_path=save_path, session=make_session()))
|
||||
|
||||
assert save_path.read_bytes() == BODY
|
||||
assert len(server.hits) == 2
|
||||
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
|
||||
|
||||
|
||||
def test_complete_file_is_reported_without_a_request(tmp_path, server):
|
||||
save_path = tmp_path / "0.mp4"
|
||||
save_path.write_bytes(b"x" * 10)
|
||||
events = list(dl.download(url=f"{server.url}/plain", save_path=save_path, session=rq.Session()))
|
||||
|
||||
assert server.hits == []
|
||||
assert save_path.read_bytes() == b"x" * 10
|
||||
assert {"file_downloaded": save_path, "written": 10} in events
|
||||
|
||||
|
||||
def test_legacy_layout_restarts_clean(tmp_path, server):
|
||||
save_path = tmp_path / "0.mp4"
|
||||
save_path.write_bytes(b"partial")
|
||||
marker = save_path.with_name(save_path.name + ".!dev")
|
||||
marker.write_bytes(b"")
|
||||
list(dl.download(url=f"{server.url}/plain", save_path=save_path, session=rq.Session()))
|
||||
|
||||
assert save_path.read_bytes() == BODY
|
||||
assert not marker.exists()
|
||||
assert server.hits[0][1] is None
|
||||
@@ -47,7 +47,7 @@ def test_rnet_spec_round_trips_cookie_domains() -> None:
|
||||
rebuilt = rebuild_session(pickle.loads(pickle.dumps(spec)), 1)
|
||||
assert rebuilt is not None
|
||||
|
||||
assert rebuilt.cookies.get_dict_by_domain() == ns.cookies.get_dict_by_domain()
|
||||
assert [vars(c) for c in rebuilt.cookies.snapshot()] == [vars(c) for c in ns.cookies.snapshot()]
|
||||
assert rebuilt.cookies.get_dict() == ns.cookies.get_dict()
|
||||
assert rebuilt.cookies.get("cdn_token", domain="cdn.example.com") == "abc"
|
||||
assert rebuilt.cookies.get("api_token", domain="api.example.com") == "def"
|
||||
@@ -71,17 +71,35 @@ def test_rnet_spec_cookies_carry_domain_information() -> None:
|
||||
spec = build_session_spec(ns)
|
||||
assert spec is not None
|
||||
|
||||
cookies = spec["cookies"]
|
||||
assert set(cookies) == {"cdn.example.com", "api.example.com", ""}
|
||||
assert all(isinstance(jar, dict) for jar in cookies.values())
|
||||
assert cookies["cdn.example.com"] == {"cdn_token": "abc"}
|
||||
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")
|
||||
ns.cookies.set("hdntl", "one", domain=".cdn.example.com", path="/t/1")
|
||||
ns.cookies.set("hdntl", "two", domain=".cdn.example.com", path="/t/2")
|
||||
|
||||
spec = build_session_spec(ns)
|
||||
assert spec is not None
|
||||
rebuilt = rebuild_session(pickle.loads(pickle.dumps(spec)), 1)
|
||||
assert rebuilt is not None
|
||||
|
||||
assert rebuilt.cookies.get("hdntl", path="/t/1") == "one"
|
||||
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
|
||||
|
||||
assert pickle.loads(pickle.dumps(spec)) == spec
|
||||
loaded = pickle.loads(pickle.dumps(spec))
|
||||
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:
|
||||
@@ -191,6 +209,19 @@ def test_requests_spec_carries_verify() -> None:
|
||||
assert rebuilt.verify is False
|
||||
|
||||
|
||||
def test_requests_spec_carries_trust_env() -> None:
|
||||
"""A proxied session ignores env proxies, so a child must not let HTTPS_PROXY win again."""
|
||||
rs = Session()
|
||||
rs.trust_env = False
|
||||
|
||||
spec = build_session_spec(rs)
|
||||
assert spec is not None
|
||||
rebuilt = rebuild_session(pickle.loads(pickle.dumps(spec)), 1)
|
||||
assert rebuilt is not None
|
||||
|
||||
assert rebuilt.trust_env is False
|
||||
|
||||
|
||||
def test_requests_spec_carries_params() -> None:
|
||||
"""Services hold an auth token in session.params; without it every segment request is unauthed."""
|
||||
rs = Session()
|
||||
|
||||
@@ -90,7 +90,19 @@ def test_bucket_holds_aggregate_rate_across_threads():
|
||||
t.join()
|
||||
achieved = sum(totals) / (time.monotonic() - start)
|
||||
assert achieved <= rate * 1.1
|
||||
assert achieved >= rate * 0.5
|
||||
|
||||
|
||||
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]
|
||||
monkeypatch.setattr(requests_downloader, "time", SimpleNamespace(monotonic=lambda: clock[0]))
|
||||
monkeypatch.setattr(
|
||||
requests_downloader, "DOWNLOAD_CANCELLED", SimpleNamespace(wait=lambda s: clock.__setitem__(0, clock[0] + s))
|
||||
)
|
||||
bucket = TokenBucket(1_000)
|
||||
for _ in range(50):
|
||||
bucket.consume(100)
|
||||
assert clock[0] == pytest.approx(5.0)
|
||||
|
||||
|
||||
def test_bucket_chunk_larger_than_capacity_does_not_deadlock(monkeypatch):
|
||||
@@ -104,15 +116,11 @@ def test_bucket_chunk_larger_than_capacity_does_not_deadlock(monkeypatch):
|
||||
|
||||
def test_locked_limit_ignores_unlocked_calls():
|
||||
"""serve's global_speed_limit must survive the per-job set in dl.result()."""
|
||||
try:
|
||||
set_speed_limit(5_000_000, lock=True)
|
||||
set_speed_limit(None)
|
||||
set_speed_limit(1_000_000)
|
||||
limiter = requests_downloader.speed_limiter
|
||||
assert limiter is not None and limiter.rate == 5_000_000
|
||||
finally:
|
||||
requests_downloader.speed_limit_locked = False
|
||||
requests_downloader.speed_limiter = None
|
||||
set_speed_limit(5_000_000, lock=True)
|
||||
set_speed_limit(None)
|
||||
set_speed_limit(1_000_000)
|
||||
limiter = requests_downloader.speed_limiter
|
||||
assert limiter is not None and limiter.rate == 5_000_000
|
||||
|
||||
|
||||
def test_bucket_wait_aborts_on_cancellation():
|
||||
|
||||
Reference in New Issue
Block a user