diff --git a/README.claude.md b/README.claude.md index 5468e6d..f6f8cc4 100644 --- a/README.claude.md +++ b/README.claude.md @@ -25,12 +25,45 @@ they come as separate streams). python main.py ``` +### Keyboard shortcuts + +* **Ctrl+T** — switch language (currently English/German; shows a picker). +* **Ctrl+A** — show help, rendered from `i18n//help.md` in a Markdown + viewer. Works even while the Url/Name input is focused (it overrides + `Input`'s own "select all" binding on that key). + +## Tests + +```bash +pip install -r requirements-dev.txt +pytest +``` + +`tests/` covers: + +* `test_models.py` — the format-filtering / split-vs-combined detection + logic, run against both worked examples from the requirements document + (copied into `tests/fixtures/`), plus a couple of edge cases (no + survivable formats, missing `formats` key). +* `test_subprocess_clients.py` — the `yt-dlp`/`ffmpeg` async wrappers, with + `asyncio.create_subprocess_exec` monkeypatched to a fake process so no + real binaries or network access are needed. +* `test_i18n_integration.py` — the bundled i18n library against this app's + own translation data: fallback behaviour, language switching, listener + notification, `get_help()`. +* `test_app_workflow.py` — full end-to-end runs of the Textual UI via + `Pilot`: the split and combined selection flows, the error paths (empty + URL, cancelled selection), download + merge + temp-file cleanup, and the + Ctrl+T / Ctrl+A shortcuts. + ## Project layout ``` main.py Entry point; wires up i18n, then starts the app app/ tui_app.py The Textual App: layout + all screen wiring + styles.tcss External stylesheet for the app and every modal + screen (loaded via DownloadManagerApp.CSS_PATH) models.py FormatEntry / VideoInfo + the filtering logic that decides split vs. combined audio/video ytdlp_client.py async wrappers for `yt-dlp --dump-json` and @@ -39,12 +72,15 @@ app/ screens/ format_select_screen.py Modal format-selection table (audio & video) error_screen.py Modal error dialog + language_select_screen.py Modal language picker (Ctrl+T) + help_screen.py Modal help viewer, renders help.md (Ctrl+A) lib/i18n/ The provided i18n library (unmodified aside from a small `__init__.py` re-export so that `from i18n import I18n` works as documented) i18n/en/, i18n/de/ This application's own translation data (strings.json + help.md), as expected by the library at /i18n// +tests/ pytest suite (see "Tests" below) ``` The i18n *library* is kept in `lib/i18n` (added to `sys.path` by @@ -88,8 +124,8 @@ own package directory would use if it were placed at the project root. ## Notes / assumptions * The two example JSON documents from the requirements are used as the - basis for the filtering logic and are exercised by an ad-hoc test during - development; there is no bundled test suite since none was requested. + basis for the filtering logic and are checked into `tests/fixtures/` so + the test suite exercises them directly. * Temporary files for split downloads are named `.video.tmp.mp4` / `.audio.tmp.mp4` next to the destination file. diff --git a/app/screens/__init__.py b/app/screens/__init__.py index 406170e..373b1bf 100644 --- a/app/screens/__init__.py +++ b/app/screens/__init__.py @@ -1,4 +1,6 @@ from .error_screen import ErrorScreen from .format_select_screen import FormatSelectScreen +from .help_screen import HelpScreen +from .language_select_screen import LanguageSelectScreen -__all__ = ["ErrorScreen", "FormatSelectScreen"] +__all__ = ["ErrorScreen", "FormatSelectScreen", "HelpScreen", "LanguageSelectScreen"] diff --git a/app/screens/error_screen.py b/app/screens/error_screen.py index 509a44c..1978350 100644 --- a/app/screens/error_screen.py +++ b/app/screens/error_screen.py @@ -13,35 +13,8 @@ from i18n import I18n class ErrorScreen(ModalScreen[None]): """Modal dialog showing a title and a message, dismissed via OK.""" - DEFAULT_CSS = """ - ErrorScreen { - align: center middle; - } - - ErrorScreen > Container { - width: 60%; - max-width: 70; - height: auto; - border: thick $error 80%; - background: $surface; - padding: 1 2; - } - - ErrorScreen #error-title { - text-style: bold; - color: $error; - margin-bottom: 1; - } - - ErrorScreen #error-message { - margin-bottom: 1; - } - - ErrorScreen Horizontal { - align-horizontal: center; - height: auto; - } - """ + # Styling for this screen lives in the app's shared external stylesheet + # (app/styles.tcss), loaded via DownloadManagerApp.CSS_PATH. def __init__(self, message: str, *, title: str | None = None) -> None: super().__init__() diff --git a/app/screens/format_select_screen.py b/app/screens/format_select_screen.py index 6886ce2..0de2994 100644 --- a/app/screens/format_select_screen.py +++ b/app/screens/format_select_screen.py @@ -24,37 +24,8 @@ class FormatSelectScreen(ModalScreen[FormatEntry | None]): can treat that as "no valid entry selected". """ - DEFAULT_CSS = """ - FormatSelectScreen { - align: center middle; - } - - FormatSelectScreen > Container { - width: 90%; - max-width: 120; - height: auto; - max-height: 80%; - border: thick $primary 80%; - background: $surface; - padding: 1 2; - } - - FormatSelectScreen #dialog-title { - text-style: bold; - margin-bottom: 1; - } - - FormatSelectScreen DataTable { - height: auto; - max-height: 20; - margin-bottom: 1; - } - - FormatSelectScreen Horizontal { - align-horizontal: center; - height: auto; - } - """ + # Styling for this screen lives in the app's shared external stylesheet + # (app/styles.tcss), loaded via DownloadManagerApp.CSS_PATH. BINDINGS = [("escape", "cancel", "Cancel")] diff --git a/app/screens/help_screen.py b/app/screens/help_screen.py new file mode 100644 index 0000000..1a8299d --- /dev/null +++ b/app/screens/help_screen.py @@ -0,0 +1,38 @@ +"""Modal dialog showing the current language's help text as Markdown.""" + +from __future__ import annotations + +from textual.app import ComposeResult +from textual.containers import Container, Horizontal +from textual.screen import ModalScreen +from textual.widgets import Button, Label, MarkdownViewer + +from i18n import I18n + + +class HelpScreen(ModalScreen[None]): + """Renders ``I18n.get_help()`` in a scrollable Markdown viewer.""" + + # Styling for this screen lives in the app's shared external stylesheet + # (app/styles.tcss), loaded via DownloadManagerApp.CSS_PATH. + + BINDINGS = [("escape", "close", "Close")] + + def compose(self) -> ComposeResult: + i18n = I18n() + try: + help_text = i18n.get_help() + except FileNotFoundError: + help_text = i18n.t("dialog.help_missing", default="No help is available.") + + with Container(): + yield Label(i18n.t("dialog.help_title", default="Help"), id="help-title") + yield MarkdownViewer(help_text, show_table_of_contents=False) + with Horizontal(): + yield Button(i18n.t("button.close", default="Close"), id="help-close") + + def on_button_pressed(self, event: Button.Pressed) -> None: + self.dismiss(None) + + def action_close(self) -> None: + self.dismiss(None) diff --git a/app/screens/language_select_screen.py b/app/screens/language_select_screen.py new file mode 100644 index 0000000..c673262 --- /dev/null +++ b/app/screens/language_select_screen.py @@ -0,0 +1,48 @@ +"""Modal dialog for picking one of the application's available languages.""" + +from __future__ import annotations + +from textual.app import ComposeResult +from textual.containers import Container, Horizontal, Vertical +from textual.screen import ModalScreen +from textual.widgets import Button, Label + +from i18n import I18n + + +class LanguageSelectScreen(ModalScreen[str | None]): + """Shows one button per available language; returns the chosen code. + + Returns ``None`` if the dialog is cancelled (Escape or the Cancel + button), leaving the current language unchanged. + """ + + # Styling for this screen lives in the app's shared external stylesheet + # (app/styles.tcss), loaded via DownloadManagerApp.CSS_PATH. + + BINDINGS = [("escape", "cancel", "Cancel")] + + def compose(self) -> ComposeResult: + i18n = I18n() + with Container(): + yield Label( + i18n.t("dialog.select_language", default="Select language"), + id="language-title", + ) + with Vertical(id="language-options"): + for code, display_name in i18n.get_available_languages().items(): + variant = "primary" if code == i18n.get_language() else "default" + yield Button(display_name, id=f"lang-{code}", variant=variant) + with Horizontal(): + yield Button(i18n.t("button.cancel", default="Cancel"), id="language-cancel") + + def on_button_pressed(self, event: Button.Pressed) -> None: + button_id = event.button.id or "" + if button_id == "language-cancel": + self.dismiss(None) + return + if button_id.startswith("lang-"): + self.dismiss(button_id.removeprefix("lang-")) + + def action_cancel(self) -> None: + self.dismiss(None) diff --git a/app/styles.tcss b/app/styles.tcss new file mode 100644 index 0000000..504925b --- /dev/null +++ b/app/styles.tcss @@ -0,0 +1,180 @@ +/* --------------------------------------------------------------------- + * Styles for DownloadManagerApp (main screen) + * ------------------------------------------------------------------- */ + +#form Input { + margin-bottom: 1; +} + +.field-row { + height: auto; + margin-bottom: 1; +} + +.field-row Label { + width: 10; + padding-top: 1; +} + +.field-row Input { + width: 1fr; +} + +#selection-area { + height: auto; + margin-bottom: 1; +} + +#progress-text { + margin-top: 1; +} + +#progress-bar { + width: 100%; + margin-bottom: 1; +} + +#button-row { + height: auto; + align-horizontal: left; +} + +#button-row Button { + margin-right: 1; +} + +/* --------------------------------------------------------------------- + * ErrorScreen + * ------------------------------------------------------------------- */ + +ErrorScreen { + align: center middle; +} + +ErrorScreen > Container { + width: 60%; + max-width: 70; + height: auto; + border: thick $error 80%; + background: $surface; + padding: 1 2; +} + +ErrorScreen #error-title { + text-style: bold; + color: $error; + margin-bottom: 1; +} + +ErrorScreen #error-message { + margin-bottom: 1; +} + +ErrorScreen Horizontal { + align-horizontal: center; + height: auto; +} + +/* --------------------------------------------------------------------- + * FormatSelectScreen + * ------------------------------------------------------------------- */ + +FormatSelectScreen { + align: center middle; +} + +FormatSelectScreen > Container { + width: 90%; + max-width: 120; + height: auto; + max-height: 80%; + border: thick $primary 80%; + background: $surface; + padding: 1 2; +} + +FormatSelectScreen #dialog-title { + text-style: bold; + margin-bottom: 1; +} + +FormatSelectScreen DataTable { + height: auto; + max-height: 20; + margin-bottom: 1; +} + +FormatSelectScreen Horizontal { + align-horizontal: center; + height: auto; +} + +/* --------------------------------------------------------------------- + * LanguageSelectScreen + * ------------------------------------------------------------------- */ + +LanguageSelectScreen { + align: center middle; +} + +LanguageSelectScreen > Container { + width: 50%; + max-width: 50; + height: auto; + border: thick $primary 80%; + background: $surface; + padding: 1 2; +} + +LanguageSelectScreen #language-title { + text-style: bold; + margin-bottom: 1; +} + +LanguageSelectScreen Vertical#language-options { + height: auto; + margin-bottom: 1; +} + +LanguageSelectScreen Button { + width: 100%; + margin-bottom: 1; +} + +LanguageSelectScreen Horizontal { + align-horizontal: center; + height: auto; +} + +/* --------------------------------------------------------------------- + * HelpScreen + * ------------------------------------------------------------------- */ + +HelpScreen { + align: center middle; +} + +HelpScreen > Container { + width: 80%; + max-width: 100; + height: 80%; + border: thick $primary 80%; + background: $surface; + padding: 1 2; +} + +HelpScreen #help-title { + text-style: bold; + margin-bottom: 1; + height: auto; +} + +HelpScreen MarkdownViewer { + height: 1fr; + margin-bottom: 1; +} + +HelpScreen Horizontal { + align-horizontal: center; + height: auto; +} diff --git a/app/tui_app.py b/app/tui_app.py index f9d8a18..0c4de6a 100644 --- a/app/tui_app.py +++ b/app/tui_app.py @@ -5,6 +5,7 @@ from __future__ import annotations from pathlib import Path from textual.app import App, ComposeResult +from textual.binding import Binding from textual.containers import Horizontal, Vertical from textual.widgets import Button, Footer, Header, Input, Label, ProgressBar, Static from textual.worker import Worker, WorkerState @@ -13,54 +14,23 @@ from i18n import I18n from . import ffmpeg_client, ytdlp_client from .models import FormatEntry, VideoInfo -from .screens import ErrorScreen, FormatSelectScreen +from .screens import ErrorScreen, FormatSelectScreen, HelpScreen, LanguageSelectScreen class DownloadManagerApp(App[None]): """A textual UI for downloading a single film via yt-dlp.""" - CSS = """ - #form Input { - margin-bottom: 1; - } + # All widget styling (this screen plus every modal screen) lives in one + # external stylesheet rather than scattered DEFAULT_CSS/CSS blocks. + CSS_PATH = "styles.tcss" - .field-row { - height: auto; - margin-bottom: 1; - } - - .field-row Label { - width: 10; - padding-top: 1; - } - - .field-row Input { - width: 1fr; - } - - #selection-area { - height: auto; - margin-bottom: 1; - } - - #progress-text { - margin-top: 1; - } - - #progress-bar { - width: 100%; - margin-bottom: 1; - } - - #button-row { - height: auto; - align-horizontal: left; - } - - #button-row Button { - margin-right: 1; - } - """ + # `priority=True` makes these global: they fire even while an Input (or + # any other widget with its own key bindings, e.g. Input's built-in + # ctrl+a "select all") has focus. + BINDINGS = [ + Binding("ctrl+t", "switch_language", "Language", priority=True), + Binding("ctrl+a", "show_help", "Help", priority=True), + ] def __init__(self) -> None: super().__init__() @@ -80,10 +50,10 @@ class DownloadManagerApp(App[None]): yield Header() with Vertical(id="form"): with Horizontal(classes="field-row"): - yield Label(t("label.url", default="Url")) + yield Label(t("label.url", default="Url"), id="url-label") yield Input(id="url-input", placeholder=t("placeholder.url", default="https://...")) with Horizontal(classes="field-row"): - yield Label(t("label.name", default="Name")) + yield Label(t("label.name", default="Name"), id="name-label") yield Input( id="name-input", placeholder=t("placeholder.name", default="destination filename"), @@ -136,6 +106,72 @@ class DownloadManagerApp(App[None]): async def _show_error(self, message: str) -> None: await self.push_screen_wait(ErrorScreen(message)) + # -- language switching & help ------------------------------------------- + + def on_mount(self) -> None: + self.i18n.add_language_change_listener(self._on_language_changed) + + def on_unmount(self) -> None: + self.i18n.remove_language_change_listener(self._on_language_changed) + + def _on_language_changed(self, code: str) -> None: + self._refresh_translations() + + def _refresh_translations(self) -> None: + """Re-apply translated text to every static/translated widget. + + Called once after `I18n.set_language` notifies its listeners, since + widgets built during `compose()` don't re-translate themselves. + """ + t = self.i18n.t + self.title = t("app.title", default="yt-dlp Download Manager") + + self.query_one("#url-label", Label).update(t("label.url", default="Url")) + self.query_one("#url-input", Input).placeholder = t( + "placeholder.url", default="https://..." + ) + self.query_one("#name-label", Label).update(t("label.name", default="Name")) + self.query_one("#name-input", Input).placeholder = t( + "placeholder.name", default="destination filename" + ) + + self.query_one("#audio-label", Static).update( + self._format_selection_line("audio", self.selected_audio) + ) + self.query_one("#video-label", Static).update( + self._format_selection_line("video", self.selected_video) + ) + + self.query_one("#select-parts-btn", Button).label = t( + "button.select_parts", default="Select parts" + ) + self.query_one("#start-download-btn", Button).label = t( + "button.start_download", default="Start download" + ) + self.query_one("#exit-btn", Button).label = t("button.exit", default="Exit") + + # Only clobber the progress text with "Idle" while nothing is + # running; an in-progress download keeps updating it anyway. + if not self.query_one("#select-parts-btn", Button).disabled: + self.query_one("#progress-text", Static).update(t("status.idle", default="Idle")) + + def action_switch_language(self) -> None: + # Bindings are dispatched outside of a worker context, but + # `push_screen_wait` requires one, so the real work runs in a + # worker. + self.run_worker(self._switch_language(), exclusive=True, group="language") + + async def _switch_language(self) -> None: + chosen = await self.push_screen_wait(LanguageSelectScreen()) + if chosen is not None and chosen != self.i18n.get_language(): + self.i18n.set_language(chosen) + + def action_show_help(self) -> None: + self.run_worker(self._show_help(), exclusive=True, group="help") + + async def _show_help(self) -> None: + await self.push_screen_wait(HelpScreen()) + # -- button wiring ------------------------------------------------------ def on_button_pressed(self, event: Button.Pressed) -> None: diff --git a/i18n/de/strings.json b/i18n/de/strings.json index c4e1925..f897fc1 100644 --- a/i18n/de/strings.json +++ b/i18n/de/strings.json @@ -22,10 +22,17 @@ "button.exit": "Beenden", "button.ok": "OK", "button.cancel": "Abbrechen", + "button.close": "Schließen", "dialog.error_title": "Fehler", "dialog.select_audio": "Audio-Teil auswählen", "dialog.select_video": "Video-Teil auswählen", + "dialog.select_language": "Sprache auswählen", + "dialog.help_title": "Hilfe", + "dialog.help_missing": "Keine Hilfe verfügbar.", + + "keybind.language": "Sprache", + "keybind.help": "Hilfe", "table.format_id": "Format-ID", "table.resolution": "Auflösung", diff --git a/i18n/en/strings.json b/i18n/en/strings.json index d6e12a9..ced0c37 100644 --- a/i18n/en/strings.json +++ b/i18n/en/strings.json @@ -22,10 +22,17 @@ "button.exit": "Exit", "button.ok": "OK", "button.cancel": "Cancel", + "button.close": "Close", "dialog.error_title": "Error", "dialog.select_audio": "Select audio part", "dialog.select_video": "Select video part", + "dialog.select_language": "Select language", + "dialog.help_title": "Help", + "dialog.help_missing": "No help is available.", + + "keybind.language": "Language", + "keybind.help": "Help", "table.format_id": "Format ID", "table.resolution": "Resolution", diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..2f4c80e --- /dev/null +++ b/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +asyncio_mode = auto diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..7df8cd2 --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,3 @@ +-r requirements.txt +pytest>=8.0 +pytest-asyncio>=0.24 diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..30fcc33 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,46 @@ +"""Shared pytest fixtures for the yt-dlp download manager tests.""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path + +import pytest + +PROJECT_ROOT = Path(__file__).resolve().parent.parent +FIXTURES_DIR = Path(__file__).resolve().parent / "fixtures" + +# Make both the app package and the bundled i18n library importable, exactly +# as main.py does for the real application. +sys.path.insert(0, str(PROJECT_ROOT / "lib")) +sys.path.insert(0, str(PROJECT_ROOT)) + +from i18n import I18n # noqa: E402 + + +@pytest.fixture(scope="session", autouse=True) +def i18n_singleton() -> I18n: + """Configure the process-wide I18n singleton once for the whole run. + + Mirrors what main.py does before starting the real application. + """ + return I18n( + default_language="en", + available_languages={"en": "English", "de": "Deutsch"}, + project_root=PROJECT_ROOT, + ) + + +@pytest.fixture +def split_format_json() -> dict: + """The "separate audio/video parts" example from the requirements doc.""" + with (FIXTURES_DIR / "example_split.json").open(encoding="utf-8") as fh: + return json.load(fh) + + +@pytest.fixture +def combined_format_json() -> dict: + """The "audio+video in one part" example from the requirements doc.""" + with (FIXTURES_DIR / "example_combined.json").open(encoding="utf-8") as fh: + return json.load(fh) diff --git a/tests/fixtures/example_combined.json b/tests/fixtures/example_combined.json new file mode 100644 index 0000000..2ac268d --- /dev/null +++ b/tests/fixtures/example_combined.json @@ -0,0 +1,64 @@ +{ + "formats": [ + { + "format_id": "http-main-6", + "language": "deu", + "width": 1280, + "height": 720, + "vcodec": "H.264", + "protocol": "https", + "ext": "mp4", + "video_ext": "mp4", + "audio_ext": "none", + "resolution": "1280x720", + "dynamic_range": "SDR", + "format": "http-main-6 - 1280x720 (HD Ready)" + }, + { + "format_id": "hls-main-3309-1", + "ext": "mp4", + "protocol": "m3u8_native", + "width": 1280, + "height": 720, + "vcodec": "avc1.640020", + "acodec": "mp4a.40.2", + "dynamic_range": "SDR", + "language": "deu", + "video_ext": "mp4", + "audio_ext": "none", + "resolution": "1280x720", + "format": "hls-main-3309-1 - 1280x720" + }, + { + "format_id": "http-main-7", + "language": "deu", + "width": 1920, + "height": 1080, + "vcodec": "H.264", + "protocol": "https", + "ext": "mp4", + "video_ext": "mp4", + "audio_ext": "none", + "resolution": "1920x1080", + "dynamic_range": "SDR", + "format": "http-main-7 - 1920x1080 (Full HD)" + }, + { + "format_id": "hls-main-5147-1", + "ext": "mp4", + "protocol": "m3u8_native", + "width": 1920, + "height": 1080, + "vcodec": "avc1.64002a", + "acodec": "mp4a.40.2", + "dynamic_range": "SDR", + "language": "deu", + "video_ext": "mp4", + "audio_ext": "none", + "resolution": "1920x1080", + "format": "hls-main-5147-1 - 1920x1080" + } + ], + "fulltitle": "Unterwegs nach Cold Mountain", + "_type": "video" +} diff --git a/tests/fixtures/example_split.json b/tests/fixtures/example_split.json new file mode 100644 index 0000000..968dc1c --- /dev/null +++ b/tests/fixtures/example_split.json @@ -0,0 +1,80 @@ +{ + "formats": [ + { + "format_id": "VA-audio_0-Deutsch__Audiodeskription_", + "format_note": "Deutsch [DE]", + "language": "de", + "ext": "mp4", + "protocol": "m3u8_native", + "vcodec": "none", + "audio_ext": "mp4", + "video_ext": "none", + "resolution": "audio only", + "format": "VA-audio_0-Deutsch__Audiodeskription_ - audio only (Deutsch [DE])" + }, + { + "format_id": "VA-1293", + "ext": "mp4", + "protocol": "m3u8_native", + "width": 1280, + "height": 720, + "vcodec": "avc1.64001F", + "acodec": "none", + "dynamic_range": "SDR", + "format_note": "Deutsch [DE]", + "video_ext": "mp4", + "audio_ext": "none", + "resolution": "1280x720", + "format": "VA-1293 - 1280x720 (Deutsch [DE])" + }, + { + "format_id": "VA-1069", + "ext": "mp4", + "protocol": "m3u8_native", + "width": 1280, + "height": 720, + "vcodec": "hev1.1.6.L93.B0", + "acodec": "none", + "dynamic_range": "SDR", + "format_note": "Deutsch [DE]", + "video_ext": "mp4", + "audio_ext": "none", + "resolution": "1280x720", + "format": "VA-1069 - 1280x720 (Deutsch [DE])" + }, + { + "format_id": "VA-2198", + "ext": "mp4", + "protocol": "m3u8_native", + "width": 1920, + "height": 1080, + "vcodec": "avc1.640028", + "acodec": "none", + "video_ext": "mp4", + "audio_ext": "none", + "abr": 0, + "vbr": 2198.272, + "resolution": "1920x1080", + "aspect_ratio": 1.78, + "format": "VA-2198 - 1920x1080 (Deutsch [DE])" + }, + { + "format_id": "VA-1978", + "format_index": null, + "ext": "mp4", + "protocol": "m3u8_native", + "width": 1920, + "height": 1080, + "vcodec": "hev1.1.6.L120.B0", + "acodec": "none", + "dynamic_range": "SDR", + "format_note": "Deutsch [DE]", + "video_ext": "mp4", + "audio_ext": "none", + "resolution": "1920x1080", + "format": "VA-1978 - 1920x1080 (Deutsch [DE])" + } + ], + "fulltitle": "Der Pate", + "_type": "video" +} diff --git a/tests/test_app_workflow.py b/tests/test_app_workflow.py new file mode 100644 index 0000000..88850dd --- /dev/null +++ b/tests/test_app_workflow.py @@ -0,0 +1,189 @@ +"""End-to-end tests driving the actual Textual UI via Pilot. + +yt-dlp / ffmpeg subprocess calls are monkeypatched so these tests need +neither network access nor the real binaries installed. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest +from textual.widgets import Button, Label, MarkdownViewer, Static + +from app import ffmpeg_client, ytdlp_client +from app.tui_app import DownloadManagerApp + + +async def _wait_until(pilot, predicate, attempts: int = 50) -> None: + for _ in range(attempts): + await pilot.pause() + if predicate(): + return + raise AssertionError("condition not met in time") + + +@pytest.mark.asyncio +async def test_split_selection_and_download_merges_and_cleans_up( + monkeypatch: pytest.MonkeyPatch, split_format_json: dict, tmp_path: Path +) -> None: + async def fake_fetch_info(url: str) -> dict: + return split_format_json + + async def fake_download(url, destination, format_id, on_progress=None) -> None: + if on_progress is not None: + await on_progress(0) + await on_progress(100) + Path(destination).write_text("fake stream data") + + merge_calls: list[tuple[str, str, str]] = [] + + async def fake_merge(video_path: str, audio_path: str, destination: str) -> None: + merge_calls.append((video_path, audio_path, destination)) + Path(destination).write_text("merged") + + monkeypatch.setattr(ytdlp_client, "fetch_info", fake_fetch_info) + monkeypatch.setattr(ytdlp_client, "download", fake_download) + monkeypatch.setattr(ffmpeg_client, "merge", fake_merge) + + destination = tmp_path / "der_pate.mp4" + + app = DownloadManagerApp() + async with app.run_test() as pilot: + app.query_one("#url-input").value = "https://example.com/der-pate" + app.query_one("#name-input").value = str(destination) + + await pilot.click("#select-parts-btn") + await _wait_until(pilot, lambda: len(app.screen_stack) == 2) + + # First modal: audio selection (split example has one audio format). + await pilot.click("#select-ok") + await _wait_until(pilot, lambda: len(app.screen_stack) == 2) + + # Second modal: video selection. + await pilot.click("#select-ok") + await _wait_until(pilot, lambda: len(app.screen_stack) == 1) + + audio_label = app.query_one("#audio-label", Static) + video_label = app.query_one("#video-label", Static) + assert "VA-audio 0-Deutsch Audiodeskription" in str(audio_label.content) + assert "VA-1293" in str(video_label.content) + + download_btn = app.query_one("#start-download-btn", Button) + assert not download_btn.disabled + + await pilot.click("#start-download-btn") + await _wait_until(pilot, lambda: destination.exists()) + + # Both temp streams were merged in the required order (video, then + # audio) and the temp files were cleaned up afterwards. + assert len(merge_calls) == 1 + video_path, audio_path, dest_path = merge_calls[0] + assert "video.tmp" in video_path + assert "audio.tmp" in audio_path + assert dest_path == str(destination) + assert not any(tmp_path.glob("*.tmp.*")) + + +@pytest.mark.asyncio +async def test_empty_url_shows_error_dialog() -> None: + app = DownloadManagerApp() + async with app.run_test() as pilot: + await pilot.click("#select-parts-btn") + await _wait_until(pilot, lambda: len(app.screen_stack) == 2) + + error_message = app.screen.query_one("#error-message", Static) + assert "URL" in str(error_message.content) + + await pilot.click("#ok") + await _wait_until(pilot, lambda: len(app.screen_stack) == 1) + + +@pytest.mark.asyncio +async def test_combined_mode_shows_single_dialog_and_cancel_disables_download( + monkeypatch: pytest.MonkeyPatch, combined_format_json: dict, tmp_path: Path +) -> None: + async def fake_fetch_info(url: str) -> dict: + return combined_format_json + + monkeypatch.setattr(ytdlp_client, "fetch_info", fake_fetch_info) + + app = DownloadManagerApp() + async with app.run_test() as pilot: + app.query_one("#url-input").value = "https://example.com/cold-mountain" + app.query_one("#name-input").value = str(tmp_path / "combined.mp4") + + await pilot.click("#select-parts-btn") + await _wait_until(pilot, lambda: len(app.screen_stack) == 2) + + # Cancel the (only) selection dialog -> should raise an error and + # leave the download button disabled. + await pilot.click("#select-cancel") + await _wait_until(pilot, lambda: len(app.screen_stack) == 2) # error dialog + await pilot.click("#ok") + await _wait_until(pilot, lambda: len(app.screen_stack) == 1) + + download_btn = app.query_one("#start-download-btn", Button) + assert download_btn.disabled + + # Redo it properly this time. + await pilot.click("#select-parts-btn") + await _wait_until(pilot, lambda: len(app.screen_stack) == 2) + await pilot.click("#select-ok") + await _wait_until(pilot, lambda: len(app.screen_stack) == 1) + + assert not download_btn.disabled + audio_label = app.query_one("#audio-label", Static) + assert str(audio_label.content).endswith("-") # no audio-only part + + +@pytest.mark.asyncio +async def test_ctrl_t_switches_language_live() -> None: + app = DownloadManagerApp() + async with app.run_test() as pilot: + select_btn = app.query_one("#select-parts-btn", Button) + assert str(select_btn.label) == "Select parts" + + await pilot.press("ctrl+t") + await _wait_until(pilot, lambda: len(app.screen_stack) == 2) + await pilot.click("#lang-de") + await _wait_until(pilot, lambda: len(app.screen_stack) == 1) + + assert str(select_btn.label) == "Teile auswählen" + assert app.title == "yt-dlp Download-Manager" + + # Switch back so later tests in the same session see English again. + await pilot.press("ctrl+t") + await _wait_until(pilot, lambda: len(app.screen_stack) == 2) + await pilot.click("#lang-en") + await _wait_until(pilot, lambda: len(app.screen_stack) == 1) + assert str(select_btn.label) == "Select parts" + + +@pytest.mark.asyncio +async def test_ctrl_a_shows_markdown_help() -> None: + app = DownloadManagerApp() + async with app.run_test() as pilot: + await pilot.press("ctrl+a") + await _wait_until(pilot, lambda: len(app.screen_stack) == 2) + + viewer = app.screen.query_one(MarkdownViewer) + assert viewer is not None + title = app.screen.query_one("#help-title", Label) + assert str(title.content) == "Help" + + await pilot.click("#help-close") + await _wait_until(pilot, lambda: len(app.screen_stack) == 1) + + +@pytest.mark.asyncio +async def test_ctrl_a_works_even_while_url_input_is_focused() -> None: + """Input's own ctrl+a ("select all") binding must not shadow the app's.""" + app = DownloadManagerApp() + async with app.run_test() as pilot: + app.query_one("#url-input").focus() + await pilot.pause() + + await pilot.press("ctrl+a") + await _wait_until(pilot, lambda: len(app.screen_stack) == 2) + assert app.screen.query(MarkdownViewer) diff --git a/tests/test_i18n_integration.py b/tests/test_i18n_integration.py new file mode 100644 index 0000000..44a7893 --- /dev/null +++ b/tests/test_i18n_integration.py @@ -0,0 +1,73 @@ +"""Tests for the i18n integration: singleton, language switching, fallback.""" + +from __future__ import annotations + +from i18n import I18n + + +def test_singleton_returns_same_instance(i18n_singleton: I18n) -> None: + assert I18n() is i18n_singleton + + +def test_english_translation_present(i18n_singleton: I18n) -> None: + assert i18n_singleton.t("button.select_parts") == "Select parts" + + +def test_unknown_key_falls_back_to_key_itself(i18n_singleton: I18n) -> None: + assert i18n_singleton.t("no.such.key") == "no.such.key" + + +def test_unknown_key_uses_supplied_default(i18n_singleton: I18n) -> None: + assert i18n_singleton.t("no.such.key", default="fallback text") == "fallback text" + + +def test_status_progress_formatting(i18n_singleton: I18n) -> None: + text = i18n_singleton.t( + "status.progress", title="Der Pate", kind="Video", percent=42.0 + ) + assert text == "Der Pate - Video - 42%" + + +def test_language_switch_changes_translations(i18n_singleton: I18n) -> None: + assert i18n_singleton.get_language() == "en" + try: + i18n_singleton.set_language("de") + assert i18n_singleton.t("button.select_parts") == "Teile auswählen" + assert i18n_singleton.t("app.title") == "yt-dlp Download-Manager" + finally: + i18n_singleton.set_language("en") + + assert i18n_singleton.t("button.select_parts") == "Select parts" + + +def test_language_change_listener_is_notified(i18n_singleton: I18n) -> None: + received: list[str] = [] + + def listener(code: str) -> None: + received.append(code) + + i18n_singleton.add_language_change_listener(listener) + try: + i18n_singleton.set_language("de") + i18n_singleton.set_language("en") + finally: + i18n_singleton.remove_language_change_listener(listener) + + assert received == ["de", "en"] + + +def test_get_help_returns_language_specific_text(i18n_singleton: I18n) -> None: + try: + i18n_singleton.set_language("de") + help_text = i18n_singleton.get_help() + assert help_text.startswith("# yt-dlp Download-Manager - Hilfe") + finally: + i18n_singleton.set_language("en") + + help_text_en = i18n_singleton.get_help() + assert help_text_en.startswith("# yt-dlp Download Manager - Help") + + +def test_available_languages_include_en_and_de(i18n_singleton: I18n) -> None: + languages = i18n_singleton.get_available_languages() + assert languages == {"en": "English", "de": "Deutsch"} diff --git a/tests/test_models.py b/tests/test_models.py new file mode 100644 index 0000000..df9cb57 --- /dev/null +++ b/tests/test_models.py @@ -0,0 +1,121 @@ +"""Unit tests for app.models: protocol filtering and split/combined detection. + +Exercised against the two worked examples from the requirements document +("requirements for a textual download manager"): one film with separate +audio/video parts ("Der Pate") and one with combined audio+video parts +("Unterwegs nach Cold Mountain"). +""" + +from __future__ import annotations + +from app.models import AUDIO_ONLY_RESOLUTION, VALID_PROTOCOL, FormatEntry, VideoInfo + + +def test_split_example_detected_as_split(split_format_json: dict) -> None: + info = VideoInfo.from_json(split_format_json) + assert info.is_split is True + + +def test_split_example_fulltitle(split_format_json: dict) -> None: + info = VideoInfo.from_json(split_format_json) + assert info.fulltitle == "Der Pate" + + +def test_split_example_audio_formats(split_format_json: dict) -> None: + info = VideoInfo.from_json(split_format_json) + assert [f.format_id for f in info.audio_formats] == [ + "VA-audio_0-Deutsch__Audiodeskription_" + ] + assert info.audio_formats[0].resolution == AUDIO_ONLY_RESOLUTION + assert info.audio_formats[0].vcodec == "none" + + +def test_split_example_video_formats(split_format_json: dict) -> None: + info = VideoInfo.from_json(split_format_json) + assert [f.format_id for f in info.video_formats] == [ + "VA-1293", + "VA-1069", + "VA-2198", + "VA-1978", + ] + # All surviving formats used the only valid protocol. + assert all(f.protocol == VALID_PROTOCOL for f in info.video_formats) + # None of them are audio-only. + assert all(f.resolution != AUDIO_ONLY_RESOLUTION for f in info.video_formats) + + +def test_combined_example_detected_as_combined(combined_format_json: dict) -> None: + info = VideoInfo.from_json(combined_format_json) + assert info.is_split is False + assert info.audio_formats == [] + + +def test_combined_example_fulltitle(combined_format_json: dict) -> None: + info = VideoInfo.from_json(combined_format_json) + assert info.fulltitle == "Unterwegs nach Cold Mountain" + + +def test_combined_example_https_formats_are_skipped(combined_format_json: dict) -> None: + """http-main-6 / http-main-7 use protocol "https" and must be dropped.""" + info = VideoInfo.from_json(combined_format_json) + ids = [f.format_id for f in info.video_formats] + assert "http-main-6" not in ids + assert "http-main-7" not in ids + + +def test_combined_example_m3u8_formats_survive(combined_format_json: dict) -> None: + info = VideoInfo.from_json(combined_format_json) + ids = [f.format_id for f in info.video_formats] + assert ids == ["hls-main-3309-1", "hls-main-5147-1"] + assert all(f.protocol == VALID_PROTOCOL for f in info.video_formats) + + +def test_no_formats_survive_filtering_yields_empty_lists() -> None: + raw = { + "fulltitle": "Nothing downloadable", + "formats": [ + {"format_id": "a", "protocol": "https", "resolution": "1280x720"}, + {"format_id": "b", "protocol": "http_dash_segments", "resolution": "1920x1080"}, + ], + } + info = VideoInfo.from_json(raw) + assert info.audio_formats == [] + assert info.video_formats == [] + assert info.is_split is False + + +def test_missing_formats_key_yields_empty_lists() -> None: + info = VideoInfo.from_json({"fulltitle": "No formats key at all"}) + assert info.audio_formats == [] + assert info.video_formats == [] + + +class TestFormatEntry: + def test_display_text_replaces_underscores_with_blanks(self) -> None: + entry = FormatEntry.from_json( + { + "format_id": "VA-audio_0-Deutsch__Audiodeskription_", + "resolution": "audio only", + "acodec": None, + "vcodec": "none", + "format": "VA-audio_0-Deutsch__Audiodeskription_ - audio only (Deutsch [DE])", + "protocol": "m3u8_native", + } + ) + assert "_" not in entry.display_text + assert entry.display_text == ( + "VA-audio 0-Deutsch Audiodeskription - audio only (Deutsch [DE])" + ) + + def test_is_audio_only_property(self) -> None: + audio_entry = FormatEntry.from_json({"resolution": "audio only", "format_id": "a"}) + video_entry = FormatEntry.from_json({"resolution": "1920x1080", "format_id": "b"}) + assert audio_entry.is_audio_only is True + assert video_entry.is_audio_only is False + + def test_missing_or_none_codec_normalised_to_none_string(self) -> None: + entry = FormatEntry.from_json( + {"format_id": "x", "resolution": "1280x720", "acodec": None, "vcodec": "none"} + ) + assert entry.acodec == "none" + assert entry.vcodec == "none" diff --git a/tests/test_subprocess_clients.py b/tests/test_subprocess_clients.py new file mode 100644 index 0000000..4487a07 --- /dev/null +++ b/tests/test_subprocess_clients.py @@ -0,0 +1,135 @@ +"""Tests for the async subprocess wrappers, using fake subprocesses. + +These avoid depending on a real yt-dlp/ffmpeg installation or network +access by monkeypatching asyncio.create_subprocess_exec with a small stand-in +that plays back canned stdout and a fixed return code. +""" + +from __future__ import annotations + +import asyncio +import json + +import pytest + +from app import ffmpeg_client, ytdlp_client + + +class _FakeStdout: + def __init__(self, lines: list[bytes]) -> None: + self._lines = list(lines) + + async def readline(self) -> bytes: + if not self._lines: + return b"" + return self._lines.pop(0) + + +class _FakeProcess: + def __init__(self, stdout_lines: list[bytes], return_code: int = 0) -> None: + self.stdout = _FakeStdout(stdout_lines) + self._return_code = return_code + self._communicate_payload = b"".join(stdout_lines) + + async def wait(self) -> int: + return self._return_code + + async def communicate(self) -> tuple[bytes, bytes]: + return self._communicate_payload, b"" + + +# -- fetch_info ----------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_fetch_info_parses_json_document(monkeypatch: pytest.MonkeyPatch) -> None: + document = {"fulltitle": "Test Film", "formats": []} + payload = (json.dumps(document) + "\n").encode("utf-8") + + async def fake_exec(*args, **kwargs): + return _FakeProcess([payload]) + + monkeypatch.setattr(asyncio, "create_subprocess_exec", fake_exec) + result = await ytdlp_client.fetch_info("https://example.com/film") + assert result == document + + +@pytest.mark.asyncio +async def test_fetch_info_raises_on_no_json(monkeypatch: pytest.MonkeyPatch) -> None: + async def fake_exec(*args, **kwargs): + return _FakeProcess([b"ERROR: unsupported URL\n"]) + + monkeypatch.setattr(asyncio, "create_subprocess_exec", fake_exec) + with pytest.raises(ytdlp_client.YtDlpError): + await ytdlp_client.fetch_info("https://example.com/bad-url") + + +# -- download --------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_download_reports_progress_on_whole_percent_changes( + monkeypatch: pytest.MonkeyPatch, +) -> None: + lines = [ + b"[download] 0.0% of 10.00MiB\n", + b"[download] 0.4% of 10.00MiB\n", # same whole percent (0) -> no callback + b"[download] 50.0% of 10.00MiB\n", + b"[download] 50.6% of 10.00MiB\n", # same whole percent (50) -> no callback + b"[download] 100.0% of 10.00MiB\n", + ] + + async def fake_exec(*args, **kwargs): + return _FakeProcess(lines) + + monkeypatch.setattr(asyncio, "create_subprocess_exec", fake_exec) + + seen: list[float] = [] + + async def on_progress(percent: float) -> None: + seen.append(percent) + + await ytdlp_client.download("https://example.com/film", "out.mp4", "137", on_progress) + assert seen == [0.0, 50.0, 100.0] + + +@pytest.mark.asyncio +async def test_download_raises_on_nonzero_exit(monkeypatch: pytest.MonkeyPatch) -> None: + async def fake_exec(*args, **kwargs): + return _FakeProcess([b"ERROR: network failure\n"], return_code=1) + + monkeypatch.setattr(asyncio, "create_subprocess_exec", fake_exec) + with pytest.raises(ytdlp_client.YtDlpError): + await ytdlp_client.download("https://example.com/film", "out.mp4", "137") + + +# -- ffmpeg merge ------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_merge_succeeds_on_zero_exit(monkeypatch: pytest.MonkeyPatch) -> None: + captured_args: list[str] = [] + + async def fake_exec(*args, **kwargs): + captured_args.extend(args) + return _FakeProcess([b""], return_code=0) + + monkeypatch.setattr(asyncio, "create_subprocess_exec", fake_exec) + await ffmpeg_client.merge("video.mp4", "audio.mp4", "dest.mp4") + + # Requirements specify: ffmpeg -i video.mp4 -i audio.mp4 -c copy dest + assert "-i" in captured_args + video_index = captured_args.index("video.mp4") + audio_index = captured_args.index("audio.mp4") + assert video_index < audio_index + assert captured_args[-1] == "dest.mp4" + + +@pytest.mark.asyncio +async def test_merge_raises_on_nonzero_exit(monkeypatch: pytest.MonkeyPatch) -> None: + async def fake_exec(*args, **kwargs): + return _FakeProcess([b"ffmpeg error output\n"], return_code=1) + + monkeypatch.setattr(asyncio, "create_subprocess_exec", fake_exec) + with pytest.raises(ffmpeg_client.FfmpegError): + await ffmpeg_client.merge("video.mp4", "audio.mp4", "dest.mp4")