Skip to content

Bulk asynchronous downloader for multiple file hosts

refactor: simplify apprise notifications (#119)

NTFSvolume34af880b1078
diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml
index 1687e3fe2..46a717fe4 100644
--- a/.github/workflows/ci.yaml
+++ b/.github/workflows/ci.yaml
@@ -55,4 +55,4 @@ jobs:
- name: Run pytest
timeout-minutes: 10
run: |
- uv run pytest -v --cov --ignore=tests/test_apprise.py
+ uv run pytest -v --cov
diff --git a/cyberdrop_dl/__init__.py b/cyberdrop_dl/__init__.py
index 5e0d4d552..084c577f2 100644
--- a/cyberdrop_dl/__init__.py
+++ b/cyberdrop_dl/__init__.py
@@ -3,5 +3,4 @@ import sys
_ = sys.path.pop(0)
-
__version__ = importlib.metadata.version("cyberdrop-dl-patched")
diff --git a/cyberdrop_dl/__main__.py b/cyberdrop_dl/__main__.py
index 143457d27..b9f067f92 100644
--- a/cyberdrop_dl/__main__.py
+++ b/cyberdrop_dl/__main__.py
@@ -1,6 +1,5 @@
from __future__ import annotations
-import contextlib
import logging
import sys
from typing import TYPE_CHECKING
@@ -11,8 +10,7 @@ from cyberdrop_dl import aio, storage, webhook
from cyberdrop_dl.managers.manager import Manager
from cyberdrop_dl.scraper.scrape_mapper import ScrapeMapper
from cyberdrop_dl.ui import program_ui
-from cyberdrop_dl.updates import check_latest_pypi
-from cyberdrop_dl.utils.apprise import send_apprise_notifications
+from cyberdrop_dl.utils import apprise, check_latest_pypi
from cyberdrop_dl.utils.logger import log_spacer, setup_logging
from cyberdrop_dl.utils.sorting import Sorter
from cyberdrop_dl.utils.utilities import check_partials_and_empty_folders
@@ -43,7 +41,7 @@ async def _scrape(manager: Manager) -> None:
stats = manager.progress_manager.print_stats(start_time)
log_spacer()
- check_latest_pypi()
+ await check_latest_pypi()
log_spacer()
logger.info("Closing program...")
logger.info("Finished downloading. Enjoy :)", extra={"color": "green"})
@@ -51,7 +49,8 @@ async def _scrape(manager: Manager) -> None:
if manager.config.logs.webhook:
await webhook.send_notification(manager.config.logs.webhook, stats)
- await send_apprise_notifications(manager)
+ if manager.config_manager.apprise_urls:
+ await apprise.send_notifications(manager.config_manager.apprise_urls, stats)
async def _runtime(manager: Manager) -> None:
@@ -85,22 +84,19 @@ async def _run(manager: Manager) -> None:
await manager.close()
-def main(args: Sequence[str] | None = None) -> str | int | None:
+def main(args: Sequence[str] | None = None) -> int:
manager = Manager(args)
manager.startup()
if not manager.parsed_args.cli_only_args.download:
program_ui.run(manager)
- exit_code = 1
- with contextlib.suppress(Exception):
- try:
- aio.run(_run(manager))
- except KeyboardInterrupt:
- logger.info("Exiting (Ctrl + C) ...")
+ try:
+ aio.run(_run(manager))
- exit_code = 0
+ except KeyboardInterrupt:
+ logger.info("Exiting (Ctrl + C) ...")
- return exit_code
+ return 0
if __name__ == "__main__":
diff --git a/cyberdrop_dl/clients/__init__.py b/cyberdrop_dl/clients/__init__.py
index d4dfb441e..4d86764c5 100644
--- a/cyberdrop_dl/clients/__init__.py
+++ b/cyberdrop_dl/clients/__init__.py
@@ -103,7 +103,13 @@ class HTTPClient:
request_params.setdefault("max_redirects", 8)
request_id = str(uuid.uuid4())
- logger.debug("Starting {} request to {} [id={}]\n{}", method, url, request_id, request_params)
+ logger.debug(
+ "Starting {} request to {} [id={}]\n{}",
+ method,
+ url,
+ request_id,
+ request_params | {"headers": dict(headers)},
+ )
async with self.__request(url, method, request_params, impersonate=bool(impersonate)) as resp:
exc = None
diff --git a/cyberdrop_dl/clients/response.py b/cyberdrop_dl/clients/response.py
index 1770756c9..e6fa367da 100644
--- a/cyberdrop_dl/clients/response.py
+++ b/cyberdrop_dl/clients/response.py
@@ -84,7 +84,6 @@ class AbstractResponse(ABC, Generic[_ResponseT]):
return {
"url": str(self.url),
- "location": str(self.location) if self.location else None,
"status_code": self.status,
"created_at": str(self.created_at),
"response_headers": dict(self.headers),
diff --git a/cyberdrop_dl/config/__init__.py b/cyberdrop_dl/config/__init__.py
index 5f62b6836..0e544e4fb 100755
--- a/cyberdrop_dl/config/__init__.py
+++ b/cyberdrop_dl/config/__init__.py
@@ -7,7 +7,7 @@ from time import sleep
from typing import TYPE_CHECKING
from cyberdrop_dl import constants, env
-from cyberdrop_dl.utils.apprise import get_apprise_urls
+from cyberdrop_dl.utils.apprise import read_apprise_urls
from .auth_model import AuthSettings
from .config_model import ConfigSettings
@@ -15,7 +15,7 @@ from .global_model import GlobalSettings
if TYPE_CHECKING:
from cyberdrop_dl.cli import ParsedArgs
- from cyberdrop_dl.utils.apprise import AppriseURL
+ from cyberdrop_dl.models import AppriseURL
__all__ = [
"AuthSettings",
@@ -84,7 +84,7 @@ class Config:
auth: AuthSettings
settings: ConfigSettings
global_settings: GlobalSettings
- apprise_urls: list[AppriseURL]
+ apprise_urls: tuple[AppriseURL, ...]
def __init__(self, name: str) -> None:
self.apprise_urls = []
@@ -103,7 +103,7 @@ class Config:
self.auth = auth
self.settings = settings
self.global_settings = global_settings
- self.apprise_urls = get_apprise_urls(file=self.apprise_file)
+ self.apprise_urls = read_apprise_urls(self.apprise_file)
return self
@staticmethod
@@ -120,7 +120,7 @@ class Config:
self.auth = AuthSettings.load_file(self.auth_config_file, "socialmediagirls_username:")
self.settings = ConfigSettings.load_file(self.config_file, "download_error_urls_filename:")
self.global_settings = GlobalSettings.load_file(appdata.global_config_file, "Dupe_Cleanup_Options:")
- self.apprise_urls = get_apprise_urls(file=self.apprise_file)
+ self.apprise_urls = read_apprise_urls(self.apprise_file)
def _resolve_all_paths(self) -> None:
self.settings.resolve_paths()
diff --git a/cyberdrop_dl/dependencies/__init__.py b/cyberdrop_dl/dependencies/__init__.py
index 3b2dd32cf..e69de29bb 100644
--- a/cyberdrop_dl/dependencies/__init__.py
+++ b/cyberdrop_dl/dependencies/__init__.py
@@ -1,12 +0,0 @@
-from typing import TYPE_CHECKING
-
-if TYPE_CHECKING:
- import apprise
-
-else:
- try:
- import apprise
- except ImportError:
- apprise = None
-
-__all__ = ["apprise"]
diff --git a/cyberdrop_dl/managers/config_manager.py b/cyberdrop_dl/managers/config_manager.py
index a81ad21c3..d00e2c943 100644
--- a/cyberdrop_dl/managers/config_manager.py
+++ b/cyberdrop_dl/managers/config_manager.py
@@ -7,7 +7,7 @@ from typing import TYPE_CHECKING
from cyberdrop_dl import yaml
from cyberdrop_dl.config import AuthSettings, ConfigSettings, GlobalSettings
from cyberdrop_dl.exceptions import InvalidYamlError
-from cyberdrop_dl.utils.apprise import get_apprise_urls
+from cyberdrop_dl.utils.apprise import read_apprise_urls
if TYPE_CHECKING:
from pydantic import BaseModel
@@ -25,7 +25,7 @@ class ConfigManager:
self.settings: Path = field(init=False)
self.global_settings: Path = field(init=False)
self.deep_scrape: bool = False
- self.apprise_urls: list[AppriseURL] = []
+ self.apprise_urls: tuple[AppriseURL, ...] = []
self.authentication_data: AuthSettings = field(init=False)
self.settings_data: ConfigSettings = field(init=False)
@@ -52,7 +52,7 @@ class ConfigManager:
self._load_global_settings_config()
self._load_settings_config()
self.apprise_file = self.manager.appdata.configs / self.loaded_config / "apprise.txt"
- self.apprise_urls = get_apprise_urls(file=self.apprise_file)
+ self.apprise_urls = read_apprise_urls(self.apprise_file)
@staticmethod
def get_model_fields(model: BaseModel, *, exclude_unset: bool = True) -> set[str]:
diff --git a/cyberdrop_dl/managers/logs.py b/cyberdrop_dl/managers/logs.py
index 99ecc48e3..e37487b9d 100644
--- a/cyberdrop_dl/managers/logs.py
+++ b/cyberdrop_dl/managers/logs.py
@@ -67,7 +67,13 @@ class LogManager:
if self._ready:
return
for path in self.files:
- path.unlink(missing_ok=True)
+ try:
+ path.unlink()
+ except FileNotFoundError:
+ pass
+ else:
+ logger.warning(f"Deleted conflicting old log file: '{path}'")
+
self._ready = True
async def write_jsonl(self, data: Iterable[dict[str, Any]]) -> None:
diff --git a/cyberdrop_dl/updates.py b/cyberdrop_dl/updates.py
deleted file mode 100644
index afbcd5342..000000000
--- a/cyberdrop_dl/updates.py
+++ /dev/null
@@ -1,35 +0,0 @@
-from __future__ import annotations
-
-import logging
-from typing import Any
-
-import requests
-
-from cyberdrop_dl import __version__ as current
-
-_PYPI_JSON_URL = "https://pypi.org/pypi/cyberdrop-dl-patched/json"
-logger = logging.getLogger(__name__)
-
-
-def check_latest_pypi() -> None:
- logger.info("Checking for updates...")
- try:
- with requests.request("GET", _PYPI_JSON_URL) as response:
- contents = response.json()
-
- except Exception as e:
- logger.error(f"Unable to get latest version information {e!r}")
- else:
- _parse_pypi_resp(contents)
-
-
-def _parse_pypi_resp(data: dict[str, Any]) -> None:
- latest: str = data["info"]["version"]
- releases: set[str] = set(data["releases"])
-
- if current not in releases:
- logger.warning(f"You are using an unreleased version of CDL: {current}. Latest stable release {latest}")
- elif current == latest:
- logger.info(f"You are using an latest version of CDL: {current}")
- else:
- logger.warning(f"A new version is available: {latest}")
diff --git a/cyberdrop_dl/utils/__init__.py b/cyberdrop_dl/utils/__init__.py
index e69de29bb..ca4033b17 100644
--- a/cyberdrop_dl/utils/__init__.py
+++ b/cyberdrop_dl/utils/__init__.py
@@ -0,0 +1,45 @@
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+import aiohttp
+
+from cyberdrop_dl import __version__ as current
+
+_PYPI_JSON_URL = "https://pypi.org/pypi/cyberdrop-dl-patched/json"
+log = logging.getLogger(__name__)
+
+
+async def check_latest_pypi() -> None:
+ log.info("Checking for updates...")
+ try:
+ contents = await _request_pypi_info()
+
+ except Exception as e:
+ log.error(f"Unable to get latest version information {e!r}")
+ raise
+ else:
+ _parse_pypi_resp(contents)
+
+
+async def _request_pypi_info() -> dict[str, Any]:
+ async with aiohttp.request(
+ "GET",
+ _PYPI_JSON_URL,
+ raise_for_status=True,
+ timeout=aiohttp.ClientTimeout(sock_read=30, sock_connect=20),
+ ) as response:
+ return await response.json()
+
+
+def _parse_pypi_resp(data: dict[str, Any]) -> None:
+ latest: str = data["info"]["version"]
+ releases: set[str] = set(data["releases"])
+
+ if current not in releases:
+ log.warning(f"You are using an unreleased version of CDL: {current}. Latest stable release {latest}")
+ elif current == latest:
+ log.info(f"You are using the latest version of CDL: {current}")
+ else:
+ log.warning(f"A new version is available: {latest}")
diff --git a/cyberdrop_dl/utils/apprise.py b/cyberdrop_dl/utils/apprise.py
index fe6127b9d..79b51e779 100644
--- a/cyberdrop_dl/utils/apprise.py
+++ b/cyberdrop_dl/utils/apprise.py
@@ -1,203 +1,118 @@
from __future__ import annotations
import asyncio
-import json
+import contextlib
+import dataclasses
+import importlib
+import importlib.util
import logging
-import shutil
-import tempfile
-from dataclasses import dataclass
-from enum import IntEnum
-from io import StringIO
-from pathlib import Path
-from typing import TYPE_CHECKING, Any
-
-import rich
-from rich.text import Text
-
-from cyberdrop_dl import constants
-from cyberdrop_dl.dependencies import apprise
+from typing import TYPE_CHECKING
+
+from cyberdrop_dl import aio
from cyberdrop_dl.models import AppriseURL
-from cyberdrop_dl.utils.logger import log_spacer
+from cyberdrop_dl.utils.logger import MAIN_LOG_FILE, borrow_logger, export_logs, log_spacer
if TYPE_CHECKING:
- from cyberdrop_dl.managers.manager import Manager
-
-logger = logging.getLogger(__name__)
+ from collections.abc import AsyncGenerator, Iterable, Sequence
+ from pathlib import Path
+ import apprise
-class LogLevel(IntEnum):
- NOTSET = 0
- DEBUG = 10
- INFO = 20
- WARNING = 30
- ERROR = 40
- CRITICAL = 50
-
-
-_LOG_LEVEL_NAMES = [x.name for x in LogLevel]
+logger = logging.getLogger(__name__)
-@dataclass
-class LogLine:
- level: LogLevel = LogLevel.INFO
- msg: str = ""
[email protected](slots=True)
+class _AppriseMessage:
+ tag: str
+ body: str = "Finished downloading. Enjoy :)"
+ title: str = "Cyberdrop-DL"
+ body_format: str = "text"
+ attachment: str | None = None
-def get_apprise_urls(*, file: Path | None = None, urls: list[str] | None = None) -> list[AppriseURL]:
- """
- Get Apprise URLs from the specified file or directly from a provided URL.
+def read_apprise_urls(file: Path) -> tuple[AppriseURL, ...]:
+ return _parse_apprise_url(*_read_apprise_urls(file))
- Args:
- file (Path, optional): The path to the file containing Apprise URLs.
- url (str, optional): A single Apprise URL to be processed.
- Returns:
- list[AppriseURL] | None: A list of processed Apprise URLs, or None if no valid URLs are found.
- """
+def _read_apprise_urls(file: Path) -> tuple[str, ...]:
+ try:
+ with file.open(encoding="utf8") as fp:
+ return tuple(url for line in fp if (url := line.strip()) and not url.startswith("#"))
- if not (urls or file):
- raise ValueError("Neither url of file were supplied")
- if urls and file:
- raise ValueError("url of file are mutually exclusive")
+ except OSError:
+ logger.exception(f"Unable to read apprise URL from '{file}'. Ignoring")
+ return ()
- if file:
- if not file.is_file():
- return []
- with file.open(encoding="utf8") as apprise_file:
- urls = [line.strip() for line in apprise_file if line.strip()]
+def _parse_apprise_url(*urls: str) -> tuple[AppriseURL, ...]:
if not urls:
- return []
- if apprise is None:
- logger.warning("Found apprise URLs for notifications but apprise is not installed. Ignoring")
- return []
-
- return [AppriseURL.model_validate(url) for url in set(urls)]
-
-
-def _process_results(
- all_urls: list[str], results: dict[str, bool | None], apprise_logs: str
-) -> tuple[constants.NotificationResult, list[LogLine]]:
- result = [r for r in results.values() if r is not None]
- result_dict = {}
- for key, value in results.items():
- if value:
- result_dict[key] = str(constants.NotificationResult.SUCCESS.value)
- elif value is None:
- result_dict[key] = str(constants.NotificationResult.NONE.value)
- else:
- result_dict[key] = str(constants.NotificationResult.FAILED.value)
-
- if all(result):
- final_result = constants.NotificationResult.SUCCESS
- elif any(result):
- final_result = constants.NotificationResult.PARTIAL
- else:
- final_result = constants.NotificationResult.FAILED
-
- log_spacer()
- rich.print("Apprise notifications results:", final_result.value)
- log = logger.debug if all(result) else logger.info
- log(f"Apprise notifications results: {final_result.value}")
- log(f"PARSED_APPRISE_URLs: \n{json.dumps(all_urls, indent=4)}\n")
- log(f"RESULTS_BY_TAGS: \n{json.dumps(result_dict, indent=4)}")
- log_spacer()
- parsed_log_lines = _parse_apprise_logs(apprise_logs)
- for line in parsed_log_lines:
- log(line.msg)
- return final_result, parsed_log_lines
-
+ return ()
-def _reduce_logs(apprise_logs: str) -> list[str]:
- lines = apprise_logs.splitlines()
- to_exclude = ["Running Post-Download Processes For Config"]
- return [line for line in lines if all(word not in line for word in to_exclude)]
-
-
-def _parse_apprise_logs(apprise_logs: str) -> list[LogLine]:
- lines = _reduce_logs(apprise_logs)
- current_line: LogLine = LogLine()
- parsed_lines: list[LogLine] = []
- for line in lines:
- log_level = line[0:8].strip()
- if log_level and log_level not in _LOG_LEVEL_NAMES: # pragma: no cover
- current_line.msg += f"\n{line}"
- continue
-
- if current_line.msg != "":
- parsed_lines.append(current_line)
- current_line = LogLine(LogLevel[log_level], line[10::])
- if lines:
- parsed_lines.append(current_line)
- return parsed_lines
-
-
-async def send_apprise_notifications(manager: Manager) -> tuple[constants.NotificationResult, list[LogLine]]:
- """
- Send notifications using Apprise based on the URLs set in the manager.
+ if importlib.util.find_spec("apprise") is None:
+ logger.warning("Found apprise URLs for notifications but apprise is not installed. Ignoring")
+ return ()
- Args:
- manager (Manager): The manager instance containing.
+ return tuple(AppriseURL.model_validate({"url": url}) for url in set(urls))
- Returns:
- tuple[NotificationResult, list[LogLine]]: A tuple containing the overall notification result and a list of log lines.
- """
- apprise_urls = manager.config_manager.apprise_urls
- if not apprise_urls:
- return constants.NotificationResult.NONE, [LogLine(msg=constants.NotificationResult.NONE.value.plain)]
+async def send_notifications(urls: Sequence[AppriseURL], body: str) -> None:
+ if not urls:
+ return
- rich.print("\nSending Apprise Notifications.. ")
- text: Text = constants.LOG_OUTPUT_TEXT
- constants.LOG_OUTPUT_TEXT = Text("")
+ import apprise
+ log_spacer()
+ logger.info("Sending Apprise notifications ... ")
apprise_obj = apprise.Apprise()
+ should_attach_logs: bool = False
- attach_logs: bool = False
- for webhook in apprise_urls:
- if not attach_logs:
- attach_logs = webhook.attach_logs
+ for webhook in urls:
+ should_attach_logs |= webhook.attach_logs
_ = apprise_obj.add(str(webhook.url.get_secret_value()), tag=sorted(webhook.tags))
- main_log = manager.config.logs.main_log
- all_urls = [str(x) for x in apprise_urls]
- log_lines = []
-
- with (
- apprise.LogCapture(level=10, fmt="%(levelname)-7s - %(message)s") as capture,
- tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as temp_dir,
- ):
- temp_dir = Path(temp_dir)
- assert isinstance(capture, StringIO)
- temp_main_log = temp_dir / main_log.name
- notifications_to_send: dict[str, dict[str, Any]] = {
- "no_logs": {"body": text.plain},
- "attach_logs": {"body": text.plain},
- "simplified": {},
- }
- attach_file_failed_msg = "Unable to get copy of main log file. 'attach_logs' URLs will be processed without it"
- log_lines = [LogLine(LogLevel.ERROR, attach_file_failed_msg)]
+ messages = (
+ attach_logs_msg := _AppriseMessage(body=body, tag="attach_logs"),
+ _AppriseMessage(body=body, tag="no_logs"),
+ _AppriseMessage(tag="simplified"),
+ )
+
+ if not should_attach_logs:
+ await _notify(apprise_obj, messages)
+ return
+
+ async with _temp_copy_of_main_log() as file:
+ if file:
+ attach_logs_msg.attachment = str(file)
+ await _notify(apprise_obj, messages)
+
+
+async def _notify(apprise_obj: apprise.Apprise, messages: Iterable[_AppriseMessage]) -> None:
+ with borrow_logger("apprise", level=logging.INFO):
+ _ = await asyncio.gather(
+ *(
+ apprise_obj.async_notify(
+ title=msg.title,
+ body=msg.body,
+ body_format=msg.body_format,
+ attach=msg.attachment,
+ tag=msg.tag,
+ )
+ for msg in messages
+ )
+ )
+
+
+async def _temp_copy_of_main_log() -> AsyncGenerator[Path | None]:
+ async with aio.temp_dir() as temp_dir:
+ temp_file = temp_dir / MAIN_LOG_FILE.get().name
try:
- shutil.copy(main_log, temp_main_log)
- notifications_to_send["attach_logs"]["attach"] = str(temp_main_log.resolve())
- except OSError:
- logger.exception(attach_file_failed_msg)
-
- async def notify(tag: str, msg: dict[str, Any]) -> tuple[str, bool | None]:
- result = await apprise_obj.async_notify(**msg, tag=tag)
- return tag, result
-
- def prepare_notifications():
- for tag, extras in notifications_to_send.items():
- msg = {
- "body": "Finished downloading. Enjoy :)",
- "title": "Cyberdrop-DL",
- "body_format": apprise.NotifyFormat.TEXT,
- } | extras
- yield notify(tag, msg)
-
- results = dict(await asyncio.gather(*prepare_notifications()))
- apprise_logs = capture.getvalue()
-
- result, new_log_lines = _process_results(all_urls, results, apprise_logs)
- return result, log_lines + new_log_lines
+ logs = await asyncio.to_thread(export_logs, size_limit=25 * 1e6)
+ except Exception:
+ logger.exception("Unable to attach main log for apprise notifications")
+ yield
+ return
+
+ _ = await aio.write_bytes(temp_file, logs)
+
+ yield temp_file
diff --git a/cyberdrop_dl/utils/logger.py b/cyberdrop_dl/utils/logger.py
index a4f0d30de..1574c6552 100644
--- a/cyberdrop_dl/utils/logger.py
+++ b/cyberdrop_dl/utils/logger.py
@@ -334,3 +334,31 @@ def flush_logs() -> None:
listener = _MAIN_LOG_LISTENER.get()
listener.stop()
listener.start()
+
+
+def borrow_logger(name: str, level: int = logging.INFO) -> Generator[None]:
+ """Context manager to temporarily add our log handlers to a third party logger"""
+ _3p_logger = logging.getLogger(name)
+ _3p_level = _3p_logger.level
+ _3p_propagate = _3p_logger.propagate
+ _3p_handlers = _3p_logger.handlers.copy()
+
+ def replace_handlers_with(*new_handlers: logging.Handler) -> None:
+ for handler in _3p_logger.handlers[:]:
+ _3p_logger.removeHandler(handler)
+
+ for handler in new_handlers:
+ _3p_logger.addHandler(handler)
+
+ replace_handlers_with(*logger.handlers)
+
+ _3p_logger.propagate = False
+ _3p_logger.setLevel(level)
+
+ try:
+ yield
+ finally:
+ replace_handlers_with(*_3p_handlers)
+ _3p_logger.propagate = _3p_propagate
+ _3p_logger.setLevel(_3p_level)
diff --git a/tests/conftest.py b/tests/conftest.py
index 71e225393..75f00be47 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -9,14 +9,14 @@ from cyberdrop_dl.managers.manager import Manager
from cyberdrop_dl.scraper import scrape_mapper
if TYPE_CHECKING:
- from collections.abc import AsyncGenerator
+ from collections.abc import AsyncGenerator, Generator
from pathlib import Path
class Config(pytest.Config): # type: ignore
test_crawlers_domains: set[str]
-def pytest_addoption(parser: pytest.Parser):
+def pytest_addoption(parser: pytest.Parser) -> None:
parser.addoption(
"--test-crawlers",
action="store",
@@ -52,9 +52,10 @@ def pytest_collection_modifyitems(config: Config, items: list[pytest.Item]) -> N
@pytest.fixture(autouse=True)
-def tmp_cwd(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
- monkeypatch.chdir(tmp_path)
- return tmp_path
+def tmp_cwd(tmp_path: Path) -> Generator[Path]:
+ with pytest.MonkeyPatch.context() as m:
+ m.chdir(tmp_path)
+ yield tmp_path
@pytest.fixture
diff --git a/tests/test_apprise.py b/tests/test_apprise.py
index 2a010d243..31a074efa 100644
--- a/tests/test_apprise.py
+++ b/tests/test_apprise.py
@@ -1,156 +1,57 @@
-import inspect
+import logging
import os
-from dataclasses import dataclass, field
from pathlib import Path
import pytest
-from rich.text import Text
-from cyberdrop_dl import constants
-from cyberdrop_dl.constants import NotificationResult
-from cyberdrop_dl.managers.config_manager import ConfigManager
-from cyberdrop_dl.managers.manager import Manager
-from cyberdrop_dl.utils import apprise
-
-TEST_FILES_PATH = Path(__file__).parent / "test_files/apprise"
-FAKE_MANAGER = Manager()
-FAKE_MANAGER.config_manager = ConfigManager(FAKE_MANAGER)
-
-URL_FAIL = "mailto://test_user:[email protected]"
-APPRISE_ENV_VAR = "APPRISE_TEST_EMAIL_URL"
-URL_SUCCESS = os.environ.get(APPRISE_ENV_VAR, "")
-URL_SUCCESS_ATTACH_LOGS = f"attach_logs={URL_SUCCESS}"
-
-pytestmark = pytest.mark.skipif(not URL_SUCCESS, reason=f"{APPRISE_ENV_VAR} environment variable is not set")
-
-
-@dataclass
-class AppriseTestCase:
- urls: list[str]
- result: NotificationResult
- include: list[str] = field(default_factory=list)
- exclude: list[str] = field(default_factory=list)
- file: Path | None = None
- name: str = "Testing Apprise"
-
-
-def test_get_apprise_urls() -> None:
- with pytest.raises(ValueError):
- apprise.get_apprise_urls()
-
- with pytest.raises(ValueError):
- apprise.get_apprise_urls(urls=["url"], file=Path.cwd())
-
- with pytest.raises(SystemExit):
- apprise.get_apprise_urls(file=TEST_FILES_PATH / "invalid_single_url.txt")
-
- with pytest.raises(SystemExit):
- apprise.get_apprise_urls(file=TEST_FILES_PATH / "invalid_multiple_urls.txt")
-
- result = apprise.get_apprise_urls(file=TEST_FILES_PATH / "file_that_does_not_exists.txt")
- assert result == []
-
- result = apprise.get_apprise_urls(file=TEST_FILES_PATH / "empty_file.txt")
- assert result == []
-
- result = apprise.get_apprise_urls(file=TEST_FILES_PATH / "valid_single_url.txt")
- assert isinstance(result, list), "Result is not a list"
- assert len(result) == 1, "This should be a single URL"
- assert isinstance(result[0], apprise.AppriseURL), "Parsed URL is not an AppriseURL"
-
- result = apprise.get_apprise_urls(file=TEST_FILES_PATH / "valid_multiple_urls.txt")
- assert isinstance(result, list), "Result is not a list"
- assert len(result) == 5, "These should be 5 URLs"
-
- expected_result = [
- apprise.AppriseURL(url="discord://avatar@webhook_id/webhook_token", tags={"no_logs"}),
- apprise.AppriseURL(url="enigma2://hostname", tags={"another_tag", "no_logs"}),
- apprise.AppriseURL(url="mailto://domain.com?user=userid&pass=password", tags={"tag2", "tag_1", "no_logs"}),
- apprise.AppriseURL(url="reddit://user:password@app_id/app_secret/subreddit", tags={"attach_logs"}),
- apprise.AppriseURL(url="windows://", tags={"simplified"}),
- ]
-
- for index in range(len(result)):
- got = result[index]
- expected = expected_result[index]
- assert isinstance(got, apprise.AppriseURL), f"Parsed URL {got} is not an AppriseURL"
- assert got == expected, f"Parsed URL: {got.raw_url}, Expected URL: {expected.raw_url}"
-
-
-async def send_notification(test_case: AppriseTestCase) -> None:
- FAKE_MANAGER.config_manager.apprise_urls = []
- if test_case.urls and any(test_case.urls):
- FAKE_MANAGER.config_manager.apprise_urls = apprise.get_apprise_urls(urls=test_case.urls)
- FAKE_MANAGER.config.logs.main_log = test_case.file or TEST_FILES_PATH / "valid_single_url.txt"
- constants.LOG_OUTPUT_TEXT = Text(test_case.name)
- result, logs = await apprise.send_apprise_notifications(FAKE_MANAGER)
- assert result.value == test_case.result.value, f"Result for this case should be {test_case.result.value}"
- assert isinstance(logs, list), "Invalid return type for logs"
- assert logs, "Logs can't be empty"
- logs_as_str = "\n".join([line.msg for line in logs])
- print(logs_as_str)
- if test_case.include:
- matches = [match.casefold() in logs_as_str.casefold() for match in test_case.include]
- assert all(matches), "Logs do not match expected pattern"
- if test_case.exclude:
- assert not any(match in logs_as_str for match in test_case.exclude), "Logs should not match exclude pattern"
-
-
-async def test_failed_notification() -> None:
- test_case = AppriseTestCase(
- urls=[URL_FAIL],
- result=NotificationResult.FAILED,
- name=inspect.currentframe().f_code.co_name, # type: ignore
- )
- await send_notification(test_case)
-
-
-async def test_successful_notification() -> None:
- test_case = AppriseTestCase(
- urls=[URL_SUCCESS],
- result=NotificationResult.SUCCESS,
- include=["Sent Discord notification", "Discord Payload"],
- name=inspect.currentframe().f_code.co_name, # type: ignore
- )
- await send_notification(test_case)
-
-
-async def test_successful_notification_with_successful_attachment() -> None:
- test_case = AppriseTestCase(
- urls=[URL_SUCCESS_ATTACH_LOGS],
- result=NotificationResult.SUCCESS,
- include=["Sent Discord notification", "Discord Payload"],
- name=inspect.currentframe().f_code.co_name, # type: ignore
- )
- await send_notification(test_case)
-
-
-async def test_successful_notification_with_failed_attachment() -> None:
- test_case = AppriseTestCase(
- urls=[URL_SUCCESS_ATTACH_LOGS],
- result=NotificationResult.SUCCESS,
- include=["Sent Discord notification", "Discord Payload", "Unable to get copy of main log file"],
- file=TEST_FILES_PATH / "file_that_does_exists.txt",
- name=inspect.currentframe().f_code.co_name, # type: ignore
- )
- await send_notification(test_case)
-
-
-async def test_none_notification() -> None:
- test_case = AppriseTestCase(
- urls=[""],
- result=NotificationResult.NONE,
- include=[NotificationResult.NONE.value.plain],
- name=inspect.currentframe().f_code.co_name, # type: ignore
- )
- await send_notification(test_case)
-
-
-async def test_partial_notification() -> None:
- test_case = AppriseTestCase(
- urls=[URL_SUCCESS_ATTACH_LOGS, URL_FAIL],
- result=NotificationResult.PARTIAL,
- include=["Connection error while submitting email", "Sent Discord notification"],
- name=inspect.currentframe().f_code.co_name, # type: ignore
- )
- await send_notification(test_case)
+from cyberdrop_dl.utils.apprise import _read_apprise_urls
+
+
+class TestReadAppriseUrls:
+ def test_valid_file(self, tmp_path: Path) -> None:
+ apprise_file = tmp_path / "urls.txt"
+ _ = apprise_file.write_text(
+ "\n".join(
+ (
+ "mailto://user:[email protected]",
+ " ",
+ "# comment",
+ "tgram://bottoken/chatid\n",
+ )
+ )
+ )
+ assert _read_apprise_urls(apprise_file) == (
+ "mailto://user:[email protected]",
+ "tgram://bottoken/chatid",
+ )
+
+ def test_empty_file(self, tmp_path: Path) -> None:
+ apprise_file = tmp_path / "empty.txt"
+ apprise_file.touch()
+ assert _read_apprise_urls(apprise_file) == ()
+
+ def test_only_comments_and_whitespace(self, tmp_path: Path) -> None:
+ apprise_file = tmp_path / "comments.txt"
+ _ = apprise_file.write_text("\n".join(("# line1\n", " # line2\n\t\n")))
+ assert _read_apprise_urls(apprise_file) == ()
+
+ def test_missing_file(self, tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
+ apprise_file = tmp_path / "gone.txt"
+ with caplog.at_level(logging.ERROR):
+ assert _read_apprise_urls(apprise_file) == ()
+
+ assert "Unable to read apprise URL" in caplog.text
+
+ @pytest.mark.skipif(os.name == "nt", reason="chmod not on Windows")
+ def test_permission_error(self, tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
+ apprise_file = tmp_path / "no_access.txt"
+ _ = apprise_file.write_text("mailto://[email protected]")
+
+ _ = apprise_file.chmod(0o000)
+ try:
+ with caplog.at_level(logging.ERROR):
+ assert _read_apprise_urls(apprise_file) == ()
+
+ assert "Unable to read apprise URL" in caplog.text
+ finally:
+ _ = apprise_file.chmod(0o644) # restore for cleanup
diff --git a/tests/test_logger.py b/tests/test_logger.py
index 6c0cb4111..4de38d25e 100644
--- a/tests/test_logger.py
+++ b/tests/test_logger.py
@@ -34,3 +34,49 @@ def test_export_logs(tmp_path: Path) -> None:
assert "Debug log file" in content
for line in TEXT.splitlines():
assert line in content
+
+
+class TestBorrowLogger:
+ def test_handlers_swapped_temporarily(self) -> None:
+ root_handler = logging.StreamHandler()
+ logger.logger.addHandler(root_handler)
+
+ try:
+ other = logging.getLogger("third_party")
+ original_handler = logging.NullHandler()
+ other.addHandler(original_handler)
+
+ assert other.handlers == [original_handler]
+
+ with logger.borrow_logger("third_party"):
+ assert other.handlers == [root_handler]
+
+ assert other.handlers == [original_handler]
+ finally:
+ logger.logger.removeHandler(root_handler)
+
+ def test_level_and_propagate_restored(self) -> None:
+ other = logging.getLogger("third_party_restore")
+ other.setLevel(logging.WARNING)
+ other.propagate = True
+
+ with logger.borrow_logger("third_party_restore", level=logging.DEBUG):
+ assert other.level == logging.DEBUG
+ assert other.propagate is False
+
+ assert other.level == logging.WARNING
+ assert other.propagate is True
+
+ def test_exception_inside_block_restores_state(self) -> None:
+ other = logging.getLogger("third_party_exc")
+ orig_handler = logging.NullHandler()
+ other.addHandler(orig_handler)
+ other.setLevel(logging.CRITICAL)
+
+ with pytest.raises(RuntimeError):
+ with logger.borrow_logger("third_party_exc", level=logging.INFO):
+ assert other.level == logging.INFO
+ raise RuntimeError("boom")
+
+ assert other.handlers == [orig_handler]
+ assert other.level == logging.CRITICAL
diff --git a/tests/test_startup.py b/tests/test_startup.py
index ab521d359..dcf4c370b 100644
--- a/tests/test_startup.py
+++ b/tests/test_startup.py
@@ -1,25 +1,24 @@
-from pathlib import Path
-
import pytest
from cyberdrop_dl.__main__ import main
from cyberdrop_dl.ui import program_ui
-def test_startup(tmp_cwd: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None:
+def test_startup(capsys: pytest.CaptureFixture[str]) -> None:
# This is just to test that cyberdrop is able to run in the current python version
msg = "main UI started successfully"
def main_ui(*_) -> None:
print(msg)
- monkeypatch.setattr(program_ui, "run", main_ui)
- main(())
- captured = capsys.readouterr()
- output = captured.out
- assert msg in output
+ with pytest.MonkeyPatch.context() as m:
+ m.setattr(program_ui, "run", main_ui)
+ main(())
+ captured = capsys.readouterr()
+ output = captured.out
+ assert msg in output
-def test_async_startup(tmp_cwd: Path, caplog: pytest.LogCaptureFixture) -> None:
+def test_async_startup(caplog: pytest.LogCaptureFixture) -> None:
main(("--download",))
assert "Finished downloading. Enjoy :)" in caplog.text