"""Unit tests for JellyfinClient user-id resolution. Jellyfin's ``/Users/{id}/...`` endpoints require the internal user Id (a hash), not the username. The service ``user_id`` config field accepts either form, so ``resolve_user_id`` must turn a username like ``'admin'`` into the real Id before any user-scoped call. See clients/jellyfin.py. """ from __future__ import annotations import unittest from unittest.mock import patch from media_library_viewer_api.clients.jellyfin import JellyfinClient class ResolveUserIdTests(unittest.TestCase): def _client(self) -> JellyfinClient: return JellyfinClient("https://jf.example.com", "api-key") def test_returns_identifier_when_it_matches_an_internal_id(self) -> None: users = [{"Id": "a1b2", "Name": "admin"}, {"Id": "c3d4", "Name": "friend"}] with patch.object(JellyfinClient, "users", return_value=users): self.assertEqual(self._client().resolve_user_id("c3d4"), "c3d4") def test_resolves_username_to_internal_id(self) -> None: """Regression: a configured username 'admin' must resolve to the internal Id. Hitting /Users/admin/Views directly returns HTTP 400 ('The value 'admin' is not valid.'), so the username form must be resolved. """ users = [{"Id": "a1b2c3internal", "Name": "admin"}, {"Id": "zzz", "Name": "other"}] with patch.object(JellyfinClient, "users", return_value=users): self.assertEqual(self._client().resolve_user_id("admin"), "a1b2c3internal") def test_falls_back_to_first_user_when_identifier_unknown(self) -> None: users = [{"Id": "first", "Name": "admin"}, {"Id": "second", "Name": "x"}] with patch.object(JellyfinClient, "users", return_value=users): self.assertEqual(self._client().resolve_user_id("nobody"), "first") def test_falls_back_to_first_user_when_identifier_none(self) -> None: users = [{"Id": "first", "Name": "admin"}] with patch.object(JellyfinClient, "users", return_value=users): self.assertEqual(self._client().resolve_user_id(None), "first") def test_raises_when_no_users_visible(self) -> None: with patch.object(JellyfinClient, "users", return_value=[]): with self.assertRaises(RuntimeError): self._client().resolve_user_id("admin") if __name__ == "__main__": unittest.main()