testsAndMisc/python_pkg/wsg_grabber/tests/test_downloader_part2.py
Krzysztof kuhy Rudnicki 4b2cd0c398 Clear the wsg_grabber test modules: python_pkg is now under the cap
The last six over-cap files split into eleven new modules, in two passes
since the first cut left five still over. python_pkg has no violations
left at all, down from 50 when this effort started.

Each split carries the whole preamble including the module's pytest
fixtures - started, toolkit and session are taken as parameters and
resolve lexically, so a hand-written import block would have missed
them. ruff then pruned 82 unused imports.

Pass count is 277 before and after, checked after both passes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w2Pj4Ek3ZNMQVYcFHgXDY
2026-08-16 18:19:26 +02:00

180 lines
4.9 KiB
Python

"""More tests for the background worker.
Split from test_downloader.py to stay under this repo's 500-line-per-file cap;
the fixtures are duplicated because each test module must stand alone.
"""
from __future__ import annotations
import queue
import threading
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
import pytest
from python_pkg.wsg_grabber import db, downloader, net, store
from python_pkg.wsg_grabber.models import (
DownloadEvent,
DownloadResult,
JsonResponse,
Outcome,
RemoteFile,
ThreadRef,
)
from python_pkg.wsg_grabber.states import FileState
if TYPE_CHECKING:
from collections.abc import Iterator
from pathlib import Path
_MD5 = "Nz9OEKdMuMZEdYE6eLTKmA=="
_BODY = b"video bytes"
@pytest.fixture
def deps(tmp_path: Path) -> Iterator[downloader.WorkerDeps]:
"""Build worker dependencies backed by a sandboxed index.
Args:
tmp_path: Per-test temporary directory.
Yields:
downloader.WorkerDeps: Ready dependencies; resources closed after.
"""
incoming = tmp_path / "incoming"
incoming.mkdir()
conn = db.open_index(tmp_path / "index.db")
session = MagicMock()
built = downloader.WorkerDeps(
conn=conn,
session=session,
incoming=incoming,
events=queue.SimpleQueue(),
stop=threading.Event(),
include_archive=False,
)
try:
yield built
finally:
conn.close()
def _json(
payload: object,
*,
last_modified: str | None = None,
not_modified: bool = False,
not_found: bool = False,
) -> JsonResponse:
"""Build a JsonResponse with sensible defaults.
Args:
payload: Decoded body.
last_modified: Header value the response carried.
not_modified: Whether the server answered 304.
not_found: Whether the thread has gone.
Returns:
JsonResponse: Response double.
"""
return JsonResponse(
payload=payload,
last_modified=last_modified,
not_modified=not_modified,
not_found=not_found,
)
def _remote(md5: str = _MD5, tim: int = 1) -> RemoteFile:
"""Build a RemoteFile.
Args:
md5: Identity.
tim: CDN stem.
Returns:
RemoteFile: Fixture value.
"""
return RemoteFile(
md5=md5,
tim=tim,
ext=".webm",
orig_name="clip",
fsize=len(_BODY),
width=480,
height=360,
thread_no=7,
post_no=tim,
)
def _drain(events: queue.SimpleQueue[DownloadEvent]) -> list[DownloadEvent]:
"""Pull everything currently queued.
Args:
events: Queue to empty.
Returns:
list[DownloadEvent]: Events in order.
"""
out: list[DownloadEvent] = []
while not events.empty():
out.append(events.get_nowait())
return out
def test_download_progress_is_persisted(deps: downloader.WorkerDeps) -> None:
worker = downloader.Worker(deps)
store.record_files(deps.conn, [_remote()])
def fake_download(_session: object, transfer: net.Transfer) -> DownloadResult:
assert transfer.on_progress is not None
transfer.on_progress(7)
return DownloadResult(outcome=Outcome.ABORTED, bytes_done=7)
with patch.object(net, "download", side_effect=fake_download):
worker.run_once()
assert deps.conn.execute("SELECT bytes_done FROM files").fetchone()[0] == 7
def test_claim_losing_a_race_is_a_no_op(deps: downloader.WorkerDeps) -> None:
worker = downloader.Worker(deps)
store.record_files(deps.conn, [_remote()])
with (
patch.object(store, "claim_next", return_value=None),
patch.object(
net,
"download",
) as never,
):
worker._download_one()
never.assert_not_called()
def test_deleted_upstream_files_are_written_off(
deps: downloader.WorkerDeps,
) -> None:
worker = downloader.Worker(deps)
store.record_files(deps.conn, [_remote()])
thread = {"posts": [{"no": 1, "md5": _MD5, "filedeleted": 1}]}
# Driven directly: with a file queued, run_once would always pick DOWNLOAD
# over SCAN, so the thread fetch under test would never happen.
with patch.object(net, "get_json", return_value=_json(thread)):
worker._fetch_thread(ThreadRef(7, 100))
assert store.counts(deps.conn)[FileState.GONE.value] == 1
assert store.pending_downloads(deps.conn) == 0
def test_an_already_downloaded_file_survives_upstream_deletion(
deps: downloader.WorkerDeps,
) -> None:
"""Once the bytes are ours, the post being deleted is irrelevant."""
worker = downloader.Worker(deps)
store.record_files(deps.conn, [_remote()])
store.mark_downloaded(deps.conn, _MD5, "1-x.webm")
thread = {"posts": [{"no": 1, "md5": _MD5, "filedeleted": 1}]}
with patch.object(net, "get_json", return_value=_json(thread)):
worker._fetch_thread(ThreadRef(7, 100))
assert store.state_of(deps.conn, _MD5) is FileState.READY