mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-05 07:25:08 +00:00
refactor(downloader): put one transport adapter per HTTP session kind under download()
This commit is contained in:
@@ -147,12 +147,11 @@ 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])
|
||||
list(download(url="http://127.0.0.1:1/sub.vtt", save_path=save_path, session=session))
|
||||
list(download(url="http://127.0.0.1:1/sub.vtt", save_path=save_path, session=dl.RnetTransport(session)))
|
||||
# the encoded 206 must be dropped, not appended; the clean restart fetches the whole body
|
||||
assert session.range_requests == 1
|
||||
assert save_path.read_bytes() == PLAIN
|
||||
|
||||
@@ -170,12 +170,11 @@ class _RecoveringSession:
|
||||
|
||||
|
||||
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))
|
||||
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
|
||||
|
||||
@@ -23,8 +23,7 @@ class FakeSession:
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def session(monkeypatch):
|
||||
monkeypatch.setattr(dl, "is_rnet_session", lambda s: isinstance(s, FakeSession))
|
||||
def session():
|
||||
return FakeSession()
|
||||
|
||||
|
||||
@@ -41,11 +40,12 @@ def test_segment_request_read_timeout(tmp_path, session, monkeypatch, network, m
|
||||
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))
|
||||
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", session)
|
||||
dl.probe_ranged("http://127.0.0.1:1/a", dl.RnetTransport(session))
|
||||
assert session.calls[0]["read_timeout"] == 7
|
||||
|
||||
@@ -145,6 +145,18 @@ def test_stalled_body_times_out_and_retries(tmp_path, server, make_session, monk
|
||||
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"})
|
||||
try:
|
||||
assert body.status_code == 206
|
||||
assert body.header("content-range") == body.header("CONTENT-RANGE") == f"bytes 0-9/{len(BODY)}"
|
||||
assert body.content_length == 10
|
||||
assert b"".join(body.chunks(4, None)) == BODY[:10]
|
||||
finally:
|
||||
body.close()
|
||||
|
||||
|
||||
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)
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Each session kind's transport switches session retries and the request record off, and reads the body its own way."""
|
||||
|
||||
import importlib
|
||||
import io
|
||||
|
||||
import pytest
|
||||
import requests as rq
|
||||
|
||||
from unshackle.core.session import RnetSession
|
||||
|
||||
dl = importlib.import_module("unshackle.core.downloaders.requests")
|
||||
|
||||
|
||||
class _Response:
|
||||
def __init__(self, headers=None, body=b"abcdef"):
|
||||
self.status_code = 200
|
||||
self.headers = rq.structures.CaseInsensitiveDict(headers or {})
|
||||
self.raw = _Raw(body)
|
||||
self.body = body
|
||||
self.content_length = len(body)
|
||||
|
||||
def raise_for_status(self):
|
||||
pass
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
def iter_content(self, chunk_size):
|
||||
yield self.body
|
||||
|
||||
|
||||
class _Raw(io.BytesIO):
|
||||
def __init__(self, body):
|
||||
super().__init__(body)
|
||||
self.calls: list[str] = []
|
||||
|
||||
def read(self, size=-1):
|
||||
self.calls.append("read")
|
||||
return super().read(size)
|
||||
|
||||
def read1(self, size=-1):
|
||||
self.calls.append("read1")
|
||||
return super().read1(size)
|
||||
|
||||
|
||||
class _Session:
|
||||
def __init__(self, response=None):
|
||||
self.calls: list[dict] = []
|
||||
self.response = response or _Response()
|
||||
|
||||
def get(self, url, **kwargs):
|
||||
self.calls.append(kwargs)
|
||||
return self.response
|
||||
|
||||
|
||||
def test_each_session_kind_gets_its_transport():
|
||||
assert isinstance(dl.transport_for(RnetSession()), dl.RnetTransport)
|
||||
assert isinstance(dl.transport_for(rq.Session()), dl.RequestsTransport)
|
||||
transport = dl.RnetTransport(_Session())
|
||||
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)
|
||||
assert body.content_encoded
|
||||
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)
|
||||
Reference in New Issue
Block a user