Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions spotapi/_studio/desktop.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,14 @@ 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."""
Expand Down Expand Up @@ -227,12 +234,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__":
Expand Down
2 changes: 1 addition & 1 deletion spotapi/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ def format_help(self) -> str:
"",
"Run 'spotapi <command> --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.",
"",
)
)
Expand Down
9 changes: 4 additions & 5 deletions spotapi/connection/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
5 changes: 5 additions & 0 deletions spotapi/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,11 @@ async def paginate(

if type(next_offset) is int:
if next_offset <= offset:
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"
)
return

offset = next_offset
Expand Down
33 changes: 33 additions & 0 deletions tests/test_auth_recovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
111 changes: 111 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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},
]
51 changes: 51 additions & 0 deletions tests/test_optional_features.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
38 changes: 38 additions & 0 deletions tests/test_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
9 changes: 9 additions & 0 deletions tests/test_public_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
40 changes: 40 additions & 0 deletions tests/test_queries_parsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}
16 changes: 16 additions & 0 deletions tests/test_studio.py
Original file line number Diff line number Diff line change
Expand Up @@ -384,3 +384,19 @@ 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()
Loading
Loading