mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-24 09:55:12 +00:00
fix(downloader): outlast network outages and harden segment merges
Outage-only retry budget, fail fast on a full disk, rnet read_timeout from config, fixed-size shared range parts, Windows-safe segment deletes, merge benchmark.
This commit is contained in:
@@ -138,3 +138,49 @@ def test_cleanup_never_climbs_past_the_segment_store(tmp_path: Path, monkeypatch
|
||||
assert keep.exists(), "cleanup deleted an unrelated file in the download directory"
|
||||
assert library.exists()
|
||||
assert not (library / "temp" / "task_x" / "Audio_1.mp4_segments").exists(), "the segment store was left behind"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ffmpeg_ok(monkeypatch: pytest.MonkeyPatch) -> list[dict]:
|
||||
"""Patch in an ffmpeg that writes b"merged" and succeeds; gives the kwargs of each call."""
|
||||
calls: list[dict] = []
|
||||
|
||||
def fake_run(args, **kwargs):
|
||||
calls.append(kwargs)
|
||||
Path(args[-1]).write_bytes(b"merged")
|
||||
return subprocess.CompletedProcess(args, 0, "", "")
|
||||
|
||||
monkeypatch.setattr("unshackle.core.manifests.hls.binaries.FFMPEG", Path("ffmpeg"))
|
||||
monkeypatch.setattr("unshackle.core.manifests.hls.subprocess.run", fake_run)
|
||||
return calls
|
||||
|
||||
|
||||
def test_segment_delete_error_after_ffmpeg_success_keeps_the_output(
|
||||
tmp_path: Path, segments: list[Path], ffmpeg_ok: list[dict], monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
real_unlink = Path.unlink
|
||||
|
||||
def locked_unlink(self, *args, **kwargs):
|
||||
if self == segments[1]:
|
||||
raise PermissionError(13, "The process cannot access the file", str(self))
|
||||
return real_unlink(self, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(Path, "unlink", locked_unlink)
|
||||
|
||||
save_path = tmp_path / "out.mp4"
|
||||
size = HLS.merge_segments(segments=segments, save_path=save_path)
|
||||
|
||||
assert size == len(b"merged")
|
||||
assert save_path.read_bytes() == b"merged"
|
||||
|
||||
|
||||
def test_ffmpeg_timeout_grows_with_input_size(tmp_path: Path, segments: list[Path], ffmpeg_ok: list[dict]) -> None:
|
||||
HLS.merge_segments(segments=segments, save_path=tmp_path / "small.mp4")
|
||||
|
||||
segments[0].parent.mkdir(exist_ok=True)
|
||||
for i, path in enumerate(segments):
|
||||
path.write_bytes(f"segment-{i}".encode())
|
||||
segments[0].write_bytes(b"\0" * 10 * 1024 * 1024)
|
||||
HLS.merge_segments(segments=segments, save_path=tmp_path / "large.mp4")
|
||||
|
||||
assert [call["timeout"] for call in ffmpeg_ok] == [300, 302]
|
||||
|
||||
@@ -20,6 +20,7 @@ real spawns stay fast.
|
||||
|
||||
import importlib
|
||||
import multiprocessing
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
@@ -98,6 +99,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}"
|
||||
|
||||
@@ -127,20 +149,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):
|
||||
|
||||
@@ -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,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
|
||||
Reference in New Issue
Block a user