implement resume downloading

This commit is contained in:
Meghdad committed 2026-08-02 22:02:42 +03:30
1 parent 187878a774
commit a3acea6457
4 files changed
+201 -34

No files matched your search

+70
View File
@@ -1,4 +1,5 @@
import email.message
import http.client
import os
import tempfile
import unittest
@@ -6,6 +7,7 @@ from pathlib import Path
from ravin_downloader import (
FileItem,
MoodleClient,
_FormParser,
_LinkParser,
_clean_name,
@@ -18,6 +20,47 @@ from ravin_downloader import (
)
class _FakeResponse:
def __init__(self, chunks, *, status=200, content_range=""):
self.chunks = list(chunks)
self.status = status
self.headers = email.message.Message()
self.headers["Content-Disposition"] = 'attachment; filename="file.bin"'
if content_range:
self.headers["Content-Range"] = content_range
def __enter__(self):
return self
def __exit__(self, *_args):
return False
def getcode(self):
return self.status
def geturl(self):
return "https://training.example/pluginfile.php/file.bin"
def read(self, _size):
if not self.chunks:
return b""
value = self.chunks.pop(0)
if isinstance(value, BaseException):
raise value
return value
class _FakeDownloadClient(MoodleClient):
def __init__(self, responses):
super().__init__("https://training.example")
self.responses = list(responses)
self.request_headers = []
def _request(self, _path_or_url, *, data=None, headers=None, timeout=45):
self.request_headers.append(headers or {})
return self.responses.pop(0)
class ParserTests(unittest.TestCase):
def test_parses_login_form_and_hidden_token(self):
parser = _FormParser()
@@ -83,6 +126,33 @@ class ParserTests(unittest.TestCase):
)
self.assertEqual(os.stat(path).st_mode & 0o777, 0o600)
def test_interrupted_download_retries_with_range(self):
first = _FakeResponse(
[
b"abcde",
http.client.IncompleteRead(b"xyz", 2),
]
)
second = _FakeResponse([b"!!"], status=206, content_range="bytes 8-9/10")
client = _FakeDownloadClient([first, second])
item = FileItem(44, "Course files", "Lesson", "file.bin", "https://training.example/file.bin")
with tempfile.TemporaryDirectory() as directory:
destination = client.download(item, Path(directory), retries=1, retry_delay=0)
self.assertEqual(destination.read_bytes(), b"abcdexyz!!")
self.assertEqual(client.request_headers, [{}, {"Range": "bytes=8-"}])
def test_existing_partial_download_is_resumed(self):
response = _FakeResponse([b"67890"], status=206, content_range="bytes 5-9/10")
client = _FakeDownloadClient([response])
item = FileItem(44, "Course files", "Lesson", "file.bin", "https://training.example/file.bin")
with tempfile.TemporaryDirectory() as directory:
partial = Path(directory) / "44" / "Course files" / "file.bin.part"
partial.parent.mkdir(parents=True)
partial.write_bytes(b"12345")
destination = client.download(item, Path(directory), retries=0, retry_delay=0)
self.assertEqual(destination.read_bytes(), b"1234567890")
self.assertEqual(client.request_headers, [{"Range": "bytes=5-"}])
if __name__ == "__main__":
unittest.main()