From db51ae8b69ea82a1941b5f1d54c6f8022c1c6582 Mon Sep 17 00:00:00 2001 From: Aran <96021763+Aran404@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:29:36 -0500 Subject: [PATCH 1/4] Harden pagination and shutdown, cover command and retry contracts --- spotapi/_studio/desktop.py | 16 ++++- spotapi/cli.py | 2 +- spotapi/connection/http.py | 9 ++- spotapi/query.py | 5 ++ tests/test_cli.py | 111 ++++++++++++++++++++++++++++++++++ tests/test_queries_parsing.py | 40 ++++++++++++ tests/test_studio.py | 18 ++++++ tests/test_transport.py | 44 ++++++++++++++ 8 files changed, 236 insertions(+), 9 deletions(-) diff --git a/spotapi/_studio/desktop.py b/spotapi/_studio/desktop.py index d9fd88e..f859c65 100644 --- a/spotapi/_studio/desktop.py +++ b/spotapi/_studio/desktop.py @@ -180,7 +180,13 @@ def main() -> None: webview = cast(WebView, import_module("webview")) loop = asyncio.new_event_loop() studio = Studio() - worker = threading.Thread(target=loop.run_forever, name="spotapi-studio", daemon=True) + def run_loop() -> None: + try: + loop.run_forever() + finally: + loop.close() + + worker = threading.Thread(target=run_loop, name="spotapi-studio", daemon=True) def notify(status: str) -> None: """Notify the page using fixed scripts with no embedded account values.""" @@ -227,12 +233,16 @@ async def shutdown() -> None: await loop.shutdown_asyncgens() await loop.shutdown_default_executor() + cleanup = asyncio.run_coroutine_threadsafe(shutdown(), loop) try: - asyncio.run_coroutine_threadsafe(shutdown(), loop).result(timeout=15) + cleanup.result(timeout=15) finally: + if not cleanup.done(): + cleanup.cancel() loop.call_soon_threadsafe(loop.stop) worker.join(timeout=5) - loop.close() + if worker.is_alive(): + raise RuntimeError("Studio worker did not stop after shutdown") if __name__ == "__main__": diff --git a/spotapi/cli.py b/spotapi/cli.py index 66f8bbd..4eac985 100644 --- a/spotapi/cli.py +++ b/spotapi/cli.py @@ -128,7 +128,7 @@ def format_help(self) -> str: "", "Run 'spotapi --help' for command-specific options.", "Use --json after a command for machine-readable output.", - "Default output remains JSON when redirected or piped.", + "Most reads output JSON when redirected; search requires --json.", "", ) ) diff --git a/spotapi/connection/http.py b/spotapi/connection/http.py index 3bd8a8d..95f16a0 100644 --- a/spotapi/connection/http.py +++ b/spotapi/connection/http.py @@ -634,11 +634,10 @@ def _parse_json_object(text: str) -> ObjectDict | None: """Parse ``text`` as a JSON object, returning ``None`` for anything else.""" try: data = json.loads(text) - except ValueError: - return None - - if isinstance(data, dict): - return ObjectDict.from_json(cast("dict[str, Any]", data)) + if isinstance(data, dict): + return ObjectDict.from_json(cast("dict[str, Any]", data)) + except (ValueError, RecursionError): + pass return None diff --git a/spotapi/query.py b/spotapi/query.py index 5597119..b17306a 100644 --- a/spotapi/query.py +++ b/spotapi/query.py @@ -159,6 +159,11 @@ async def paginate( if type(next_offset) is int: if next_offset <= offset: + if has_total_count and offset + len(items) < total_count: + raise BaseClientError( + "Spotify pagination stopped advancing before totalCount; " + "results may be incomplete" + ) return offset = next_offset diff --git a/tests/test_cli.py b/tests/test_cli.py index 8fc8f5e..7b51124 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -357,3 +357,114 @@ def test_public_playlist_rejects_ignored_profile( assert main(["playlist", "items", "abc", "--profile", "work"]) == 1 assert "Use --private with --profile" in capsys.readouterr().err lookup.assert_not_called() + + +@pytest.mark.parametrize( + ("command", "method", "arguments"), + [ + (["pause"], "pause", ()), + (["resume"], "resume", ()), + (["next"], "next", ()), + (["previous"], "previous", ()), + (["play", "spotify:track:abc"], "play", ("spotify:track:abc",)), + (["seek", "2000"], "seek", (2000,)), + (["volume", "25"], "volume", (25,)), + (["queue", "spotify:track:abc"], "add_to_queue", ("spotify:track:abc",)), + ], +) +def test_player_commands_dispatch_once( + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + command: list[str], + method: str, + arguments: tuple[object, ...], +) -> None: + player = Mock() + action = AsyncMock() + setattr(player, method, action) + closed: list[bool] = [] + + @asynccontextmanager + async def connection() -> AsyncGenerator[Mock, None]: + try: + yield player + finally: + closed.append(True) + + @asynccontextmanager + async def account(cookie: str) -> AsyncGenerator[object, None]: + yield SimpleNamespace(session=Mock(spec=AuthSession)) + + monkeypatch.setenv("SPOTIFY_COOKIE", "test-cookie") + monkeypatch.setattr(Private, "from_cookies", account) + monkeypatch.setattr("spotapi.cli.Player", Mock(return_value=Mock(connect=connection))) + assert main(["player", *command]) == 0 + action.assert_awaited_once_with(*arguments) + assert closed == [True] + assert not capsys.readouterr().out + + +def test_player_command_failure_closes_connection( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + player = Mock(next=AsyncMock(side_effect=SpotAPIError("device disconnected"))) + closed: list[bool] = [] + + @asynccontextmanager + async def connection() -> AsyncGenerator[Mock, None]: + try: + yield player + finally: + closed.append(True) + + @asynccontextmanager + async def account(cookie: str) -> AsyncGenerator[object, None]: + yield SimpleNamespace(session=Mock(spec=AuthSession)) + + monkeypatch.setenv("SPOTIFY_COOKIE", "test-cookie") + monkeypatch.setattr(Private, "from_cookies", account) + monkeypatch.setattr("spotapi.cli.Player", Mock(return_value=Mock(connect=connection))) + assert main(["player", "next"]) == 1 + player.next.assert_awaited_once() + assert closed == [True] + captured = capsys.readouterr() + assert not captured.out + assert "device disconnected" in captured.err + + +def test_public_playlist_read_closes_generator( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + closed: list[bool] = [] + + async def items(value: str, *, limit: int) -> AsyncGenerator[tuple[dict[str, str], ...], None]: + assert value == "playlist" and limit == 2 + try: + yield ({"uid": "first"}, {"uid": "second"}) + raise AssertionError("The CLI should read only one page") + finally: + closed.append(True) + + monkeypatch.setattr(Public, "get_playlist_items", items) + assert main(["playlist", "items", "playlist", "--limit", "2"]) == 0 + assert json.loads(capsys.readouterr().out) == [{"uid": "first"}, {"uid": "second"}] + assert closed == [True] + + +def test_library_contains_preserves_input_order( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + liked = Mock(contains=AsyncMock(return_value=[True, False])) + + @asynccontextmanager + async def account(cookie: str) -> AsyncGenerator[object, None]: + yield SimpleNamespace(liked_tracks=liked) + + monkeypatch.setenv("SPOTIFY_COOKIE", "test-cookie") + monkeypatch.setattr(Private, "from_cookies", account) + assert main(["library", "contains", "first", "second"]) == 0 + liked.contains.assert_awaited_once_with(["first", "second"]) + assert json.loads(capsys.readouterr().out) == [ + {"track": "first", "liked": True}, + {"track": "second", "liked": False}, + ] diff --git a/tests/test_queries_parsing.py b/tests/test_queries_parsing.py index c7d15ed..77225ed 100644 --- a/tests/test_queries_parsing.py +++ b/tests/test_queries_parsing.py @@ -194,3 +194,43 @@ async def request(variables: dict[str, Any]) -> ObjectDict: pages = [page async for page in paginate(request, {"limit": 1})] assert len(pages) == 3 + + +@pytest.mark.parametrize("next_offset", [0, -1]) +async def test_pagination_reports_a_stalled_offset_before_total(next_offset: int) -> None: + async def request(variables: dict[str, Any]) -> ObjectDict: + return ObjectDict( + {"items": ["first"], "totalCount": 3, "pagingInfo": {"nextOffset": next_offset}} + ) + + pages: list[ObjectDict] = [] + with pytest.raises(BaseClientError, match="results may be incomplete"): + async for page in paginate(request, {"limit": 1}): + pages.append(page) + assert len(pages) == 1 + + +async def test_pagination_accepts_terminal_offset_after_all_items() -> None: + async def request(variables: dict[str, Any]) -> ObjectDict: + return ObjectDict({"items": ["last"], "totalCount": 1, "pagingInfo": {"nextOffset": 0}}) + + assert len([page async for page in paginate(request, {"limit": 1})]) == 1 + + +async def test_pagination_respects_server_offset_and_keeps_original_variables() -> None: + requested: list[dict[str, Any]] = [] + variables = {"limit": 2, "offset": 1} + + async def request(values: dict[str, Any]) -> ObjectDict: + requested.append(values) + return ObjectDict( + { + "items": ["item"], + "totalCount": 5, + "pagingInfo": {"nextOffset": 4 if values["offset"] == 1 else None}, + } + ) + + assert len([page async for page in paginate(request, variables)]) == 2 + assert requested == [{"limit": 2, "offset": 1}, {"limit": 2, "offset": 4}] + assert variables == {"limit": 2, "offset": 1} diff --git a/tests/test_studio.py b/tests/test_studio.py index 085d814..bc410bf 100644 --- a/tests/test_studio.py +++ b/tests/test_studio.py @@ -384,3 +384,21 @@ async def search(self, query: str, *, types: tuple[str, ...], limit: int) -> obj def test_lyrics_identifies_installed_release(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr("spotapi._studio.lyrics.package_version", Mock(return_value="2.7.3")) assert _studio_user_agent() == ("SpotAPI Studio v2.7.3 (https://github.com/Aran404/SpotAPI)") + + +def test_native_app_closes_loop_even_when_shutdown_fails( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from spotapi._studio import desktop + + loop = asyncio.new_event_loop() + backend = Mock() + monkeypatch.setattr("dotenv.load_dotenv", Mock()) + monkeypatch.delenv("SPOTIFY_COOKIE", raising=False) + monkeypatch.setattr(desktop, "import_module", Mock(return_value=backend)) + monkeypatch.setattr(desktop.asyncio, "new_event_loop", Mock(return_value=loop)) + monkeypatch.setattr(Studio, "close", AsyncMock(side_effect=RuntimeError("cleanup failed"))) + + with pytest.raises(RuntimeError, match="cleanup failed"): + desktop.main() + assert loop.is_closed() diff --git a/tests/test_transport.py b/tests/test_transport.py index 1fadb93..4adbccc 100644 --- a/tests/test_transport.py +++ b/tests/test_transport.py @@ -293,3 +293,47 @@ async def test_spotify_json_media_type_is_not_binary(monkeypatch: pytest.MonkeyP result = await http.get("https://example.test/") assert result.json is not None and result.json["items"] == [] assert result.body == b"" + + +async def test_excessively_nested_json_is_rejected_without_leaking_response( + monkeypatch: pytest.MonkeyPatch, +) -> None: + body = '{"nested":' + "[" * 2000 + "0" + "]" * 2000 + "}" + raw = RawResponse(body=body) + http, transport = client(monkeypatch, [raw]) + response = await http.get("https://example.test/") + assert response.json is None + assert raw.closed and transport.calls == 1 + + +@pytest.mark.parametrize("status", [429, 500, 502, 503, 504]) +async def test_failed_mutation_response_is_never_replayed( + monkeypatch: pytest.MonkeyPatch, status: int +) -> None: + raw = RawResponse(status, headers=[(b"retry-after", b"0")]) + http, transport = client(monkeypatch, [raw]) + response = await http.post("https://example.test/") + assert response.status_code.as_int() == status + assert raw.closed and transport.calls == 1 + + +@pytest.mark.parametrize("attempts", [0, -1, True]) +async def test_invalid_attempt_limit_precedes_transport( + monkeypatch: pytest.MonkeyPatch, attempts: int +) -> None: + http, transport = client(monkeypatch, []) + with pytest.raises(ValueError, match="max_attempts"): + await http.get("https://example.test/", max_attempts=attempts) + assert transport.calls == 0 + + +@pytest.mark.parametrize("delay", [-1.0, float("nan"), float("inf")]) +async def test_invalid_backoff_callback_does_not_retry( + monkeypatch: pytest.MonkeyPatch, delay: float +) -> None: + raw = RawResponse(503) + http, transport = client(monkeypatch, [raw]) + http._backoff = lambda attempt: delay + with pytest.raises(ValueError, match="backoff"): + await http.get("https://example.test/") + assert raw.closed and transport.calls == 1 From 2b62b5384638d5c1b02d49b865c96fceabc11528 Mon Sep 17 00:00:00 2001 From: Aran <96021763+Aran404@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:30:40 -0500 Subject: [PATCH 2/4] Exercise token cancellation, playback validation and MCP reads --- tests/test_auth_recovery.py | 33 +++++++++++++++++++++ tests/test_optional_features.py | 51 +++++++++++++++++++++++++++++++++ tests/test_player.py | 38 ++++++++++++++++++++++++ tests/test_public_api.py | 9 ++++++ 4 files changed, 131 insertions(+) diff --git a/tests/test_auth_recovery.py b/tests/test_auth_recovery.py index d311bf6..9e4a7ca 100644 --- a/tests/test_auth_recovery.py +++ b/tests/test_auth_recovery.py @@ -313,3 +313,36 @@ async def test_login_rejection_is_preserved_when_failed_login_cleanup_also_fails assert caught.value.status_code == 401 assert isinstance(caught.value.__cause__, ConnectionError) assert client.close.await_count >= 1 + + +async def test_cancelled_token_renewal_releases_lock_and_preserves_credentials( + monkeypatch: pytest.MonkeyPatch, +) -> None: + session = AuthSession(Mock(spec=AsyncClient)) + original = AccessToken("client", "old", 0) + renewed = AccessToken("client", "new", int((time.time() + 3600) * 1000)) + session._token = original + started = asyncio.Event() + + async def stall() -> AccessToken: + started.set() + await asyncio.Future[None]() + raise AssertionError("Renewal should have been cancelled") + + issue = AsyncMock(side_effect=stall) + monkeypatch.setattr(AuthSession, "_issue_token", issue) + task = asyncio.create_task(session.refresh(previous_token="old")) + await started.wait() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert session.token is original + assert not session._auth_lock.locked() + + issue.side_effect = None + issue.return_value = renewed + try: + async with asyncio.timeout(1): + assert await session.refresh(previous_token="old") is renewed + finally: + await session.stop_refresh() diff --git a/tests/test_optional_features.py b/tests/test_optional_features.py index ebdbf14..5b1bbbd 100644 --- a/tests/test_optional_features.py +++ b/tests/test_optional_features.py @@ -432,3 +432,54 @@ async def test_mcp_can_like_a_supplied_track_without_a_player( with pytest.raises(Exception, match="open.spotify.com"): await server.call_tool("like", {"track": "https://example.com/track/test"}) login.assert_not_awaited() + + +async def test_mcp_public_reads_and_batch_limits(monkeypatch: pytest.MonkeyPatch) -> None: + pytest.importorskip("mcp") + from spotapi.mcp import build_server + from spotapi.public import Public + + lookup = AsyncMock(return_value={"name": "Example"}) + search = AsyncMock(return_value={"tracks": []}) + fetch = AsyncMock(return_value=()) + monkeypatch.setattr(Public, "get", lookup) + monkeypatch.setattr(Public, "search", search) + monkeypatch.setattr(Public, "fetch_many", fetch) + server = build_server() + + await server.call_tool("get_resource", {"value": "spotify:track:abc"}) + lookup.assert_awaited_once_with("spotify:track:abc") + await server.call_tool("search", {"query": "Example", "limit": 3}) + search.assert_awaited_once_with("Example", types=("track", "artist"), limit=3) + await server.call_tool("batch", {"values": ["spotify:track:abc"], "concurrency": 2}) + fetch.assert_awaited_once_with(["spotify:track:abc"], concurrency=2) + fetch.reset_mock() + with pytest.raises(Exception, match="at most 50"): + await server.call_tool("batch", {"values": ["spotify:track:abc"] * 51}) + fetch.assert_not_awaited() + + +async def test_mcp_playlist_read_closes_stream_and_catalogue( + monkeypatch: pytest.MonkeyPatch, +) -> None: + pytest.importorskip("mcp") + from spotapi.mcp import build_server + + closed: list[bool] = [] + + async def pages(value: str, *, limit: int) -> AsyncGenerator[tuple[dict[str, str], ...], None]: + assert value == "playlist" and limit == 2 + try: + yield ({"uid": "one"}, {"uid": "two"}) + raise AssertionError("Only the first page should be read") + finally: + closed.append(True) + + catalogue = MagicMock() + catalogue.__aenter__ = AsyncMock(return_value=catalogue) + catalogue.__aexit__ = AsyncMock(return_value=False) + catalogue.get_playlist_items = pages + monkeypatch.setattr("spotapi.mcp.Catalogue", Mock(return_value=catalogue)) + await build_server().call_tool("playlist_items", {"value": "playlist", "limit": 2}) + assert closed == [True] + catalogue.__aexit__.assert_awaited_once() diff --git a/tests/test_player.py b/tests/test_player.py index a2d7685..bc3df62 100644 --- a/tests/test_player.py +++ b/tests/test_player.py @@ -1302,3 +1302,41 @@ async def add(self: LikedTracks, tracks: list[str]) -> None: assert observed == [False, True, False] await player.close() + + +async def test_unchanged_playback_options_do_not_send_commands( + session: Mock, monkeypatch: pytest.MonkeyPatch +) -> None: + player = Player(session) + state = PlayerState.from_cluster(packet(2)["payloads"][0]["cluster"]) + command = AsyncMock() + monkeypatch.setattr(Player, "command", command) + monkeypatch.setattr(Player, "_selected_state", Mock(return_value=state)) + + await player.shuffle(state.shuffle) + await player.repeat(state.repeat_mode) + command.assert_not_awaited() + + +@pytest.mark.parametrize( + ("value", "position", "offset", "track"), + [ + ("spotify:track:abc", -1, None, None), + ("spotify:track:abc", 0, -1, None), + ("spotify:track:abc", 0, 1, "spotify:track:def"), + ("spotify:user:listener", 0, None, None), + ], +) +async def test_invalid_play_request_never_sends_command( + session: Mock, + monkeypatch: pytest.MonkeyPatch, + value: str, + position: int, + offset: int | None, + track: str | None, +) -> None: + command = AsyncMock() + monkeypatch.setattr(Player, "command", command) + with pytest.raises(ValueError): + await Player(session).play(value, position_ms=position, offset=offset, track=track) + command.assert_not_awaited() diff --git a/tests/test_public_api.py b/tests/test_public_api.py index 15cd99e..1f94210 100644 --- a/tests/test_public_api.py +++ b/tests/test_public_api.py @@ -640,3 +640,12 @@ async def scenario() -> None: def test_parse_rejects_credentials_and_control_characters(value: str) -> None: with pytest.raises(ValueError): Public.parse_url(value) + + +def test_all_public_exports_resolve() -> None: + import spotapi + + assert set(spotapi.__all__) == set(spotapi._EXPORTS) + for name in spotapi.__all__: + assert name in dir(spotapi) + assert getattr(spotapi, name) is not None From cf1b411b4fe636ea78f1352de9b6ff2fdb85f233 Mon Sep 17 00:00:00 2001 From: Aran <96021763+Aran404@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:30:59 -0500 Subject: [PATCH 3/4] Resolve strict type checks in pagination and retry tests --- spotapi/query.py | 2 +- tests/test_studio.py | 4 +--- tests/test_transport.py | 5 ++++- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/spotapi/query.py b/spotapi/query.py index b17306a..c665ed3 100644 --- a/spotapi/query.py +++ b/spotapi/query.py @@ -159,7 +159,7 @@ async def paginate( if type(next_offset) is int: if next_offset <= offset: - if has_total_count and offset + len(items) < total_count: + if has_total_count and offset + len(cast(list[object], items)) < total_count: raise BaseClientError( "Spotify pagination stopped advancing before totalCount; " "results may be incomplete" diff --git a/tests/test_studio.py b/tests/test_studio.py index bc410bf..a205987 100644 --- a/tests/test_studio.py +++ b/tests/test_studio.py @@ -386,9 +386,7 @@ def test_lyrics_identifies_installed_release(monkeypatch: pytest.MonkeyPatch) -> assert _studio_user_agent() == ("SpotAPI Studio v2.7.3 (https://github.com/Aran404/SpotAPI)") -def test_native_app_closes_loop_even_when_shutdown_fails( - monkeypatch: pytest.MonkeyPatch, -) -> None: +def test_native_app_closes_loop_even_when_shutdown_fails(monkeypatch: pytest.MonkeyPatch) -> None: from spotapi._studio import desktop loop = asyncio.new_event_loop() diff --git a/tests/test_transport.py b/tests/test_transport.py index 4adbccc..2277dab 100644 --- a/tests/test_transport.py +++ b/tests/test_transport.py @@ -333,7 +333,10 @@ async def test_invalid_backoff_callback_does_not_retry( ) -> None: raw = RawResponse(503) http, transport = client(monkeypatch, [raw]) - http._backoff = lambda attempt: delay + def backoff(attempt: int) -> float: + return delay + + http._backoff = backoff with pytest.raises(ValueError, match="backoff"): await http.get("https://example.test/") assert raw.closed and transport.calls == 1 From 7bf9681a43a52e72495672be40420088d99dfb2e Mon Sep 17 00:00:00 2001 From: Aran <96021763+Aran404@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:08:58 -0500 Subject: [PATCH 4/4] Format shutdown and retry helpers --- spotapi/_studio/desktop.py | 1 + tests/test_transport.py | 1 + 2 files changed, 2 insertions(+) diff --git a/spotapi/_studio/desktop.py b/spotapi/_studio/desktop.py index f859c65..61a159d 100644 --- a/spotapi/_studio/desktop.py +++ b/spotapi/_studio/desktop.py @@ -180,6 +180,7 @@ def main() -> None: webview = cast(WebView, import_module("webview")) loop = asyncio.new_event_loop() studio = Studio() + def run_loop() -> None: try: loop.run_forever() diff --git a/tests/test_transport.py b/tests/test_transport.py index 2277dab..ec1ca4b 100644 --- a/tests/test_transport.py +++ b/tests/test_transport.py @@ -333,6 +333,7 @@ async def test_invalid_backoff_callback_does_not_retry( ) -> None: raw = RawResponse(503) http, transport = client(monkeypatch, [raw]) + def backoff(attempt: int) -> float: return delay