From 1b2acae316caab6e15277085c4e058cbba814d83 Mon Sep 17 00:00:00 2001 From: stilobique Date: Sun, 15 Nov 2026 00:08:03 +0100 Subject: [PATCH] Add test suite (box rules, Python, QML against a fake Jellyfin server) and local preview jobs - freebox-jellyfin test: box-only rules (ES5, QtQuick 2.5, qmldir, singletons), tooling unit tests, qmltestrunner on tests/qml against fake_server.py - freebox-jellyfin fake-server and preview --fake-server - package enforces the box rules; CI runs the tests - JetBrains run configs: Local Preview, Local Preview (faux serveur), Tests Co-Authored-By: Claude Opus 5.5 --- .gitea/workflows/ci.yml | 7 +- .run/Local Preview (faux serveur).run.xml | 26 ++ .run/Local Preview.run.xml | 26 ++ .run/Tests.run.xml | 26 ++ CLAUDE.md | 15 +- readme.md | 15 +- src/freebox_jellyfin/__init__.py | 8 +- src/freebox_jellyfin/boxrules.py | 154 +++++++ src/freebox_jellyfin/fake_server.py | 347 ++++++++++++++++ src/freebox_jellyfin/package.py | 20 +- src/freebox_jellyfin/preview.py | 24 +- src/freebox_jellyfin/test.py | 102 +++++ tests/python/test_boxrules.py | 113 ++++++ tests/python/test_tooling.py | 97 +++++ tests/qml/JellyfinTestCase.qml | 81 ++++ tests/qml/tst_flow.qml | 212 ++++++++++ tests/qml/tst_helpers.qml | 111 +++++ tests/qml/tst_player.qml | 258 ++++++++++++ tests/qml/tst_session.qml | 472 ++++++++++++++++++++++ 19 files changed, 2097 insertions(+), 17 deletions(-) create mode 100644 .run/Local Preview (faux serveur).run.xml create mode 100644 .run/Local Preview.run.xml create mode 100644 .run/Tests.run.xml create mode 100644 src/freebox_jellyfin/boxrules.py create mode 100644 src/freebox_jellyfin/fake_server.py create mode 100644 src/freebox_jellyfin/test.py create mode 100644 tests/python/test_boxrules.py create mode 100644 tests/python/test_tooling.py create mode 100644 tests/qml/JellyfinTestCase.qml create mode 100644 tests/qml/tst_flow.qml create mode 100644 tests/qml/tst_helpers.qml create mode 100644 tests/qml/tst_player.qml create mode 100644 tests/qml/tst_session.qml diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 75318a6..365c2cd 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -1,4 +1,4 @@ -# Vérifications à chaque push / pull request, et release Gitea avec le paquet FreeStore +# Tests et vérifications à chaque push / pull request, et release Gitea avec le paquet FreeStore # sur un tag « vX.Y.Z » (qui doit correspondre à « version » dans app/manifest.json). # Le téléversement sur la console FreeFactory reste manuel (pas d'API connue). name: CI @@ -22,7 +22,7 @@ jobs: $SUDO apt-get update -qq DEBIAN_FRONTEND=noninteractive $SUDO apt-get install -y -qq --no-install-recommends \ curl git ca-certificates qmlscene qtdeclarative5-dev-tools \ - qml-module-qtquick2 qml-module-qtquick-window2 qml-module-qtmultimedia + qml-module-qtquick2 qml-module-qtquick-window2 qml-module-qtmultimedia qml-module-qttest git clone --depth 1 https://github.com/fbx/libfbxqml.git ../libfbxqml - name: uv (outils Python du dépôt) @@ -30,6 +30,9 @@ jobs: curl -LsSf https://astral.sh/uv/0.12.9/install.sh | sh echo "$HOME/.local/bin" >> "$GITHUB_PATH" + - name: Tests (règles de la box, outillage Python, QML contre un faux serveur Jellyfin) + run: uv run --locked freebox-jellyfin test + - name: Manifest, syntaxe QML/JS et paquet FreeStore run: uv run --locked freebox-jellyfin package diff --git a/.run/Local Preview (faux serveur).run.xml b/.run/Local Preview (faux serveur).run.xml new file mode 100644 index 0000000..7e025b8 --- /dev/null +++ b/.run/Local Preview (faux serveur).run.xml @@ -0,0 +1,26 @@ + + + + + diff --git a/.run/Local Preview.run.xml b/.run/Local Preview.run.xml new file mode 100644 index 0000000..1454a5d --- /dev/null +++ b/.run/Local Preview.run.xml @@ -0,0 +1,26 @@ + + + + + diff --git a/.run/Tests.run.xml b/.run/Tests.run.xml new file mode 100644 index 0000000..cc3a091 --- /dev/null +++ b/.run/Tests.run.xml @@ -0,0 +1,26 @@ + + + + + diff --git a/CLAUDE.md b/CLAUDE.md index 2784298..1b9837b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -9,24 +9,27 @@ A Jellyfin client for the Freebox Player (Revolution), written in pure QML (no C ## Layout - `app/` — the application itself, the only directory served to / packaged for the Player (`manifest.json`, `Jellyfin.qml`, `icon.png`, `Components/`, `Core/`, `Shared/`, `Views/`, plus the QtCreator project `Jellyfin.fbxproject`). Paths in the Architecture section are relative to `app/`. -- `src/freebox_jellyfin/` — Python dev tooling; `tools/preview.qml` — desktop preview wrapper; `dist/`, `deploy.log` — generated at the repo root. +- `src/freebox_jellyfin/` — Python dev tooling; `tests/` — QML tests (`tests/qml/`) and tooling tests (`tests/python/`), never packaged; `tools/preview.qml` — desktop preview wrapper; `dist/`, `deploy.log` — generated at the repo root. ## Build / run -There is no build system and no test suite: `freebox-jellyfin check` is the only automated guard; beyond that, verify on the box with `deploy`. +There is no build system. Automated guards: `freebox-jellyfin test` and `check` (both in CI); what they can't cover (real playback, the box's Qt 5.5 runtime, persistence) is verified on the box with `deploy`. **Local preview on the PC** (no Freebox needed): `fbx.application` from [libfbxqml](https://github.com/fbx/libfbxqml) is pure QML (a fullscreen `Window` scaled to a 720p virtual height), so the app runs with Qt 5's `qmlscene`. -- Prerequisites: `sudo apt install qmlscene qml-module-qtmultimedia qtdeclarative5-dev-tools`, and libfbxqml cloned next to the repo (`../libfbxqml`, override with `LIBFBXQML=`). -- Dev tooling is the Python package `freebox_jellyfin` (`src/freebox_jellyfin/`, uv project, Python 3.14, stdlib only): `uv sync`, then `uv run freebox-jellyfin ` (also `python -m freebox_jellyfin`). -- `uv run freebox-jellyfin preview` — 1280×720 window via `tools/preview.qml`; `--fullscreen` runs `app/Jellyfin.qml` as the box would. +- Prerequisites: `sudo apt install qmlscene qml-module-qtmultimedia qtdeclarative5-dev-tools qml-module-qttest`, and libfbxqml cloned next to the repo (`../libfbxqml`, override with `LIBFBXQML=`). +- Dev tooling is the Python package `freebox_jellyfin` (`src/freebox_jellyfin/`, uv project, Python 3.14, stdlib only): `uv sync`, then `uv run freebox-jellyfin ` (also `python -m freebox_jellyfin`). +- `uv run freebox-jellyfin preview` — 1280×720 window via `tools/preview.qml`; `--fullscreen` runs `app/Jellyfin.qml` as the box would; `--fake-server` also starts the fake Jellyfin below on `127.0.0.1:8096` for the session. JetBrains run configs in `.run/`: Local Preview, Local Preview (faux serveur), Tests, Local Deploy. - `QT_QPA_PLATFORM=offscreen uv run freebox-jellyfin preview` — headless run, useful to catch QML warnings. - HTTPS on the PC works with the system `qmlscene` (Qt 5.15 + OpenSSL 3). PyQt5 wheels from pip bundle a Qt built for OpenSSL 1.x and cannot do TLS here. - Lint: `cd app && qmllint Jellyfin.qml Components/*.qml Core/*.qml Shared/*.qml Views/*.qml` +- `uv run freebox-jellyfin test` — three stages, stops at the first failure: (1) `boxrules.py`, the box-only rules the desktop doesn't catch (ES5 syntax, QtQuick ≤ 2.5, no QtQuick.Controls, `qmldir` completeness, singleton cycles, no `import "."`; also enforced by `package`); (2) `tests/python/` (unittest); (3) `qmltestrunner` on `tests/qml/tst_*.qml`, offscreen, against `fake_server.py`. Single file: `--qml tst_session.qml`; single function: `freebox-jellyfin test Session::test_logout` (TestCase `name` + function). +- **QML tests**: `tst_helpers` (Format/Remote/DeviceProfile), `tst_session` (Session API against the fake server: probing, auth header, catalog, PlaybackInfo, Quick Connect, `cancel()`, errors/timeouts), `tst_player` (PlayerView reporting rules, with a fake session and `VideoSurface` driven by hand), `tst_flow` (remote-control journeys through Navigator + real views + real Session). Extend `JellyfinTestCase.qml` (helpers: `waitCallback`, `requests`, `mock`, `resetServer`, `findChild`); the fake server's URL comes from the generated `TestEnv` module (`Env.baseUrl/host/port`). Tests run on Qt 5.15, so `tests/` is exempt from the ES5 rule. **A `TestCase` is invisible and `KeyNavigation` skips invisible items**: put UI under a visible root `Item` next to the `TestCase`, not inside it. Set state in the order `VideoSurface._poll()` does (position, then `playerState`). +- `uv run freebox-jellyfin fake-server [--port 8096]` — the same fake Jellyfin (`fake_server.py`: users alice/secret and bob without password, Films with 25 movies incl. direct/transcode/unplayable ones, a series with 2 seasons, Quick Connect code 123456) for working in `preview` without a real server: add server `127.0.0.1`, port `8096`. Control endpoints for tests: `/__reset`, `/__requests`, `/__mock`, `/__quickconnect/authorize`. - `uv run freebox-jellyfin check` — serves `app/` over HTTP and loads it with `qmlscene` (offscreen, software renderer) like the box does; fails on any Qt warning not coming from libfbxqml. This reproduces the box's HTTP loading mode, which behaves differently from local files (see constraints below): run it after touching imports, `qmldir` files or singletons. - The desktop has Qt 5.15 while the box targets QtQuick 2.5: code that runs locally can still use APIs too new for the box. -**CI** (`.gitea/workflows/ci.yml`, Gitea Actions on the `ubuntu-latest` runner image): installs uv (pinned 0.12.9, which fetches Python 3.14) and on every push/PR runs `uv run --locked freebox-jellyfin package` (manifest + qmllint + archive) and `… check`; package uploaded as artifact (`upload-artifact@v3`/`download-artifact@v3`: v4 only works on recent Gitea versions). On tag `vX.Y.Z` matching `manifest.json` `version`, creates a Gitea release with the package attached (API calls with the job's `GITHUB_TOKEN`). +**CI** (`.gitea/workflows/ci.yml`, Gitea Actions on the `ubuntu-latest` runner image): installs uv (pinned 0.12.9, which fetches Python 3.14) and on every push/PR runs `uv run --locked freebox-jellyfin test`, `… package` (manifest + box rules + qmllint + archive) and `… check`; package uploaded as artifact (`upload-artifact@v3`/`download-artifact@v3`: v4 only works on recent Gitea versions). On tag `vX.Y.Z` matching `manifest.json` `version`, creates a Gitea release with the package attached (API calls with the job's `GITHUB_TOKEN`). **Releasing**: bump `version` in `app/manifest.json` **and** `clientVersion` in `app/Core/Session.qml` (`package` refuses to build if they differ), then push a `vX.Y.Z` tag. diff --git a/readme.md b/readme.md index 697e967..ab5f6cc 100644 --- a/readme.md +++ b/readme.md @@ -25,13 +25,26 @@ Sans Freebox, l'application tourne avec `qmlscene` (Qt 5) et la bibliothèque [l ```bash -sudo apt install qmlscene qml-module-qtmultimedia qtdeclarative5-dev-tools +sudo apt install qmlscene qml-module-qtmultimedia qtdeclarative5-dev-tools qml-module-qttest git clone https://github.com/fbx/libfbxqml.git ../libfbxqml uv run freebox-jellyfin preview # fenêtre 1280x720 uv run freebox-jellyfin preview --fullscreen # plein écran, comme sur la box +uv run freebox-jellyfin preview --fake-server # avec le faux serveur Jellyfin (127.0.0.1, port 8096) uv run freebox-jellyfin check # chargement en HTTP comme le Player, échoue sur tout avertissement Qt ``` +## Tests +```bash +uv run freebox-jellyfin test # règles de la box, tests Python et QML +uv run freebox-jellyfin test --qml tst_session.qml # un seul fichier de tests (tests/qml/) +uv run freebox-jellyfin test Session::test_logout # une seule fonction +uv run freebox-jellyfin fake-server # faux serveur Jellyfin sur 127.0.0.1:8096 +``` + +`test` vérifie d'abord les règles propres au Freebox Player que le PC ne signale pas (JavaScript ES5, QtQuick 2.5 au plus, `qmldir` complets, singletons), puis lance les tests QML (`tests/qml/`) contre un faux serveur Jellyfin : connexion, catalogue, lecture, Quick Connect, règles de reprise du lecteur et parcours complets à la télécommande. + +`fake-server` lance ce même faux serveur pour travailler dans l'aperçu sans vrai serveur : ajouter le serveur `127.0.0.1`, port `8096`, puis se connecter avec `alice` / `secret` ou `bob` (sans mot de passe). + ## Tester sur la Freebox Activer le mode développeur du Player (menu Réglages, avec la télécommande), puis : diff --git a/src/freebox_jellyfin/__init__.py b/src/freebox_jellyfin/__init__.py index 13d61ab..4791670 100644 --- a/src/freebox_jellyfin/__init__.py +++ b/src/freebox_jellyfin/__init__.py @@ -2,12 +2,14 @@ freebox-jellyfin preview [--fullscreen] aperçu sur le PC (qmlscene + libfbxqml) freebox-jellyfin check chargement en HTTP comme sur la box (CI) + freebox-jellyfin test [--qml FICHIER] règles de la box, tests Python et QML + freebox-jellyfin fake-server [--port N] faux serveur Jellyfin pour l'aperçu freebox-jellyfin package paquet FreeStore dans dist/ freebox-jellyfin deploy [--box IP] … lancement sur un Player en mode développeur """ import sys -COMMANDS = ("preview", "check", "package", "deploy") +COMMANDS = ("preview", "check", "test", "fake-server", "package", "deploy") def main(argv=None): @@ -22,6 +24,10 @@ def main(argv=None): from .preview import main as run elif command == "check": from .check_load import main as run + elif command == "test": + from .test import main as run + elif command == "fake-server": + from .fake_server import main as run elif command == "package": from .package import main as run else: diff --git a/src/freebox_jellyfin/boxrules.py b/src/freebox_jellyfin/boxrules.py new file mode 100644 index 0000000..fb417be --- /dev/null +++ b/src/freebox_jellyfin/boxrules.py @@ -0,0 +1,154 @@ +"""Règles du Freebox Player que qmlscene (Qt 5.15) et qmllint ne signalent pas sur le PC. + +- JavaScript ES5 seulement (Qt 5.5) : ni let/const, ni fonctions fléchées, ni gabarits `…`, + ni class, for…of ou opérateur « ... » ; +- QtQuick 2.5 au plus, pas de QtQuick.Controls, pas d'import "." ; +- chargement HTTP : chaque dossier importé a un qmldir qui liste tous ses types (et seulement + des fichiers existants), au plus un singleton par dossier, et aucun composant du dossier + d'un singleton ne l'utilise (« Cyclic dependency detected »). + +Utilisé par `freebox-jellyfin test` et `freebox-jellyfin package`. +""" +import re +from pathlib import Path + +ES5_RULES = [ + (re.compile(r"\blet\s+[A-Za-z_$\[{]"), "« let » (ES6) : utiliser var"), + (re.compile(r"\bconst\s+[A-Za-z_$\[{]"), "« const » (ES6) : utiliser var"), + (re.compile(r"=>"), "fonction fléchée (ES6) : utiliser function"), + (re.compile(r"`"), "gabarit `…` (ES6) : concaténer des chaînes"), + (re.compile(r"\bclass\s+[A-Za-z_$]"), "class (ES6)"), + (re.compile(r"\bfor\s*\(\s*(?:var\s+)?[A-Za-z_$][\w$]*\s+of\b"), "for…of (ES6)"), + (re.compile(r"\.\.\.[A-Za-z_$\[{(]"), "opérateur « ... » (ES6)"), +] +QTQUICK_MAX = (2, 5) +IMPORT_RE = re.compile(r'^\s*import\s+(?:"([^"]+)"|([\w.]+)\s+(\d+)\.(\d+))', re.M) + + +def strip_code(text): + """Remplace commentaires et contenu des chaînes par des espaces (lignes conservées). + + Les littéraux d'expression régulière sont gardés tels quels : « // » n'y est pris pour un + commentaire que s'il n'est pas précédé d'une barre oblique inverse. + """ + out = [] + i, n = 0, len(text) + while i < n: + c = text[i] + if c == "/" and i + 1 < n and text[i + 1] == "/" and (i == 0 or text[i - 1] != "\\"): + end = text.find("\n", i) + end = n if end < 0 else end + out.append(" " * (end - i)) + i = end + elif c == "/" and i + 1 < n and text[i + 1] == "*": + end = text.find("*/", i + 2) + end = n if end < 0 else end + 2 + out.append(re.sub(r"[^\n]", " ", text[i:end])) + i = end + elif c in "\"'": + j = i + 1 + while j < n and text[j] != c and text[j] != "\n": + j += 2 if text[j] == "\\" else 1 + out.append(c + " " * (min(j, n) - i - 1) + (c if j < n and text[j] == c else "")) + i = j + 1 if j < n and text[j] == c else j + else: + out.append(c) + i += 1 + return "".join(out) + + +def check_es5(path, text): + problems = [] + for number, line in enumerate(strip_code(text).splitlines(), 1): + for pattern, message in ES5_RULES: + if pattern.search(line): + problems.append("%s:%d: %s" % (path, number, message)) + return problems + + +def check_imports(path, text): + problems = [] + for match in IMPORT_RE.finditer(text): # une ligne commentée ne commence pas par « import » + line = text.count("\n", 0, match.start()) + 1 + target, module = match.group(1), match.group(2) + if target is not None: + if target in (".", "./"): + problems.append("%s:%d: import \".\" interdit (cycle en chargement HTTP)" % (path, line)) + continue + version = (int(match.group(3)), int(match.group(4))) + if module == "QtQuick" and version > QTQUICK_MAX: + problems.append("%s:%d: QtQuick %d.%d trop récent pour la box (2.5 au plus)" + % (path, line, version[0], version[1])) + if module.startswith("QtQuick.Controls"): + problems.append("%s:%d: QtQuick.Controls absent de la box" % (path, line)) + return problems + + +def _qmldir_entries(qmldir): + """[(type, singleton?, fichier)] d'un fichier qmldir.""" + entries = [] + for raw in qmldir.read_text(encoding="utf-8").splitlines(): + parts = raw.split("#")[0].split() + if not parts or parts[0] in ("module", "plugin", "classname", "typeinfo", "depends", "designersupported"): + continue + singleton = parts[0] == "singleton" + if singleton: + parts = parts[1:] + if len(parts) >= 3: + entries.append((parts[0], singleton, parts[-1])) + return entries + + +def check_directories(app_dir): + """Dossiers importés par chemin : qmldir complet, singletons sans cycle.""" + app_dir = Path(app_dir) + problems = [] + imported = set() + for qml in app_dir.rglob("*.qml"): + for match in IMPORT_RE.finditer(qml.read_text(encoding="utf-8")): + target = match.group(1) + if target and not target.endswith(".js") and target not in (".", "./"): + imported.add((qml.parent / target).resolve()) + + for folder in sorted(imported): + rel = folder.relative_to(app_dir.resolve()) if folder.is_relative_to(app_dir.resolve()) else folder + qmldir = folder / "qmldir" + if not qmldir.is_file(): + problems.append("%s/: importé mais sans qmldir (« X is not a type » sur la box)" % rel) + continue + entries = _qmldir_entries(qmldir) + listed = {file for _, _, file in entries} + for name, _, file in entries: + if not (folder / file).is_file(): + problems.append("%s/qmldir: %s → %s introuvable" % (rel, name, file)) + for qml in sorted(folder.glob("*.qml")): + if qml.name[0].isupper() and qml.name not in listed: + problems.append("%s/qmldir: %s absent (« %s is not a type » sur la box)" + % (rel, qml.name, qml.stem)) + singletons = [(name, file) for name, singleton, file in entries if singleton] + if len(singletons) > 1: + problems.append("%s/: plusieurs singletons (%s) : « Cyclic dependency detected » sur la box" + % (rel, ", ".join(n for n, _ in singletons))) + for name, file in singletons: + uses = re.compile(r"\b%s\." % re.escape(name)) + for qml in sorted(folder.glob("*.qml")): + if qml.name != file and uses.search(strip_code(qml.read_text(encoding="utf-8"))): + problems.append("%s/%s: utilise le singleton %s de son propre dossier " + "(« Cyclic dependency detected » sur la box)" % (rel, qml.name, name)) + return problems + + +def check_app(app_dir): + """Toutes les règles sur le dossier de l'application ; renvoie la liste des problèmes.""" + app_dir = Path(app_dir) + problems = [] + for path in sorted(list(app_dir.rglob("*.qml")) + list(app_dir.rglob("*.js"))): + if any(part.startswith(".") for part in path.relative_to(app_dir).parts): + continue + rel = path.relative_to(app_dir) + text = path.read_text(encoding="utf-8") + problems += check_es5(rel, text) + if path.suffix == ".qml": + problems += check_imports(rel, text) + problems += check_directories(app_dir) + return problems diff --git a/src/freebox_jellyfin/fake_server.py b/src/freebox_jellyfin/fake_server.py new file mode 100644 index 0000000..1261b0a --- /dev/null +++ b/src/freebox_jellyfin/fake_server.py @@ -0,0 +1,347 @@ +"""Faux serveur Jellyfin (HTTP, données fixes) pour les tests QML et l'aperçu sur PC. + +Données : comptes « alice » (mot de passe « secret ») et « bob » (sans mot de passe), +bibliothèques Films (25 films, dont « Film direct », « Film transcodé », « Film illisible ») +et Séries (« Série test », 2 saisons). Quick Connect activé (code 123456). + +Points d'entrée de contrôle, réservés aux tests (jamais enregistrés dans /__requests) : + POST /__reset état initial, journal des requêtes vidé + GET /__requests requêtes reçues : [{method, path, query, auth, body}] + POST /__mock {path, method?, status?, body?, raw?, delay?} : réponse imposée + POST /__quickconnect/authorize autorise la demande Quick Connect en cours + + freebox-jellyfin fake-server [--port 8096] +""" +import argparse +import http.server +import json +import re +import struct +import threading +import time +import urllib.parse +import zlib + +SERVER_ID = "fakeserver0000000000000000000001" +SERVER_NAME = "Serveur de test" +USERS = [ + {"Name": "alice", "Id": "user-alice", "HasPassword": True, "password": "secret"}, + {"Name": "bob", "Id": "user-bob", "HasPassword": False, "password": ""}, +] +QUICK_CONNECT = {"Secret": "qc-secret", "Code": "123456"} +TICKS_PER_MS = 10000 + +def _png(width=2, height=3, rgb=(0x55, 0x5a, 0x66)): + """PNG uni (réponse à toutes les demandes d'image).""" + def chunk(kind, data): + return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data)) + rows = b"".join(b"\x00" + bytes(rgb) * width for _ in range(height)) + return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(rows)) + chunk(b"IEND", b"")) + + +PNG = _png() + + +def _item(item_id, name, item_type, **extra): + item = {"Id": item_id, "Name": name, "Type": item_type, "ImageTags": {"Primary": "tag-" + item_id}, + "BackdropImageTags": [], "UserData": {"PlaybackPositionTicks": 0, "Played": False}} + item.update(extra) + return item + + +def _catalog(): + libraries = [ + _item("lib-movies", "Films", "CollectionFolder", CollectionType="movies", IsFolder=True), + _item("lib-shows", "Séries", "CollectionFolder", CollectionType="tvshows", IsFolder=True), + ] + two_hours = 2 * 3600 * 1000 * TICKS_PER_MS + movies = [ + _item("movie-direct", "Film direct", "Movie", ProductionYear=1997, RunTimeTicks=two_hours, + OfficialRating="Tous publics", CommunityRating=7.5, Overview="Lu tel quel (H.264).", + BackdropImageTags=["bd-movie-direct"], + UserData={"PlaybackPositionTicks": 10 * 60 * 1000 * TICKS_PER_MS, "PlayedPercentage": 8.3, + "Played": False}), + _item("movie-transcode", "Film transcodé", "Movie", ProductionYear=2015, RunTimeTicks=two_hours), + _item("movie-broken", "Film illisible", "Movie", ProductionYear=2001, RunTimeTicks=two_hours), + ] + movies += [_item("movie-%02d" % n, "Film %02d" % n, "Movie", ProductionYear=2000 + n, RunTimeTicks=two_hours) + for n in range(1, 23)] + for movie in movies: + movie["ParentId"] = "lib-movies" + + series = _item("series-1", "Série test", "Series", ProductionYear=2020, ChildCount=2, ParentId="lib-shows") + seasons, episodes = [], [] + for number, count in ((1, 2), (2, 1)): + season_id = "season-%d" % number + seasons.append(_item(season_id, "Saison %d" % number, "Season", IndexNumber=number, + SeriesId="series-1", SeriesName="Série test", + SeriesPrimaryImageTag="tag-series-1")) + for episode in range(1, count + 1): + episodes.append(_item( + "ep-%d-%d" % (number, episode), "Épisode %d" % episode, "Episode", + IndexNumber=episode, ParentIndexNumber=number, SeasonId=season_id, SeriesId="series-1", + SeriesName="Série test", SeriesPrimaryImageTag="tag-series-1", + RunTimeTicks=45 * 60 * 1000 * TICKS_PER_MS, Overview="Résumé de l'épisode.")) + return {"libraries": libraries, "movies": movies, "series": [series], "seasons": seasons, + "episodes": episodes} + + +class State: + def __init__(self): + self.lock = threading.Lock() + self.reset() + + def reset(self): + self.catalog = _catalog() + self.requests = [] + self.mocks = [] + self.quick_connect_authorized = False + + def all_items(self): + c = self.catalog + return c["libraries"] + c["movies"] + c["series"] + c["seasons"] + c["episodes"] + + def find(self, item_id): + for item in self.all_items(): + if item["Id"] == item_id: + return item + return None + + +class Handler(http.server.BaseHTTPRequestHandler): + server_version = "FakeJellyfin/1.0" + protocol_version = "HTTP/1.1" + + def log_message(self, *args): + pass + + # ------------------------------------------------------------ réponses + + def _send(self, status, body=None, content_type="application/json"): + if body is None: + data = b"" + elif isinstance(body, bytes): + data = body + elif isinstance(body, str): + data = body.encode() + else: + data = json.dumps(body).encode() + self.send_response(status) + if data: + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(data))) + self.send_header("Access-Control-Allow-Origin", "*") + self.end_headers() + if self.command != "HEAD": + self.wfile.write(data) + + def do_GET(self): + self._dispatch() + + def do_POST(self): + self._dispatch() + + def do_DELETE(self): + self._dispatch() + + def _dispatch(self): + state = self.server.state + parsed = urllib.parse.urlsplit(self.path) + path = parsed.path + query = {k: v[0] for k, v in urllib.parse.parse_qs(parsed.query, keep_blank_values=True).items()} + length = int(self.headers.get("Content-Length") or 0) + raw = self.rfile.read(length) if length else b"" + try: + body = json.loads(raw) if raw else None + except ValueError: + body = raw.decode(errors="replace") + + if path.startswith("/__"): + self._control(state, path, body) + return + + with state.lock: + state.requests.append({"method": self.command, "path": path, "query": query, + "auth": self.headers.get("Authorization", ""), "body": body}) + mock = next((m for m in state.mocks if m["path"] == path + and m.get("method", self.command) == self.command), None) + if mock: + if mock.get("delay"): + time.sleep(mock["delay"] / 1000.0) + if "raw" in mock: + self._send(mock.get("status", 200), mock["raw"], "text/plain") + else: + self._send(mock.get("status", 200), mock.get("body")) + return + + try: + status, response = self._route(state, path, query, body) + except Exception as error: # bug du faux serveur : visible dans la réponse + status, response = 500, {"error": repr(error)} + if isinstance(response, bytes): + self._send(status, response, "image/png") + else: + self._send(status, response) + + def _control(self, state, path, body): + with state.lock: + if path == "/__reset": + state.reset() + self._send(204) + elif path == "/__requests": + self._send(200, state.requests) + elif path == "/__mock": + state.mocks.insert(0, body) + self._send(204) + elif path == "/__quickconnect/authorize": + state.quick_connect_authorized = True + self._send(204) + else: + self._send(404, {"error": "contrôle inconnu"}) + + # --------------------------------------------------------- API Jellyfin + + def _user_for_token(self): + match = re.search(r'Token="([^"]+)"', self.headers.get("Authorization", "")) + token = match and match.group(1) + return next((u for u in USERS if token == "token-" + u["Id"]), None) + + def _signed_in(self, user): + return 200, {"AccessToken": "token-" + user["Id"], "ServerId": SERVER_ID, + "User": {"Name": user["Name"], "Id": user["Id"], "ServerId": SERVER_ID}} + + def _route(self, state, path, query, body): + # --- public + if path == "/System/Info/Public": + return 200, {"Id": SERVER_ID, "ServerName": SERVER_NAME, "Version": "10.10.0", + "LocalAddress": "http://%s:%d" % self.server.server_address[:2]} + if path == "/Users/Public": + return 200, [{"Name": u["Name"], "Id": u["Id"], "HasPassword": u["HasPassword"]} for u in USERS] + if path == "/Users/AuthenticateByName": + body = body or {} + user = next((u for u in USERS if u["Name"].lower() == str(body.get("Username", "")).lower()), None) + if not user or body.get("Pw", "") != user["password"]: + return 401, "Error processing request." + return self._signed_in(user) + if path == "/QuickConnect/Enabled": + return 200, True + if path == "/QuickConnect/Initiate": + return 200, dict(QUICK_CONNECT, Authenticated=False) + if path == "/QuickConnect/Connect": + if query.get("Secret") != QUICK_CONNECT["Secret"]: + return 404, None + return 200, dict(QUICK_CONNECT, Authenticated=state.quick_connect_authorized) + if path == "/Users/AuthenticateWithQuickConnect": + if not state.quick_connect_authorized or (body or {}).get("Secret") != QUICK_CONNECT["Secret"]: + return 401, None + return self._signed_in(USERS[0]) + if path == "/dev-config.json": + host, port = self.server.server_address[:2] + return 200, {"servers": ["%s:%d" % (host, port)], + "users": [{"name": "carol", "password": "test"}]} + if re.match(r"^/Items/[^/]+/Images/", path): + return 200, PNG + + # --- authentifié + user = self._user_for_token() + if not user: + return 401, None + with state.lock: + return self._catalog_route(state, path, query, body) + + def _catalog_route(self, state, path, query, body): + c = state.catalog + if path == "/Sessions/Logout": + return 204, None + if path == "/UserViews": + return 200, {"Items": c["libraries"], "TotalRecordCount": len(c["libraries"])} + if path == "/UserItems/Resume": + items = [i for i in c["movies"] + c["episodes"] if i["UserData"].get("PlaybackPositionTicks")] + return 200, {"Items": items, "TotalRecordCount": len(items)} + if path == "/Items/Latest": + parent = query.get("parentId") + items = c["movies"] if parent == "lib-movies" else c["series"] if parent == "lib-shows" else [] + return 200, items[:int(query.get("limit") or 20)] + if path == "/Items": + parent = query.get("parentId") + items = c["movies"] if parent == "lib-movies" else c["series"] if parent == "lib-shows" else [] + types = query.get("includeItemTypes", "").split(",") + items = [i for i in items if not types[0] or i["Type"] in types] + items = sorted(items, key=lambda i: i["Name"]) + start = int(query.get("startIndex") or 0) + limit = int(query.get("limit") or len(items)) + return 200, {"Items": items[start:start + limit], "TotalRecordCount": len(items), + "StartIndex": start} + match = re.match(r"^/Shows/([^/]+)/(Seasons|Episodes)$", path) + if match: + if match.group(2) == "Seasons": + items = [s for s in c["seasons"] if s["SeriesId"] == match.group(1)] + else: + items = [e for e in c["episodes"] if e["SeriesId"] == match.group(1) + and (not query.get("seasonId") or e["SeasonId"] == query["seasonId"])] + return 200, {"Items": items, "TotalRecordCount": len(items)} + match = re.match(r"^/Items/([^/]+)/PlaybackInfo$", path) + if match: + return self._playback_info(match.group(1)) + match = re.match(r"^/Items/([^/]+)$", path) + if match: + item = state.find(match.group(1)) + return (200, item) if item else (404, None) + if path in ("/Sessions/Playing", "/Sessions/Playing/Progress", "/Sessions/Playing/Stopped"): + body = body or {} + item = state.find(body.get("ItemId")) + if item is not None and path == "/Sessions/Playing/Stopped": + item["UserData"]["PlaybackPositionTicks"] = body.get("PositionTicks", 0) + return 204, None + return 404, None + + def _playback_info(self, item_id): + session = "play-" + item_id + if item_id == "movie-broken": + return 200, {"MediaSources": [], "PlaySessionId": session, "ErrorCode": "NoCompatibleStream"} + source = {"Id": "src-" + item_id, "Container": "mkv", "SupportsDirectPlay": True, + "SupportsDirectStream": True, "SupportsTranscoding": True} + if item_id == "movie-transcode": + source.update(Container="mkv", SupportsDirectPlay=False, SupportsDirectStream=False, + TranscodingUrl="/videos/%s/master.m3u8?MediaSourceId=src-%s&PlaySessionId=%s" + % (item_id, item_id, session)) + return 200, {"MediaSources": [source], "PlaySessionId": session} + + +class FakeServer(http.server.ThreadingHTTPServer): + daemon_threads = True + + def __init__(self, address=("127.0.0.1", 0)): + super().__init__(address, Handler) + self.state = State() + + def handle_error(self, request, client_address): + pass # client qui coupe (BrokenPipe) ou poignée de main TLS sur ce serveur HTTP + + @property + def url(self): + return "http://%s:%d" % self.server_address[:2] + + +def start(address=("127.0.0.1", 0)): + """Démarre le serveur dans un thread ; renvoie l'instance (server.url, server.shutdown()).""" + server = FakeServer(address) + threading.Thread(target=server.serve_forever, daemon=True).start() + return server + + +def main(argv=None): + parser = argparse.ArgumentParser(prog="freebox-jellyfin fake-server", description=__doc__.splitlines()[0]) + parser.add_argument("--host", default="127.0.0.1", help="adresse d'écoute (défaut : 127.0.0.1)") + parser.add_argument("--port", type=int, default=8096, help="port (défaut : 8096)") + args = parser.parse_args(argv) + server = FakeServer((args.host, args.port)) + print("Faux serveur Jellyfin sur %s (Ctrl+C pour arrêter)" % server.url, flush=True) + print("Dans l'app : adresse %s, port %d ; comptes alice / secret et bob (sans mot de passe)." + % (args.host, args.port), flush=True) + try: + server.serve_forever() + except KeyboardInterrupt: + pass + return 0 diff --git a/src/freebox_jellyfin/package.py b/src/freebox_jellyfin/package.py index bd0b147..472d4f5 100755 --- a/src/freebox_jellyfin/package.py +++ b/src/freebox_jellyfin/package.py @@ -5,8 +5,8 @@ Reproduit « Outils > Freebox SDK > Make FreeStore Package » du plugin QtCreato - fichiers inclus comme dans Jellyfin.fbxproject : QML, JS, images, polices, qmldir et manifest.json, pris dans app/ uniquement (l'outillage PC n'a rien à faire sur la box) ; - vérifications : manifest.json (identifiant, version identique à Session.clientVersion, - points d'entrée existants), JSON valides, - syntaxe QML/JS (qmllint, s'il est installé) ; + points d'entrée existants), JSON valides, règles du Player (boxrules : ES5, QtQuick 2.5, + qmldir, singletons), syntaxe QML/JS (qmllint, s'il est installé) ; - archive tar (format ustar, avec les entrées de dossiers) compressée en gzip. Usage : freebox-jellyfin package [--output dist/paquet.tar.gz] @@ -22,6 +22,7 @@ import sys import tarfile import time +from . import boxrules from .project import APP_DIR, REPO_DIR APP_DIR, REPO_DIR = str(APP_DIR), str(REPO_DIR) @@ -48,7 +49,8 @@ def check_manifest(files): path = os.path.join(APP_DIR, "manifest.json") if not os.path.exists(path): raise ValueError("manifest.json manquant") - manifest = json.load(open(path, encoding="utf-8")) + with open(path, encoding="utf-8") as stream: + manifest = json.load(stream) identifier = manifest.get("identifier") if not isinstance(identifier, str) or not re.fullmatch(r"\w+(\.\w+)+", identifier): raise ValueError("manifest.json : « identifier » absent ou invalide (forme attendue : a.b.c)") @@ -73,7 +75,8 @@ def check_manifest(files): if not isinstance(version, str) or not re.fullmatch(r"\d+\.\d+\.\d+", version): raise ValueError("manifest.json : « version » absente ou invalide (forme attendue : 1.2.3)") # La version envoyée à Jellyfin (Session.clientVersion) doit rester la même. - session = open(os.path.join(APP_DIR, "Core", "Session.qml"), encoding="utf-8").read() + with open(os.path.join(APP_DIR, "Core", "Session.qml"), encoding="utf-8") as stream: + session = stream.read() client = re.search(r'clientVersion:\s*"([^"]*)"', session) if not client or client.group(1) != version: raise ValueError("version du manifest (%s) différente de Session.clientVersion (%s)" @@ -87,7 +90,11 @@ def check_manifest(files): def check_sources(files): for name in files: if name.endswith(".json"): - json.load(open(os.path.join(APP_DIR, name), encoding="utf-8")) + with open(os.path.join(APP_DIR, name), encoding="utf-8") as stream: + json.load(stream) + problems = boxrules.check_app(APP_DIR) + if problems: + raise ValueError("règles du Freebox Player non respectées :\n" + "\n".join(problems)) qmllint = shutil.which("qmllint") if not qmllint: print("Attention : qmllint introuvable, syntaxe QML/JS non vérifiée.") @@ -120,7 +127,8 @@ def build_archive(files, output): if directory not in seen_dirs: seen_dirs.add(directory) archive.addfile(info(directory, True)) - data = open(os.path.join(APP_DIR, name), "rb").read() + with open(os.path.join(APP_DIR, name), "rb") as stream: + data = stream.read() archive.addfile(info(name.replace(os.sep, "/"), False, len(data)), io.BytesIO(data)) diff --git a/src/freebox_jellyfin/preview.py b/src/freebox_jellyfin/preview.py index 1b95d3e..5e67e3f 100644 --- a/src/freebox_jellyfin/preview.py +++ b/src/freebox_jellyfin/preview.py @@ -1,6 +1,8 @@ """Lance l'application sur le PC avec qmlscene (Qt 5) et libfbxqml.""" import argparse import os +import subprocess +import sys from .project import APP_DIR, REPO_DIR, libfbxqml, qmlscene @@ -9,7 +11,27 @@ def main(argv=None): parser = argparse.ArgumentParser(prog="freebox-jellyfin preview", description=__doc__) parser.add_argument("--fullscreen", action="store_true", help="lance Jellyfin.qml en plein écran, comme sur la box (sinon fenêtre 1280x720)") + parser.add_argument("--fake-server", action="store_true", + help="démarre aussi le faux serveur Jellyfin (127.0.0.1, port --fake-port)") + parser.add_argument("--fake-port", type=int, default=8096, help="port du faux serveur (défaut : 8096)") args = parser.parse_args(argv) lib, scene = libfbxqml(), qmlscene() qml = APP_DIR / "Jellyfin.qml" if args.fullscreen else REPO_DIR / "tools" / "preview.qml" - os.execv(scene, [scene, "-I", str(lib), str(qml)]) + command = [scene, "-I", str(lib), str(qml)] + if not args.fake_server: + os.execv(scene, command) + + from . import fake_server + try: + server = fake_server.start(("127.0.0.1", args.fake_port)) + except OSError as error: + sys.exit("Faux serveur : port %d indisponible (%s). Essayer --fake-port." % (args.fake_port, error)) + print("Faux serveur Jellyfin sur %s : dans l'app, adresse 127.0.0.1, port %d ;" + " comptes alice / secret et bob (sans mot de passe)." % (server.url, args.fake_port), flush=True) + try: + return subprocess.call(command) + except KeyboardInterrupt: + return 130 + finally: + server.shutdown() + server.server_close() diff --git a/src/freebox_jellyfin/test.py b/src/freebox_jellyfin/test.py new file mode 100644 index 0000000..024f89e --- /dev/null +++ b/src/freebox_jellyfin/test.py @@ -0,0 +1,102 @@ +"""Tests de l'application, sur le PC, en trois étapes (arrêt à la première en échec) : + + 1. règles du Freebox Player (boxrules : ES5, QtQuick 2.5, qmldir, singletons) ; + 2. tests Python de l'outillage (tests/python, unittest) ; + 3. tests QML (tests/qml/tst_*.qml, qmltestrunner) contre le faux serveur Jellyfin + (fake_server.py), dont l'adresse est fournie aux tests par le module QML TestEnv. + + freebox-jellyfin test tout + freebox-jellyfin test --qml tst_session.qml un seul fichier de tests QML + freebox-jellyfin test Session::test_logout une seule fonction (nom du TestCase::fonction) +""" +import argparse +import os +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +from . import boxrules, fake_server +from .project import APP_DIR, REPO_DIR, libfbxqml + +TESTS_DIR = REPO_DIR / "tests" +QML_TESTS = TESTS_DIR / "qml" +PYTHON_TESTS = TESTS_DIR / "python" + + +def qmltestrunner(): + path = os.environ.get("QMLTESTRUNNER") or shutil.which("qmltestrunner") or "/usr/lib/qt5/bin/qmltestrunner" + if not shutil.which(path) and not os.path.exists(path): + sys.exit("qmltestrunner introuvable : sudo apt install qtdeclarative5-dev-tools qml-module-qttest") + return path + + +def run_rules(): + problems = boxrules.check_app(APP_DIR) + if problems: + print("Échec : règles du Freebox Player non respectées :", file=sys.stderr) + print("\n".join(problems), file=sys.stderr) + return False + print("Règles du Freebox Player : OK") + return True + + +def run_python(): + if not PYTHON_TESTS.is_dir(): + return True + suite = unittest.defaultTestLoader.discover(str(PYTHON_TESTS), top_level_dir=str(PYTHON_TESTS)) + result = unittest.TextTestRunner(verbosity=1).run(suite) + return result.wasSuccessful() + + +def _test_env(folder, server): + """Module QML TestEnv : Env.baseUrl / Env.host / Env.port du faux serveur.""" + module = Path(folder) / "TestEnv" + module.mkdir() + host, port = server.server_address[:2] + (module / "qmldir").write_text("module TestEnv\nEnv 1.0 Env.js\n", encoding="utf-8") + (module / "Env.js").write_text( + '.pragma library\nvar baseUrl = "%s";\nvar host = "%s";\nvar port = %d;\n' % (server.url, host, port), + encoding="utf-8") + + +def run_qml(qml_file, functions): + runner, lib = qmltestrunner(), libfbxqml() + target = QML_TESTS / qml_file if qml_file else QML_TESTS + if not target.exists(): + sys.exit("Tests QML introuvables : %s" % target) + server = fake_server.start() + try: + with tempfile.TemporaryDirectory() as folder: + os.chmod(folder, 0o700) + _test_env(folder, server) + runtime = Path(folder) / "runtime" + runtime.mkdir(mode=0o700) + # Rendu logiciel hors écran : comme check, fonctionne en CI (pas d'OpenGL). + env = dict(os.environ, XDG_RUNTIME_DIR=str(runtime), QT_QPA_PLATFORM="offscreen", + QT_QUICK_BACKEND="software", QT_LOGGING_RULES="qt.multimedia*=false") + command = [runner, "-input", str(target), "-import", str(lib), "-import", folder] + list(functions) + print("Tests QML (%s), faux serveur sur %s" % (target.relative_to(REPO_DIR), server.url), flush=True) + result = subprocess.run(command, env=env) + return result.returncode == 0 + finally: + server.shutdown() + server.server_close() + + +def main(argv=None): + parser = argparse.ArgumentParser(prog="freebox-jellyfin test", description=__doc__.splitlines()[0], + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog="\n".join(__doc__.splitlines()[1:])) + parser.add_argument("--qml", metavar="FICHIER", help="un seul fichier de tests/qml (ex. tst_session.qml)") + parser.add_argument("--no-python", action="store_true", help="sauter les tests Python de l'outillage") + parser.add_argument("functions", nargs="*", help="fonctions QML à lancer (TestCase::fonction)") + args = parser.parse_args(argv) + + if not run_rules(): + return 1 + if not args.no_python and not args.qml and not args.functions and not run_python(): + return 1 + return 0 if run_qml(args.qml, args.functions) else 1 diff --git a/tests/python/test_boxrules.py b/tests/python/test_boxrules.py new file mode 100644 index 0000000..988ecde --- /dev/null +++ b/tests/python/test_boxrules.py @@ -0,0 +1,113 @@ +import tempfile +import textwrap +import unittest +from pathlib import Path + +from freebox_jellyfin import boxrules + + +def es5(code): + return boxrules.check_es5("x.js", textwrap.dedent(code)) + + +class Es5Test(unittest.TestCase): + def test_detects_es6(self): + cases = { + "let a = 1;": "let", + "const b = 2;": "const", + "list.map(x => x * 2);": "fléchée", + "var s = `a${b}`;": "gabarit", + "class A {}": "class", + "for (var x of list) {}": "for…of", + "f(...args);": "...", + } + for code, expected in cases.items(): + with self.subTest(code=code): + problems = es5(code) + self.assertEqual(len(problems), 1, problems) + self.assertIn(expected, problems[0]) + + def test_ignores_comments_strings_and_regexes(self): + code = """ + // let a = 1; x => y + /* const b = 2; + `gabarit` */ + var s = "let c = 3 => ...rest"; + var t = 'const d = `e`'; + var url = /^https?:\\/\\//i; // (regex avec « // ») + var clean = text.replace(/\\/+$/, ""); + var letter = constant + lettuce; // mots qui commencent par let/const + var ok = a >= b; + """ + self.assertEqual(es5(code), []) + + def test_reports_line_numbers(self): + self.assertEqual(es5("var a;\n\nlet b;\n"), ["x.js:3: « let » (ES6) : utiliser var"]) + + +class ImportsTest(unittest.TestCase): + def test_qtquick_version(self): + self.assertEqual(boxrules.check_imports("a.qml", "import QtQuick 2.5\n"), []) + self.assertEqual(boxrules.check_imports("a.qml", "import QtQuick 2.0\n"), []) + self.assertEqual(len(boxrules.check_imports("a.qml", "import QtQuick 2.6\n")), 1) + self.assertEqual(len(boxrules.check_imports("a.qml", "import QtQuick 2.15\n")), 1) + + def test_forbidden_imports(self): + self.assertEqual(len(boxrules.check_imports("a.qml", "import QtQuick.Controls 1.4\n")), 1) + self.assertEqual(len(boxrules.check_imports("a.qml", 'import "."\n')), 1) + self.assertEqual(boxrules.check_imports("a.qml", '// import QtQuick 2.15\nimport "../Shared"\n'), []) + + +class DirectoriesTest(unittest.TestCase): + def make_app(self, files): + folder = tempfile.TemporaryDirectory() + self.addCleanup(folder.cleanup) + root = Path(folder.name) + for name, content in files.items(): + path = root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(textwrap.dedent(content), encoding="utf-8") + return root + + def test_valid_layout(self): + app = self.make_app({ + "Main.qml": 'import QtQuick 2.5\nimport "Components"\nimport "Shared"\nItem {}\n', + "Components/qmldir": "Button 1.0 Button.qml\n", + "Components/Button.qml": 'import QtQuick 2.5\nimport "../Shared"\nItem { width: Theme.size }\n', + "Shared/qmldir": "singleton Theme 1.0 Theme.qml\n", + "Shared/Theme.qml": "pragma Singleton\nimport QtQuick 2.5\nQtObject { property int size: 1 }\n", + }) + self.assertEqual(boxrules.check_directories(app), []) + + def test_missing_qmldir_and_entries(self): + app = self.make_app({ + "Main.qml": 'import "Components"\nimport "Other"\nItem {}\n', + "Components/qmldir": "Button 1.0 Button.qml\nGone 1.0 Gone.qml\n", + "Components/Button.qml": "Item {}\n", + "Components/Card.qml": "Item {}\n", + "Other/Thing.qml": "Item {}\n", + }) + problems = "\n".join(boxrules.check_directories(app)) + self.assertIn("Card.qml absent", problems) + self.assertIn("Gone.qml introuvable", problems) + self.assertIn("Other/: importé mais sans qmldir", problems) + + def test_singleton_cycles(self): + app = self.make_app({ + "Main.qml": 'import "Shared"\nItem {}\n', + "Shared/qmldir": "singleton Theme 1.0 Theme.qml\nsingleton Style 1.0 Style.qml\nCard 1.0 Card.qml\n", + "Shared/Theme.qml": "QtObject {}\n", + "Shared/Style.qml": "QtObject {}\n", + "Shared/Card.qml": "Item { width: Theme.size }\n", + }) + problems = "\n".join(boxrules.check_directories(app)) + self.assertIn("plusieurs singletons", problems) + self.assertIn("Card.qml: utilise le singleton Theme", problems) + + def test_real_app_is_clean(self): + from freebox_jellyfin.project import APP_DIR + self.assertEqual(boxrules.check_app(APP_DIR), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/python/test_tooling.py b/tests/python/test_tooling.py new file mode 100644 index 0000000..06ff331 --- /dev/null +++ b/tests/python/test_tooling.py @@ -0,0 +1,97 @@ +import json +import os +import tarfile +import tempfile +import unittest +import urllib.error +import urllib.request + +from freebox_jellyfin import fake_server, package + + +class PackageTest(unittest.TestCase): + def test_file_selection(self): + files = package.collect_files() + self.assertIn("manifest.json", files) + self.assertIn("Jellyfin.qml", files) + self.assertIn(os.path.join("Core", "qmldir"), files) + for name in files: + self.assertFalse(name.endswith((".fbxproject", ".user", ".py")), name) + self.assertFalse(any(part.startswith(".") for part in name.split(os.sep)), name) + + def test_manifest_matches_client_version(self): + manifest = package.check_manifest(package.collect_files()) + self.assertRegex(manifest["version"], r"^\d+\.\d+\.\d+$") + + def test_archive_layout(self): + files = package.collect_files() + with tempfile.TemporaryDirectory() as folder: + output = os.path.join(folder, "p.tar.gz") + package.build_archive(files, output) + with tarfile.open(output) as archive: + names = archive.getnames() + self.assertIn("Core", names) # entrées de dossiers + self.assertIn("Core/Session.qml", names) # chemins relatifs à app/ + self.assertEqual(archive.getmember("Core").type, tarfile.DIRTYPE) + + +class FakeServerTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.server = fake_server.start() + + @classmethod + def tearDownClass(cls): + cls.server.shutdown() + cls.server.server_close() + + def call(self, method, path, body=None, token=None): + headers = {"Content-Type": "application/json"} + if token: + headers["Authorization"] = 'MediaBrowser Client="t", Token="%s"' % token + data = json.dumps(body).encode() if body is not None else None + request = urllib.request.Request(self.server.url + path, data=data, method=method, headers=headers) + try: + with urllib.request.urlopen(request, timeout=5) as response: + raw = response.read() + return response.status, json.loads(raw) if raw and raw[:1] in b"[{\"tf" else raw + except urllib.error.HTTPError as error: + return error.code, None + + def setUp(self): + self.call("POST", "/__reset") + + def test_auth_required(self): + self.assertEqual(self.call("GET", "/UserViews")[0], 401) + status, data = self.call("POST", "/Users/AuthenticateByName", {"Username": "alice", "Pw": "secret"}) + self.assertEqual(status, 200) + self.assertEqual(self.call("GET", "/UserViews", token=data["AccessToken"])[0], 200) + self.assertEqual(self.call("POST", "/Users/AuthenticateByName", {"Username": "alice", "Pw": "x"})[0], 401) + + def test_paging(self): + token = "token-user-alice" + status, data = self.call("GET", "/Items?parentId=lib-movies&startIndex=20&limit=10", token=token) + self.assertEqual((len(data["Items"]), data["TotalRecordCount"]), (5, 25)) + + def test_mock_and_journal(self): + self.call("POST", "/__mock", {"path": "/Users/Public", "status": 503}) + self.assertEqual(self.call("GET", "/Users/Public")[0], 503) + status, journal = self.call("GET", "/__requests") + self.assertEqual([r["path"] for r in journal], ["/Users/Public"]) + self.call("POST", "/__reset") + self.assertEqual(self.call("GET", "/Users/Public")[0], 200) + + def test_stop_updates_resume_point(self): + token = "token-user-alice" + self.call("POST", "/Sessions/Playing/Stopped", {"ItemId": "movie-01", "PositionTicks": 1234}, token=token) + status, item = self.call("GET", "/Items/movie-01", token=token) + self.assertEqual(item["UserData"]["PlaybackPositionTicks"], 1234) + + def test_images_are_png(self): + status, data = self.call("GET", "/Items/movie-01/Images/Primary?tag=x") + self.assertEqual(status, 200) + self.assertTrue(data.startswith(b"\x89PNG")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/qml/JellyfinTestCase.qml b/tests/qml/JellyfinTestCase.qml new file mode 100644 index 0000000..d8ff385 --- /dev/null +++ b/tests/qml/JellyfinTestCase.qml @@ -0,0 +1,81 @@ +import QtQuick 2.5 +import QtTest 1.2 +import TestEnv 1.0 + +// Base des tests : accès au faux serveur Jellyfin (src/freebox_jellyfin/fake_server.py) +// démarré par `freebox-jellyfin test`, qui fournit son adresse via le module TestEnv. +// Les tests tournent sur le PC (Qt 5.15) : ce dossier n'est pas soumis aux règles ES5. +TestCase { + id: testCase + + readonly property string serverUrl: Env.baseUrl + readonly property string serverHost: Env.host + readonly property string serverPort: String(Env.port) + + // Lance start(done) et attend l'appel de done(...) ; renvoie ses arguments (tableau). + function waitCallback(start, timeout, message) { + var box = { done: false, args: [] }; + start(function () { + box.args = Array.prototype.slice.call(arguments); + box.done = true; + }); + tryVerify(function () { return box.done; }, timeout || 5000, message || "callback jamais appelé"); + return box.args; + } + + // Requête au faux serveur ; renvoie la réponse JSON décodée (ou null). + function http(method, path, body) { + var result = waitCallback(function (done) { + var xhr = new XMLHttpRequest(); + xhr.onreadystatechange = function () { + if (xhr.readyState === XMLHttpRequest.DONE) + done(xhr.status, xhr.responseText); + }; + xhr.open(method, serverUrl + path); + if (body !== undefined) { + xhr.setRequestHeader("Content-Type", "application/json"); + xhr.send(JSON.stringify(body)); + } else { + xhr.send(); + } + }, 5000, "faux serveur injoignable : " + method + " " + path); + return result[1] ? JSON.parse(result[1]) : null; + } + + function resetServer() { + http("POST", "/__reset"); + } + + // Réponse imposée : { path, method?, status?, body?, raw?, delay? (ms) } + function mock(spec) { + http("POST", "/__mock", spec); + } + + // Requêtes reçues par le faux serveur (toutes, ou celles d'un chemin). + function requests(path) { + var all = http("GET", "/__requests"); + return path ? all.filter(function (r) { return r.path === path; }) : all; + } + + function lastRequest(path) { + var list = requests(path); + return list.length > 0 ? list[list.length - 1] : null; + } + + // Premier descendant (parcours en largeur) pour lequel predicate(objet) est vrai. + function findChild(root, predicate) { + var queue = [root]; + while (queue.length > 0) { + var item = queue.shift(); + if (item !== root && predicate(item)) + return item; + var children = item.children || []; + for (var i = 0; i < children.length; i++) + queue.push(children[i]); + var resources = item.resources || []; + for (var j = 0; j < resources.length; j++) + queue.push(resources[j]); + } + return null; + } +} diff --git a/tests/qml/tst_flow.qml b/tests/qml/tst_flow.qml new file mode 100644 index 0000000..4234896 --- /dev/null +++ b/tests/qml/tst_flow.qml @@ -0,0 +1,212 @@ +import QtQuick 2.5 +import QtTest 1.2 +import "../../app/Core" + +// Parcours complets à la télécommande (touches simulées), comme sur la box : +// Navigator + vrais écrans + vraie Session, contre le faux serveur Jellyfin. +// L'interface est hors du TestCase : il est invisible, et KeyNavigation ignore les +// éléments invisibles. +Item { + width: 1280 + height: 720 + + Session { + id: session + } + + Navigator { + id: navigator + anchors.fill: parent + session: session + focus: true + } + + JellyfinTestCase { + id: testCase + name: "Parcours" + when: windowShown + + function init() { + session.cancel(); + session.logout(); + session.currentServer = null; + session.devUsers = []; + session.servers.clear(); + session._quickConnectPoll.interval = 5000; + resetServer(); + navigator.reset("ServerSelect"); + waitTitle("Sélectionner un serveur"); + } + + // Écran affiché par le Navigator. + function view() { + var loader = findChild(navigator, function (o) { return o.setSource !== undefined && o.item !== undefined; }); + return loader ? loader.item : null; + } + + function waitTitle(title, timeout) { + tryVerify(function () { var v = view(); return v !== null && v.title === title; }, timeout || 5000, + "écran « " + title + " » attendu, affiché : « " + (view() ? view().title : "") + " »"); + wait(50); // focus initial posé par le Navigator (onLoaded) + } + + function type(text) { + for (var i = 0; i < text.length; i++) + keyClick(text.charAt(i)); + } + + function press(key, times) { + for (var i = 0; i < (times || 1); i++) + keyClick(key); + } + + // Connexion sans passer par l'interface (pour les parcours qui commencent plus loin). + function signedIn() { + waitCallback(function (done) { session.connectToServer(serverHost, serverPort, done); }, 15000); + var result = waitCallback(function (done) { session.authenticate("alice", "secret", done); }); + compare(result[0], null); + } + + function rowTitles() { + return view().rows.map(function (r) { return r.title; }); + } + + // ----------------------------------------------------------- connexion + + function test_addServerAndSignInWithPassword() { + press(Qt.Key_Return); // « Ajouter un serveur » + waitTitle("Ajouter un serveur"); + type(serverHost); + press(Qt.Key_Return); // champ suivant : port + type(serverPort); + press(Qt.Key_Return); // connexion + waitTitle("Qui regarde ?", 15000); + tryVerify(function () { return !view().loading; }, 5000); + compare(view().users.length, 2); + + press(Qt.Key_Return); // alice (mot de passe) + waitTitle("Se connecter"); + compare(view().username, "alice"); + type("faux"); + press(Qt.Key_Return); + tryCompare(view(), "error", "Nom d'utilisateur ou mot de passe incorrect.", 5000); + compare(view().title, "Se connecter"); + press(Qt.Key_Backspace, 4); // le focus est revenu sur le mot de passe + type("secret"); + press(Qt.Key_Return); + waitTitle("Bonjour alice"); + tryVerify(function () { return !view().loading; }, 5000); + compare(rowTitles(), ["Reprendre", "Mes médias", "Ajouts récents · Films", "Ajouts récents · Séries"]); + compare(navigator.depth, 1, "Retour ne doit pas revenir à l'écran de connexion"); + + compare(session.servers.count, 1, "serveur enregistré"); + compare(session.servers.get(0).address, "http://" + serverHost + ":" + serverPort); + } + + function test_savedServerAndUserWithoutPassword() { + waitCallback(function (done) { session.connectToServer(serverHost, serverPort, done); }, 15000); + navigator.reset("ServerSelect"); + waitTitle("Sélectionner un serveur"); + press(Qt.Key_Return); // le serveur enregistré a le focus + waitTitle("Qui regarde ?"); + tryVerify(function () { return !view().loading; }, 5000); + press(Qt.Key_Right); // bob + press(Qt.Key_Return); // connexion directe, sans mot de passe + waitTitle("Bonjour bob"); + } + + function test_invalidServerShowsError() { + press(Qt.Key_Return); + waitTitle("Ajouter un serveur"); + type("127.0.0.1"); + press(Qt.Key_Return); + type("1"); + press(Qt.Key_Return); + tryCompare(view(), "error", "Aucun serveur Jellyfin trouvé à cette adresse.", 15000); + compare(view().title, "Ajouter un serveur"); + compare(view().busy, false); + } + + function test_quickConnect() { + session._quickConnectPoll.interval = 50; + waitCallback(function (done) { session.connectToServer(serverHost, serverPort, done); }, 15000); + navigator.reset("ServerSelect"); + waitTitle("Sélectionner un serveur"); + press(Qt.Key_Return); + waitTitle("Qui regarde ?"); + tryVerify(function () { return !view().loading; }, 5000); + press(Qt.Key_Right, 2); // « Ajouter un compte » + press(Qt.Key_Return); + waitTitle("Se connecter"); + tryVerify(function () { return view().quickConnectAvailable; }, 5000); + press(Qt.Key_Down, 2); // nom → mot de passe → « Se connecter » + press(Qt.Key_Right); // « Utiliser Quick Connect » + press(Qt.Key_Return); + waitTitle("Quick Connect"); + tryCompare(view(), "quickConnectCode", "123456", 5000); + http("POST", "/__quickconnect/authorize"); + waitTitle("Bonjour alice"); + } + + // ----------------------------------------------------------- catalogue + + function test_homeToDetailsAndBack() { + signedIn(); + navigator.reset("Home"); + waitTitle("Bonjour alice"); + tryVerify(function () { return !view().loading; }, 5000); + press(Qt.Key_Return); // 1re carte de « Reprendre » + waitTitle("Film direct"); + tryVerify(function () { return view().item !== null; }, 5000); + compare(view().resumeMs, 600000); + press(Qt.Key_Escape); + waitTitle("Bonjour alice"); + press(Qt.Key_Escape); // depuis l'accueil : choix de l'utilisateur + waitTitle("Qui regarde ?"); + compare(navigator.depth, 2); + } + + function test_libraryAndSeries() { + signedIn(); + navigator.reset("Home"); + waitTitle("Bonjour alice"); + tryVerify(function () { return !view().loading; }, 5000); + press(Qt.Key_Down); // « Mes médias » + press(Qt.Key_Return); // Films + waitTitle("Films"); + tryCompare(view(), "total", 25, 5000); + press(Qt.Key_Escape); + waitTitle("Bonjour alice"); + tryVerify(function () { return !view().loading; }, 5000); + press(Qt.Key_Down, 3); // « Ajouts récents · Séries » + press(Qt.Key_Return); + waitTitle("Série test"); + tryVerify(function () { return view().seasons.length === 2; }, 5000); + press(Qt.Key_Return); // Saison 1 (titre : la série, sous-titre : la saison) + tryVerify(function () { return view().subtitle === "Saison 1"; }, 5000, "écran de la saison attendu"); + tryVerify(function () { return view().episodes !== undefined; }, 5000); + } + + // De bout en bout : la lecture échoue (pas de flux sur le faux serveur), puis Retour. + // Le point de reprise (10 min) doit rester intact sur le serveur. + function test_failedPlaybackKeepsResumePoint() { + signedIn(); + navigator.reset("Home"); + navigator.push("Details", { itemId: "movie-direct" }); + waitTitle("Film direct"); + tryVerify(function () { return view().item !== null; }, 5000); + press(Qt.Key_Return); // « Reprendre à 10:00 » + tryVerify(function () { return view().itemId === "movie-direct" && view().info !== null; }, 5000); + compare(view().startMs, 600000); + wait(1500); + press(Qt.Key_Escape); + waitTitle("Film direct"); + wait(300); + compare(requests("/Sessions/Playing").length, 0); + compare(requests("/Sessions/Playing/Progress").length, 0); + compare(requests("/Sessions/Playing/Stopped").length, 0); + var item = waitCallback(function (done) { session.loadItem("movie-direct", done); })[1]; + compare(item.positionTicks, 6000000000); + } + } +} diff --git a/tests/qml/tst_helpers.qml b/tests/qml/tst_helpers.qml new file mode 100644 index 0000000..ee5db46 --- /dev/null +++ b/tests/qml/tst_helpers.qml @@ -0,0 +1,111 @@ +import QtQuick 2.5 +import QtTest 1.2 +import "../../app/Shared/Format.js" as Format +import "../../app/Shared/Remote.js" as Remote +import "../../app/Core/DeviceProfile.js" as DeviceProfile + +// Fonctions pures : Format.js, Remote.js, DeviceProfile.js. +TestCase { + name: "Helpers" + + function test_ticks() { + compare(Format.ticksToMs(600000000), 60000); + compare(Format.msToTicks(1500), 15000000); + compare(Format.ticksToMs(undefined), 0); + compare(Format.msToTicks(null), 0); + } + + function test_runtime_data() { + return [ + { tag: "vide", minutes: 0, expected: "" }, + { tag: "minutes", minutes: 52, expected: "52 min" }, + { tag: "heure pile", minutes: 120, expected: "2 h" }, + { tag: "heure + minutes < 10", minutes: 63, expected: "1 h 03 min" }, + { tag: "heure + minutes", minutes: 94, expected: "1 h 34 min" } + ]; + } + + function test_runtime(data) { + compare(Format.runtime(Format.msToTicks(data.minutes * 60000)), data.expected); + } + + function test_clock_data() { + return [ + { tag: "zéro", ms: 0, expected: "0:00" }, + { tag: "négatif", ms: -5000, expected: "0:00" }, + { tag: "secondes", ms: 4000, expected: "0:04" }, + { tag: "minutes", ms: 245000, expected: "4:05" }, + { tag: "heures", ms: 3723000, expected: "1:02:03" }, + { tag: "heures, minutes à 2 chiffres", ms: 2 * 3600000 + 45 * 60000, expected: "2:45:00" } + ]; + } + + function test_clock(data) { + compare(Format.clock(data.ms), data.expected); + } + + function test_cardLabels() { + var episode = { type: "Episode", name: "Pilote", seriesName: "Série", parentIndexNumber: 1, indexNumber: 3 }; + compare(Format.episodeCode(episode), "S1 · É3"); + compare(Format.cardTitle(episode), "Série"); + compare(Format.cardSubtitle(episode), "S1 · É3 – Pilote"); + compare(Format.episodeCode({ type: "Movie" }), ""); + compare(Format.cardTitle({ type: "Movie", name: "Film" }), "Film"); + compare(Format.cardSubtitle({ type: "Movie", year: 1997 }), "1997"); + compare(Format.cardSubtitle({ type: "Movie", year: 0 }), ""); + compare(Format.cardSubtitle({ type: "Series", childCount: 1 }), "1 saison"); + compare(Format.cardSubtitle({ type: "Series", childCount: 3 }), "3 saisons"); + } + + function test_progress() { + compare(Format.progress({ playedPercentage: 25 }), 0.25); + compare(Format.progress({ runtimeTicks: 1000, positionTicks: 500 }), 0.5); + compare(Format.progress({ runtimeTicks: 0, positionTicks: 0 }), 0); + } + + function test_infoLine() { + compare(Format.infoLine({ type: "Movie", year: 1997, runtimeTicks: Format.msToTicks(94 * 60000), + rating: "Tous publics", communityRating: 7.46 }), + "1997 · 1 h 34 min · Tous publics · 7,5/10"); + compare(Format.infoLine({ type: "Episode", parentIndexNumber: 2, indexNumber: 1 }), "S2 · É1"); + compare(Format.infoLine({ type: "Movie" }), ""); + } + + function test_remote() { + verify(Remote.isAccept(Qt.Key_Return)); + verify(Remote.isAccept(Qt.Key_Enter)); + verify(Remote.isAccept(Qt.Key_Select)); + verify(!Remote.isAccept(Qt.Key_Space)); + verify(Remote.isBack(Qt.Key_Back)); + verify(Remote.isBack(Qt.Key_Escape)); + verify(!Remote.isBack(Qt.Key_Backspace)); + } + + // La Revolution ne lit que le H.264 : jamais de HEVC déclaré, sinon Jellyfin + // enverrait un flux illisible au lieu de transcoder. + function test_deviceProfile_codecs() { + var profile = DeviceProfile.profile(); + verify(profile.DirectPlayProfiles.length > 0); + for (var i = 0; i < profile.DirectPlayProfiles.length; i++) { + compare(profile.DirectPlayProfiles[i].VideoCodec, "h264"); + } + var transcode = profile.TranscodingProfiles[0]; + compare(transcode.Protocol, "hls"); + compare(transcode.VideoCodec, "h264"); + compare(profile.MaxStreamingBitrate, DeviceProfile.maxBitrate); + verify(JSON.stringify(profile).toLowerCase().indexOf("hevc") < 0); + verify(JSON.stringify(profile).toLowerCase().indexOf("h265") < 0); + } + + // Sous-titres texte « External » : sinon Jellyfin transcode pour les incruster. + function test_deviceProfile_subtitles() { + var subtitles = DeviceProfile.profile().SubtitleProfiles; + var formats = []; + for (var i = 0; i < subtitles.length; i++) { + compare(subtitles[i].Method, "External", subtitles[i].Format); + formats.push(subtitles[i].Format); + } + verify(formats.indexOf("srt") >= 0); + verify(formats.indexOf("subrip") >= 0); + } +} diff --git a/tests/qml/tst_player.qml b/tests/qml/tst_player.qml new file mode 100644 index 0000000..4028330 --- /dev/null +++ b/tests/qml/tst_player.qml @@ -0,0 +1,258 @@ +import QtQuick 2.5 +import QtTest 1.2 +import "../../app/Views" + +// Views/PlayerView.qml : ce qui est signalé au serveur (reprise, « vu »). +// Règle critique : ne jamais écraser le point de reprise. Rien n'est signalé avant que la +// lecture ait démarré ET atteint la position de reprise, et jamais d'arrêt à la position 0. +// +// La session est simulée, et l'état du lecteur est piloté directement sur le VideoSurface +// (sans source, son interrogation périodique du lecteur reste à l'arrêt). Le lecteur est créé +// dans « stage » : le TestCase est invisible, et le focus ignore les éléments invisibles. +Item { + id: stage + width: 1280 + height: 720 + + TestCase { + id: testCase + name: "PlayerView" + when: windowShown + + property var player: null + property var video: null + property var session: null + property var navigator: null + + Component { + id: fakeSessionComponent + QtObject { + property var reports: [] + property var pending: null + property string preparedItem: "" + function preparePlayback(itemId, callback) { + preparedItem = itemId; + pending = callback; + } + function reportPlayback(event, info, positionMs, paused) { + var list = reports.slice(); + list.push({ event: event, position: positionMs, paused: paused, itemId: info.itemId }); + reports = list; + } + } + } + + Component { + id: fakeNavigatorComponent + QtObject { + property int pops: 0 + function pop() { + pops++; + return true; + } + } + } + + Component { + id: playerComponent + PlayerView { + anchors.fill: parent + } + } + + function open(startMs) { + session = fakeSessionComponent.createObject(testCase); + navigator = fakeNavigatorComponent.createObject(testCase); + player = playerComponent.createObject(stage, { + session: session, navigator: navigator, itemId: "movie-01", title: "Film", startMs: startMs || 0 + }); + verify(player !== null, "PlayerView non créé"); + video = findVideo(player); + verify(video !== null, "VideoSurface introuvable"); + compare(session.preparedItem, "movie-01"); + } + + // Réponse de Session.preparePlayback (URL vide : aucun vrai lecteur ne démarre). + function prepared() { + session.pending(null, { url: "", itemId: "movie-01", mediaSourceId: "src", playSessionId: "ps", + playMethod: "Transcode" }); + } + + // Même ordre que VideoSurface._poll() : position et durée, puis état. + function play(positionMs, durationMs) { + video.duration = durationMs || 7200000; + video.position = positionMs; + video.playerState = "playing"; + } + + function close() { + player.destroy(); + player = null; + wait(20); + } + + function events() { + return session.reports.map(function (r) { return r.event + "@" + Math.round(r.position); }); + } + + function findVideo(root) { + var queue = [root]; + while (queue.length > 0) { + var item = queue.shift(); + if (item !== root && item.backendName !== undefined && item.playerState !== undefined) + return item; + for (var i = 0; i < item.children.length; i++) + queue.push(item.children[i]); + } + return null; + } + + function findTimer(root, interval) { + for (var i = 0; i < root.resources.length; i++) { + if (root.resources[i].interval === interval) + return root.resources[i]; + } + return null; + } + + function cleanup() { + if (player) + close(); + if (session) + session.destroy(); + if (navigator) + navigator.destroy(); + session = navigator = video = null; + } + + // ---------------------------------------------------------------- reprise + + // Le cas qui a déjà effacé des points de reprise : lecture lancée mais position de + // reprise jamais atteinte (déplacement initial raté), puis Retour. + function test_resume_nothingReportedBeforeResumePoint() { + open(600000); + prepared(); + play(0); + play(1000); + compare(events(), [], "rien avant la position de reprise"); + close(); + compare(events(), [], "pas d'arrêt signalé : le point de reprise serait écrasé"); + } + + function test_resume_reportedOnceReached() { + open(600000); + prepared(); + play(0); + video.position = 590000; // à moins de 15 s de la reprise + compare(events(), ["start@590000"]); + video.position = 601000; + compare(events(), ["start@590000"], "start une seule fois"); + close(); + compare(events(), ["start@590000", "stop@601000"]); + } + + function test_resume_notStartedWhilePaused() { + open(600000); + prepared(); + video.duration = 7200000; + video.playerState = "paused"; + video.position = 600000; + compare(events(), [], "pas de start tant que la lecture n'a pas démarré"); + video.playerState = "playing"; + compare(events(), ["start@600000"]); + } + + // ------------------------------------------------------ depuis le début + + function test_fromStart_startAtZeroButNoStopAtZero() { + open(0); + prepared(); + play(0); + compare(events(), ["start@0"]); + close(); + compare(events(), ["start@0"], "jamais d'arrêt signalé à la position 0"); + } + + function test_fromStart_stopWithPositionAndPause() { + open(0); + prepared(); + play(5000); + video.playerState = "paused"; + close(); + compare(events(), ["start@5000", "stop@5000"]); + compare(session.reports[1].paused, true); + } + + function test_progressEvery10s() { + open(0); + prepared(); + play(1000); + var timer = findTimer(player, 10000); + verify(timer !== null, "minuterie de progression introuvable"); + verify(timer.running); + timer.interval = 50; + video.position = 2000; + tryVerify(function () { return events().indexOf("progress@2000") >= 0; }, 2000); + video.position = 0; + var count = session.reports.length; + wait(200); + compare(session.reports.length, count, "pas de progression signalée à la position 0"); + } + + // ------------------------------------------------------- échecs et fin + + function test_prepareError_nothingReported() { + open(600000); + session.pending("Lecture impossible (NoCompatibleStream)."); + compare(player.error, "Lecture impossible (NoCompatibleStream)."); + video.playerState = "playing"; + close(); + compare(events(), []); + } + + function test_playerError_nothingReported() { + open(0); + prepared(); + video.playerState = "error"; + close(); + compare(events(), []); + } + + function test_ended_stopsOnceAndLeaves() { + open(0); + prepared(); + play(7199000); + video.ended(); + compare(navigator.pops, 1); + close(); + compare(events(), ["start@7199000", "stop@7199000"], "un seul arrêt, même à la destruction"); + } + + // ------------------------------------------------------- télécommande + + // Haut/Bas réaffichent les informations de lecture (masquées au bout de 4 s). + function test_keys_showOsd() { + open(0); + prepared(); + play(100000); + player.forceActiveFocus(); + var osd = findChild(player, function (o) { return o.shown !== undefined; }); + verify(osd !== null, "OSD introuvable"); + osd.shown = false; + keyClick(Qt.Key_Down); + verify(osd.shown); + } + + function findChild(root, predicate) { + var queue = [root]; + while (queue.length > 0) { + var item = queue.shift(); + if (item !== root && predicate(item)) + return item; + for (var i = 0; i < item.children.length; i++) + queue.push(item.children[i]); + } + return null; + } + } +} diff --git a/tests/qml/tst_session.qml b/tests/qml/tst_session.qml new file mode 100644 index 0000000..13bcb3e --- /dev/null +++ b/tests/qml/tst_session.qml @@ -0,0 +1,472 @@ +import QtQuick 2.5 +import QtTest 1.2 +import "../../app/Core" + +// Core/Session.qml : fonctions pures, puis API Jellyfin contre le faux serveur. +JellyfinTestCase { + id: testCase + name: "Session" + + Session { + id: session + } + + function init() { + session.cancel(); + session.accessToken = ""; + session.currentUser = null; + session.currentServer = null; + session.devUsers = []; + session.servers.clear(); + session._quickConnectPoll.interval = 5000; + resetServer(); + } + + function connect() { + var result = waitCallback(function (done) { + session.connectToServer(serverHost, serverPort, done); + }, 15000, "connectToServer"); + compare(result[0], null, "erreur de connexion"); + return result[1]; + } + + function signIn(name, password) { + connect(); + var result = waitCallback(function (done) { + session.authenticate(name || "alice", password === undefined ? "secret" : password, done); + }); + compare(result[0], null, "erreur d'authentification"); + return result[1]; + } + + // ------------------------------------------------------- fonctions pures + + function test_serverCandidates() { + compare(session.serverCandidates("box.lan", ""), + ["https://box.lan", "http://box.lan:8096", "https://box.lan:8920", "http://box.lan"]); + compare(session.serverCandidates(" box.lan/ ", ""), + ["https://box.lan", "http://box.lan:8096", "https://box.lan:8920", "http://box.lan"]); + compare(session.serverCandidates("box.lan", "8100"), ["https://box.lan:8100", "http://box.lan:8100"]); + compare(session.serverCandidates("192.168.1.20:8096", ""), + ["https://192.168.1.20:8096", "http://192.168.1.20:8096"]); + compare(session.serverCandidates("http://box.lan", ""), ["http://box.lan"]); + compare(session.serverCandidates("https://box.lan", "8920"), ["https://box.lan:8920"]); + compare(session.serverCandidates("https://box.lan:443", "8920"), ["https://box.lan:443"]); + compare(session.serverCandidates("", ""), []); + compare(session.serverCandidates(" ", "80"), []); + } + + function test_isValidPort() { + verify(session.isValidPort("1")); + verify(session.isValidPort("8096")); + verify(session.isValidPort("65535")); + verify(!session.isValidPort("0")); + verify(!session.isValidPort("65536")); + verify(!session.isValidPort("80a")); + verify(!session.isValidPort("-1")); + verify(!session.isValidPort("")); + } + + function test_query() { + compare(session._query({ a: 1, b: "", c: null, d: undefined, e: "x y&z", f: false }), + "a=1&e=x%20y%26z&f=false"); + } + + function test_toItem() { + var item = session._toItem({ + Id: "i1", Name: "Nom", Type: "Episode", ProductionYear: 2001, RunTimeTicks: 10, + ImageTags: { Primary: "p", Thumb: "t" }, BackdropImageTags: ["b"], + ParentBackdropItemId: "pb", ParentBackdropImageTags: ["pbt"], + SeriesId: "s", SeriesName: "Série", SeriesPrimaryImageTag: "sp", SeasonId: "se", + IndexNumber: 3, ParentIndexNumber: 1, ChildCount: 2, + UserData: { PlaybackPositionTicks: 5, PlayedPercentage: 50, Played: true } + }); + compare(item.id, "i1"); + compare(item.imageTag, "p"); + compare(item.thumbTag, "t"); + compare(item.backdropTag, "b"); + compare(item.parentBackdropTag, "pbt"); + compare(item.seriesPrimaryTag, "sp"); + compare(item.indexNumber, 3); + compare(item.parentIndexNumber, 1); + compare(item.positionTicks, 5); + compare(item.played, true); + // « index » est un rôle réservé des ListModel. + verify(!item.hasOwnProperty("index")); + + var empty = session._toItem({ Id: "i2" }); + compare(empty.name, ""); + compare(empty.imageTag, ""); + compare(empty.positionTicks, 0); + compare(empty.played, false); + compare(empty.isFolder, false); + } + + function test_imageUrls() { + compare(session.imageUrl("i", "Primary", "t", 100), "", "sans serveur"); + session.currentServer = { name: "S", address: "http://srv", id: "x" }; + compare(session.imageUrl("i", "Primary", "t", 100), "http://srv/Items/i/Images/Primary?tag=t&maxHeight=100&quality=90"); + compare(session.imageUrl("i", "Primary", "", 100), "", "sans tag"); + + var episode = { id: "e", type: "Episode", imageTag: "ei", seriesId: "s", seriesPrimaryTag: "sp" }; + verify(session.thumbUrl(episode).indexOf("/Items/e/Images/Primary") > 0); + compare(session.posterUrl({ id: "e", imageTag: "", seriesId: "s", seriesPrimaryTag: "sp" }, 200), + "http://srv/Items/s/Images/Primary?tag=sp&maxHeight=200&quality=90"); + var movie = { id: "m", type: "Movie", imageTag: "mp", thumbTag: "", backdropTag: "mb" }; + verify(session.thumbUrl(movie).indexOf("/Items/m/Images/Backdrop?tag=mb") > 0, "fond à défaut de Thumb"); + movie.backdropTag = ""; + verify(session.thumbUrl(movie).indexOf("/Items/m/Images/Primary?tag=mp") > 0, "affiche en dernier recours"); + compare(session.backdropUrl({ id: "e", backdropTag: "", parentBackdropItemId: "s", parentBackdropTag: "pb" }), + "http://srv/Items/s/Images/Backdrop?tag=pb&maxHeight=720&quality=90"); + } + + // ------------------------------------------------------------- serveurs + + // https échoue (serveur HTTP seul) : la sonde retient http, sur le port saisi. + function test_connect_detectsProtocol() { + var server = connect(); + compare(server.address, "http://" + serverHost + ":" + serverPort); + compare(server.name, "Serveur de test"); + compare(server.id, "fakeserver0000000000000000000001"); + compare(session.servers.count, 1); + compare(session.currentServer.address, server.address); + verify(requests("/System/Info/Public").length >= 1); + } + + function test_connect_sameServerNotDuplicated() { + connect(); + connect(); + compare(session.servers.count, 1); + } + + function test_connect_inputErrors() { + var result = waitCallback(function (done) { session.connectToServer(" ", "", done); }); + compare(result[0], "Veuillez saisir l'adresse du serveur."); + result = waitCallback(function (done) { session.connectToServer("box.lan", "70000", done); }); + compare(result[0], "Le port doit être un nombre entre 1 et 65535."); + compare(requests().length, 0, "aucune requête pour une saisie invalide"); + } + + function test_connect_unreachable() { + var result = waitCallback(function (done) { session.connectToServer("127.0.0.1", "1", done); }, 15000); + compare(result[0], "Aucun serveur Jellyfin trouvé à cette adresse."); + compare(session.servers.count, 0); + } + + function test_connect_notJellyfin() { + mock({ path: "/System/Info/Public", body: { Hello: "world" } }); + var result = waitCallback(function (done) { session.connectToServer(serverHost, serverPort, done); }, 15000); + compare(result[0], "Aucun serveur Jellyfin trouvé à cette adresse."); + } + + // ------------------------------------------------------- utilisateurs + + function test_publicUsers() { + connect(); + var result = waitCallback(function (done) { session.loadPublicUsers(done); }); + compare(result[0], null); + compare(result[1].length, 2); + compare(result[1][0].name, "alice"); + compare(result[1][0].hasPassword, true); + compare(result[1][1].hasPassword, false); + } + + function test_authenticate_wrongPassword() { + connect(); + var result = waitCallback(function (done) { session.authenticate("alice", "faux", done); }); + compare(result[0], "Nom d'utilisateur ou mot de passe incorrect."); + compare(session.accessToken, ""); + compare(session.currentUser, null); + } + + function test_authenticate_emptyName() { + connect(); + var result = waitCallback(function (done) { session.authenticate(" ", "x", done); }); + compare(result[0], "Veuillez saisir votre nom d'utilisateur."); + compare(requests("/Users/AuthenticateByName").length, 0); + } + + function test_authenticate_withoutPassword() { + var user = signIn("bob", ""); + compare(user.name, "bob"); + compare(lastRequest("/Users/AuthenticateByName").body.Pw, ""); + } + + // En-tête Authorization : identité du client, puis jeton une fois connecté. + function test_authorizationHeader() { + connect(); + var anonymous = lastRequest("/System/Info/Public").auth; + verify(anonymous.indexOf('MediaBrowser Client="Jellyfin Freebox"') === 0, anonymous); + verify(anonymous.indexOf('Version="' + session.clientVersion + '"') > 0, anonymous); + verify(/DeviceId="[0-9a-f]{32}"/.test(anonymous), anonymous); + verify(anonymous.indexOf("Token=") < 0, "pas de jeton avant connexion"); + + var result = waitCallback(function (done) { session.authenticate("alice", "secret", done); }); + compare(result[1].id, "user-alice"); + compare(session.accessToken, "token-user-alice"); + waitCallback(function (done) { session.loadLibraries(done); }); + verify(lastRequest("/UserViews").auth.indexOf('Token="token-user-alice"') > 0); + } + + function test_logout() { + signIn(); + session.logout(); + compare(session.accessToken, ""); + compare(session.currentUser, null); + tryVerify(function () { return requests("/Sessions/Logout").length === 1; }, 3000); + verify(lastRequest("/Sessions/Logout").auth.indexOf('Token="token-user-alice"') > 0, + "la déconnexion envoie encore le jeton"); + } + + // --------------------------------------------------------- catalogue + + function test_catalog_home() { + signIn(); + var libraries = waitCallback(function (done) { session.loadLibraries(done); }); + compare(libraries[0], null); + compare(libraries[1].length, 2); + compare(libraries[1][0].collectionType, "movies"); + + var resume = waitCallback(function (done) { session.loadResume(done); }); + compare(resume[1].length, 1); + compare(resume[1][0].id, "movie-direct"); + compare(resume[1][0].positionTicks, 6000000000); + compare(lastRequest("/UserItems/Resume").query.userId, "user-alice"); + + var latest = waitCallback(function (done) { session.loadLatest("lib-shows", done); }); + compare(latest[1].length, 1); + compare(latest[1][0].type, "Series"); + } + + function test_catalog_libraryPaging() { + signIn(); + var page = waitCallback(function (done) { + session.loadLibraryItems({ id: "lib-movies", collectionType: "movies" }, 20, 10, done); + }); + compare(page[0], null); + compare(page[1].length, 5); + compare(page[2], 25); + var query = lastRequest("/Items").query; + compare(query.includeItemTypes, "Movie"); + compare(query.startIndex, "20"); + compare(query.recursive, "true"); + + waitCallback(function (done) { + session.loadLibraryItems({ id: "lib-shows", collectionType: "tvshows" }, 0, 10, done); + }); + compare(lastRequest("/Items").query.includeItemTypes, "Series"); + waitCallback(function (done) { + session.loadLibraryItems({ id: "x", collectionType: "homevideos" }, 0, 10, done); + }); + compare(lastRequest("/Items").query.includeItemTypes, "Movie,Series,Video"); + } + + function test_catalog_series() { + signIn(); + var item = waitCallback(function (done) { session.loadItem("series-1", done); }); + compare(item[1].name, "Série test"); + var seasons = waitCallback(function (done) { session.loadSeasons("series-1", done); }); + compare(seasons[1].length, 2); + var episodes = waitCallback(function (done) { session.loadEpisodes("series-1", "season-1", done); }); + compare(episodes[1].length, 2); + compare(episodes[1][1].indexNumber, 2); + compare(lastRequest("/Shows/series-1/Episodes").query.fields, "Overview"); + } + + // ------------------------------------------------------------ erreurs + + function test_errors_messages() { + signIn(); + mock({ path: "/UserViews", status: 500 }); + var result = waitCallback(function (done) { session.loadLibraries(done); }); + compare(result[0], "Erreur du serveur (500)."); + compare(result[1], []); + + mock({ path: "/UserItems/Resume", raw: "pas du JSON" }); + result = waitCallback(function (done) { session.loadResume(done); }); + compare(result[0], "Réponse inattendue du serveur."); + + mock({ path: "/Items/nope", status: 404 }); + result = waitCallback(function (done) { session.loadItem("nope", done); }); + compare(result[0], "Erreur du serveur (404)."); + compare(result[1], null); + } + + function test_errors_expiredToken() { + signIn(); + session.accessToken = "jeton-expire"; + var result = waitCallback(function (done) { session.loadLibraries(done); }); + compare(result[0], "Erreur du serveur (401)."); + } + + // Qt 5.5 n'a pas de timeout XHR : Session utilise un Timer par requête. + function test_request_timeout() { + mock({ path: "/System/Info/Public", delay: 2000, body: {} }); + var result = waitCallback(function (done) { + session._request("GET", "/System/Info/Public", null, done, { baseUrl: serverUrl, timeout: 300 }); + }, 1500); + compare(result[0].kind, "timeout"); + } + + function test_request_network() { + var result = waitCallback(function (done) { + session._request("GET", "/x", null, done, { baseUrl: "http://127.0.0.1:1", timeout: 5000 }); + }, 6000); + compare(result[0].kind, "network"); + } + + // 204 sans corps : succès avec des données nulles (pas d'erreur de JSON). + function test_request_emptyBody() { + signIn(); + var result = waitCallback(function (done) { + session._request("POST", "/Sessions/Logout", null, done); + }); + compare(result[0], null); + compare(result[1], null); + } + + // Un écran détruit appelle cancel() : ses callbacks en attente ne doivent jamais arriver. + function test_cancel_dropsPendingCallbacks() { + signIn(); + mock({ path: "/UserViews", delay: 400, body: { Items: [] } }); + var called = false; + session.loadLibraries(function () { called = true; }); + session.cancel(); + wait(900); + verify(!called, "callback appelé après cancel()"); + // Les appels suivants fonctionnent normalement. + var result = waitCallback(function (done) { session.loadResume(done); }); + compare(result[0], null); + } + + // ------------------------------------------------------------- lecture + + function test_playback_directPlay() { + signIn(); + var result = waitCallback(function (done) { session.preparePlayback("movie-direct", done); }); + compare(result[0], null); + var info = result[1]; + compare(info.playMethod, "DirectPlay"); + compare(info.mediaSourceId, "src-movie-direct"); + compare(info.playSessionId, "play-movie-direct"); + verify(info.url.indexOf(session.currentServer.address + "/Videos/movie-direct/stream?") === 0, info.url); + verify(info.url.indexOf("static=true") > 0, info.url); + verify(info.url.indexOf("api_key=token-user-alice") > 0, info.url); + + var request = lastRequest("/Items/movie-direct/PlaybackInfo"); + compare(request.method, "POST"); + compare(request.query.userId, "user-alice"); + // -1 : sinon Jellyfin transcode pour incruster les sous-titres. + compare(request.body.SubtitleStreamIndex, -1); + compare(request.body.DeviceProfile.Name, "Freebox Player"); + verify(request.body.MaxStreamingBitrate > 0); + } + + function test_playback_transcode() { + signIn(); + var info = waitCallback(function (done) { session.preparePlayback("movie-transcode", done); })[1]; + compare(info.playMethod, "Transcode"); + compare(info.url, session.currentServer.address + + "/videos/movie-transcode/master.m3u8?MediaSourceId=src-movie-transcode&PlaySessionId=play-movie-transcode"); + } + + function test_playback_errors() { + signIn(); + var result = waitCallback(function (done) { session.preparePlayback("movie-broken", done); }); + compare(result[0], "Lecture impossible (NoCompatibleStream)."); + + mock({ path: "/Items/movie-01/PlaybackInfo", + body: { PlaySessionId: "p", MediaSources: [{ Id: "s", SupportsDirectPlay: false, + SupportsDirectStream: false, SupportsTranscoding: false }] } }); + result = waitCallback(function (done) { session.preparePlayback("movie-01", done); }); + compare(result[0], "Ce média ne peut pas être lu sur la Freebox."); + } + + function test_reportPlayback() { + signIn(); + var info = { itemId: "movie-01", mediaSourceId: "src", playSessionId: "ps", playMethod: "Transcode" }; + session.reportPlayback("start", info, 0, false); + session.reportPlayback("progress", info, 61000.7, true); + session.reportPlayback("stop", info, 62000, false); + tryVerify(function () { return requests("/Sessions/Playing/Stopped").length === 1; }, 3000); + var progress = lastRequest("/Sessions/Playing/Progress").body; + compare(progress.PositionTicks, 610007000); + compare(progress.IsPaused, true); + compare(progress.PlaySessionId, "ps"); + compare(progress.PlayMethod, "Transcode"); + compare(requests("/Sessions/Playing").length, 1); + compare(lastRequest("/Sessions/Playing/Stopped").body.PositionTicks, 620000000); + } + + // ------------------------------------------------------- Quick Connect + + function test_quickConnect() { + connect(); + compare(waitCallback(function (done) { session.isQuickConnectEnabled(done); })[1], true); + + session._quickConnectPoll.interval = 50; + var code = null; + var signedIn = null; + session.startQuickConnect(function (err, value) { code = err || value; }, + function (err, user) { signedIn = err || user; }); + tryVerify(function () { return code !== null; }, 3000); + compare(code, "123456"); + wait(200); + compare(signedIn, null, "pas de connexion avant autorisation"); + + http("POST", "/__quickconnect/authorize"); + tryVerify(function () { return signedIn !== null; }, 3000); + compare(signedIn.name, "alice"); + compare(session.accessToken, "token-user-alice"); + } + + function test_quickConnect_stop() { + connect(); + session._quickConnectPoll.interval = 50; + var signedIn = false; + var code = waitCallback(function (done) { + session.startQuickConnect(done, function () { signedIn = true; }); + }); + compare(code[1], "123456"); + session.stopQuickConnect(); + http("POST", "/__quickconnect/authorize"); + wait(400); + verify(!signedIn); + compare(requests("/Users/AuthenticateWithQuickConnect").length, 0); + } + + function test_quickConnect_disabled() { + connect(); + mock({ path: "/QuickConnect/Initiate", status: 401 }); + var result = waitCallback(function (done) { session.startQuickConnect(done, function () {}); }); + compare(result[0], "Quick Connect est désactivé sur ce serveur."); + mock({ path: "/QuickConnect/Enabled", body: false }); + compare(waitCallback(function (done) { session.isQuickConnectEnabled(done); })[1], false); + } + + // ----------------------------------------------------------- dev-config + + function test_devConfig() { + session.loadDevConfig(serverUrl + "/dev-config.json"); + tryVerify(function () { return session.servers.count === 1; }, 15000); + compare(session.servers.get(0).address, "http://" + serverHost + ":" + serverPort); + compare(session.devUsers.length, 1); + compare(session.devUsers[0].name, "carol"); + } + + function test_devConfig_ignoredFromDisk() { + session.loadDevConfig("file:///tmp/dev-config.json"); + wait(200); + compare(requests().length, 0); + compare(session.servers.count, 0); + } + + function test_devConfig_missing() { + mock({ path: "/dev-config.json", status: 404 }); + session.loadDevConfig(serverUrl + "/dev-config.json"); + tryVerify(function () { return requests("/dev-config.json").length === 1; }, 3000); + wait(200); + compare(session.servers.count, 0); + compare(session.devUsers.length, 0); + } +}