Bulk asynchronous downloader for multiple file hosts
Python asynciobunkrcyberdropdownloaderdropboxfilestergofilegoogle-drivemediafiremegamega-nzonedrivepatreonpawchivepinterestpixeldraintransfer-ittwitchtwittervk
test: add test cases script (#2048)
NTFSvolume1df83f8a8138
diff --git a/scripts/tools/__init__.py b/scripts/tools/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/scripts/tools/test_crawlers.py b/scripts/tools/test_crawlers.pynew file mode 100644index 000000000..b453155f8--- /dev/null+++ b/scripts/tools/test_crawlers.py@@ -0,0 +1,70 @@+import logging++from cyclopts import App+from cyclopts.help import DefaultFormatter++from cyberdrop_dl import __version__+from cyberdrop_dl.constants import DEFAULT_PARAMETER+from cyberdrop_dl.logs import setup_console_logging++logger = logging.getLogger("cyberdrop_dl")++app = App(+ name="cyberdrop-dl crawler tester",+ version=__version__,+ default_parameter=DEFAULT_PARAMETER,+ help_format="rich",+ result_action="return_value",+ help_formatter=DefaultFormatter().with_newline_metadata(), # pyright: ignore[reportUnknownMemberType]+)+++def _cases():+ logger.info("Loading test cases ...")+ from tests.crawlers.test_crawlers import test_cases++ return test_cases+++def _crawlers():+ logger.info("Importing crawlers ...")+ from cyberdrop_dl.crawlers import Registry++ return Registry.get_crawlers()++[email protected](name="list")+def list_cases() -> None:+ "Show a map with all existing test cases"++ all_cases = sorted(_cases().load_cases().items())+ cases = {domain: len(module.cases) for domain, module in all_cases}+ app.console.print(cases)+ app.console.print("Domains:", len(cases), " Cases:", sum(cases.values()))+++def missing() -> None:+ "Show a list a crawlers with 0 test cases"++ crawlers = tuple(_crawlers())+ test_domains = set(_cases().load_cases())+ missing = sorted(c.__module__ for c in crawlers if c.DOMAIN not in test_domains)+ app.console.print(missing)+ app.console.print(f"Total: {len(missing)} ({100 * len(missing) / len(crawlers):0.2f} %)")+++def orphan() -> None:+ "Show a list of test cases that match with no crawler"++ domains = {c.DOMAIN for c in _crawlers()}+ test_modules = set(_cases().load_modules())+ orphan = dict(sorted((m.domain, m.file) for m in test_modules if m.domain not in domains))+ app.console.print(orphan)+ app.console.print(f"Total: {len(orphan)}")+++if __name__ == "__main__":+ with setup_console_logging():+ app()diff --git a/tests/__init__.py b/tests/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/crawlers/test_cases/__init__.py b/tests/crawlers/test_cases/__init__.pyindex 486491173..81a6b6481 100644--- a/tests/crawlers/test_cases/__init__.py+++ b/tests/crawlers/test_cases/__init__.py@@ -1,15 +1,11 @@-from __future__ import annotations-import dataclassesimport runpy+from collections.abc import Generator, Sequencefrom pathlib import Path-from typing import TYPE_CHECKING, Any, NotRequired, TypedDict+from typing import Any, NotRequired, TypedDictfrom pydantic import TypeAdapter-if TYPE_CHECKING:- from collections.abc import Sequence-class Result(TypedDict):# Simplified version of media_item@@ -41,28 +37,43 @@ class CrawlerTestCase:return f"{self.domain} - {self.url}"-type TestData = dict[str, list[dict[str, Any]]]+type TestData = dict[str, TestCaseModule]_TEST_CASE_ADAPTER = TypeAdapter(CrawlerTestCase)-def load_cases() -> TestData:- test_data: TestData = {}[email protected](slots=True, frozen=True, order=True)+class TestCaseModule:+ domain: str+ file: Path+ cases: list[dict[str, Any]] = dataclasses.field(hash=False)+++def load_modules() -> Generator[TestCaseModule]:for file in (Path(__file__).parent).iterdir():if not file.name.startswith("_") and file.suffix == ".py":module_globals = runpy.run_path(str(file), run_name=file.stem)- if (domain := module_globals["DOMAIN"]) in test_data:- raise RuntimeError(f"Multiple tests files for {domain}")- test_data[domain] = module_globals["TEST_CASES"]+ yield TestCaseModule(module_globals["DOMAIN"], file, module_globals["TEST_CASES"])+++def load_cases() -> TestData:+ test_data: TestData = {}+ for module in load_modules():+ if module.domain in test_data:+ raise RuntimeError(+ f"Multiple tests files for {module.domain}: {(module.file, test_data[module.domain].file)}"+ )++ test_data[module.domain] = modulereturn test_datadef parse_cases(data: TestData) -> list[CrawlerTestCase]:test_cases: list[CrawlerTestCase] = []- for domain, cases in sorted(data.items()):- test_cases.extend(_TEST_CASE_ADAPTER.validate_python({"domain": domain} | case) for case in cases)+ for domain, module in sorted(data.items()):+ test_cases.extend(_TEST_CASE_ADAPTER.validate_python({"domain": domain} | case) for case in module.cases)return test_casesdiff --git a/tests/crawlers/test_cases/e621_net.py b/tests/crawlers/test_cases/e621_net.pyindex 6f9cc475d..d3f9a66bf 100644--- a/tests/crawlers/test_cases/e621_net.py+++ b/tests/crawlers/test_cases/e621_net.py@@ -1,4 +1,4 @@-DOMAIN = "e621_net"+DOMAIN = "e621.net"TEST_CASES = [{"url": "https://e621.net/posts/6409634",diff --git a/tests/crawlers/test_cases/efukt.py b/tests/crawlers/test_cases/efukt.pyindex 4e3fe5e8f..8fef2a4e2 100644--- a/tests/crawlers/test_cases/efukt.py+++ b/tests/crawlers/test_cases/efukt.py@@ -1,4 +1,4 @@-DOMAIN = "efukt_com"+DOMAIN = "efukt.com"TEST_CASES = [{"url": "https://efukt.com/24528_That_One_Friend.html",diff --git a/tests/crawlers/test_cases/safe_soul_lol.py b/tests/crawlers/test_cases/safe_soul_lol.pydeleted file mode 100644index ed55cf0cf..000000000--- a/tests/crawlers/test_cases/safe_soul_lol.py+++ /dev/null@@ -1,44 +0,0 @@-DOMAIN = "safe.soul.lol"-TEST_CASES = [- {- "url": "https://safe.soul.lol/GGCW62sr.dat",- "results": [- {- "url": "https://safe.soul.lol/GGCW62sr.dat",- "filename": "GGCW62sr.dat",- "referer": "https://safe.soul.lol/GGCW62sr.dat",- "album_id": None,- "uploaded_at": None,- }- ],- },- {- "url": "https://safe.soul.lol/a/fH8aoyxD",- "results": [- {- "url": "https://safe.soul.lol/GGCW62sr.dat",- "filename": "GGCW62sr.dat",- "referer": "https://safe.soul.lol/GGCW62sr.dat",- "album_id": "fH8aoyxD",- "uploaded_at": 1757997917,- "download_folder": "re:cdl_test \\(Safe\\.Soul\\)",- },- {- "url": "https://safe.soul.lol/rQPLKGeA.zip",- "filename": "rQPLKGeA.zip",- "referer": "https://safe.soul.lol/rQPLKGeA.zip",- "album_id": "fH8aoyxD",- "uploaded_at": 1757997915,- "download_folder": "re:cdl_test \\(Safe\\.Soul\\)",- },- {- "url": "https://safe.soul.lol/8WXnedx1.bin",- "filename": "8WXnedx1.bin",- "referer": "https://safe.soul.lol/8WXnedx1.bin",- "album_id": "fH8aoyxD",- "uploaded_at": 1757997914,- "download_folder": "re:cdl_test \\(Safe\\.Soul\\)",- },- ],- },-]diff --git a/tests/crawlers/test_crawlers.py b/tests/crawlers/test_crawlers.pyindex 37d8a8b87..ba866a981 100644--- a/tests/crawlers/test_crawlers.py+++ b/tests/crawlers/test_crawlers.py@@ -217,10 +217,11 @@ def test_load_test_data() -> None:test_data = test_cases.load_cases()assert len(test_data) > 20assert "dropbox" in test_data- assert type(test_data["dropbox"]) is list- assert len(test_data["dropbox"]) == 4+ dropbox = test_data["dropbox"]+ assert type(dropbox) is test_cases.TestCaseModule+ assert len(dropbox.cases) == 4- for case in test_data["dropbox"]:+ for case in dropbox.cases:assert type(case) is dictassert "url" in casediff --git a/tests/test_cache.py b/tests/test_cache.pyindex c619cec94..1506bc4cb 100644--- a/tests/test_cache.py+++ b/tests/test_cache.py@@ -113,6 +113,10 @@ def test_invalid_cache(logs: pytest.LogCaptureFixture) -> None:assert logs.messages == ["Invalid cache entry a.b, ignoring"]+def local_cache() -> dict[str, Any]:+ return _IN_MEMORY_CACHE["tests"]["test_cache"]++async def test_cache_fn() -> None:call = 0@@ -135,7 +139,7 @@ async def test_cache_fn() -> None:assert await fn2() == 2await asyncio.sleep(0.2 + 0.1)assert await fn2() == 3- assert _IN_MEMORY_CACHE["test_cache"]["test_cache_fn"]["<locals>"] == {+ assert local_cache()["test_cache_fn"]["<locals>"] == {"update": {"value": 1,"ttl": None,@@ -148,7 +152,7 @@ async def test_cache_fn() -> None:},}fn.clear()- assert "update" not in _IN_MEMORY_CACHE["test_cache"]["test_cache_fn"]["<locals>"]+ assert "update" not in local_cache()["test_cache_fn"]["<locals>"]assert await fn() == 4