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
20 changes: 15 additions & 5 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,24 @@ jobs:
- run: python -m black --check .
- run: python -m build
- run: python -m twine check dist/*
- run: python -m pip install --force-reinstall --no-deps dist/*.whl
- name: Install distributions in separate clean environments
run: |
python -m venv "$RUNNER_TEMP/spotapi-wheel"
"$RUNNER_TEMP/spotapi-wheel/bin/python" -m pip install dist/*.whl
"$RUNNER_TEMP/spotapi-wheel/bin/python" -m pip check
python -m venv "$RUNNER_TEMP/spotapi-sdist"
"$RUNNER_TEMP/spotapi-sdist/bin/python" -m pip install dist/*.tar.gz
"$RUNNER_TEMP/spotapi-sdist/bin/python" -m pip check
cd "$RUNNER_TEMP"
"$RUNNER_TEMP/spotapi-sdist/bin/python" -I -m spotapi --version
"$RUNNER_TEMP/spotapi-sdist/bin/python" -I -m spotapi search --help
- name: Smoke-test the installed wheel outside the checkout
working-directory: /tmp
run: |
spotapi --help
spotapi discover --help
spotapi studio --help
python -I - <<'PY'
"$RUNNER_TEMP/spotapi-wheel/bin/python" -I -m spotapi --help
"$RUNNER_TEMP/spotapi-wheel/bin/python" -I -m spotapi discover --help
"$RUNNER_TEMP/spotapi-wheel/bin/python" -I -m spotapi studio --help
"$RUNNER_TEMP/spotapi-wheel/bin/python" -I - <<'PY'
import os
from importlib.util import find_spec
from pathlib import Path
Expand Down
12 changes: 10 additions & 2 deletions .github/workflows/spotify-public.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,10 @@ jobs:
with:
python-version: ${{ matrix.python }}
- run: python -m pip install -e '.[dev,demo]'
- if: matrix.os == 'ubuntu-latest' && matrix.python == '3.12'
run: python -m pip install -e '.[mcp,media]'
- run: python -m coverage run -m pytest -m 'not live'
- run: python -m coverage report
- run: python -m coverage report --fail-under=70
- run: python -m coverage xml
- uses: actions/upload-artifact@v6
with:
Expand Down Expand Up @@ -57,9 +59,15 @@ jobs:
shell: pwsh
run: |
$wheel = (Get-ChildItem dist/*.whl).FullName
python -m pip install "$($wheel)[connect]"
python -m pip install "$wheel"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
Set-Location $env:RUNNER_TEMP
python -m pip check
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
python -I -m spotapi search --help
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
python -m pip install "$($wheel)[connect]"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
spotapi --version
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
python -I -m spotapi --version
Expand Down
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Changelog

## 2.1.3 - Pending release
## 2.1.3 - 2026-11-22

- Decode object-shaped album pre-release timestamps as typed dates without breaking
previous string or null values (#105).
Expand Down
7 changes: 4 additions & 3 deletions docs/connect.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,10 @@ saved under that profile name in your operating system's keyring. A failed or
cancelled login does not overwrite a stored profile. Profile names are selected
at launch; the terminal does not silently switch accounts while connected.

The keyring is deliberate: Connect never creates or modifies a plaintext
`.env` file. If you prefer `.env`, load `SPOTIFY_COOKIE` into the process
*explicitly* before launching Connect. Never commit credentials to Git.
Connect never creates or modifies a plaintext `.env` file. Saved profiles use
Python keyring's configured backend; use a secure OS-backed credential store,
not a third-party plaintext backend. If you prefer an environment variable,
load `SPOTIFY_COOKIE` into the process explicitly. Never commit credentials to Git.

The browser login uses a lazy Playwright import. On a system without Playwright
or Chromium, existing shell cookies and saved keyring profiles still work.
Expand Down
7 changes: 5 additions & 2 deletions docs/release-checks.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,16 @@ python -m spotapi connect --help

The [CI workflows](https://github.com/Aran404/SpotAPI/tree/main/.github/workflows)
exercise offline contracts across Python 3.11-3.13 and supported desktop OSes,
plus wheel installation checks and frontend browser tests.
plus wheel installation checks and frontend browser tests. Offline CI enforces a
70% branch-aware coverage floor; the Linux 3.12 job also installs the real MCP
and media extras.

**Publishing preflight:** The [release workflow](https://github.com/Aran404/SpotAPI/actions/workflows/publish.yml)
also runs its **exact tagged-release build and test steps** on every pull request and
every push to `main`. This matters because `build` and `twine` introduce dependencies
that the ordinary development test environment might not have. It builds and checks
the distributions, installs the wheel, and smoke-tests it outside the checkout.
the distributions, installs both in separate clean virtual environments, and
smoke-tests them outside the checkout.
The PyPI upload job is **skipped** unless the event is a matching `v*` tag push.

Before tagging, verify a **successful release preflight on the exact `main` commit**
Expand Down
2 changes: 1 addition & 1 deletion spotapi/_parsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def mapping(value: object) -> Mapping[str, Any]:


def records(value: object) -> tuple[Mapping[str, Any], ...]:
"""Return mapping-shaped entries from a sequence, or an empty tuple."""
"""Preserve sequence positions, replacing non-mapping entries with empty mappings."""
if not isinstance(value, (list, tuple)):
return ()

Expand Down
37 changes: 25 additions & 12 deletions spotapi/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,16 +86,8 @@ def key(self, operation: str, variables: Mapping[str, Any], namespace: str) -> s
)
return hashlib.sha256(source.encode()).hexdigest()

def get(self, key: str) -> ObjectDict | None:
self._validate_key(key)
with self._lock:
encoded = self._memory.get(key)
if encoded is not None:
self._memory.move_to_end(key)
def _decode(self, encoded: str | None) -> ObjectDict | None:
try:
if encoded is None and self.directory is not None:
with (self.directory / (key + ".json")).open(encoding="utf-8") as source:
encoded = source.read(self.max_bytes + 1025)
if encoded is None or len(encoded.encode()) > self.max_bytes + 1024:
return None
envelope: Any = json.loads(encoded)
Expand All @@ -106,19 +98,40 @@ def get(self, key: str) -> ObjectDict | None:
return None
document = cast(dict[str, Any], envelope)
expires: object = document.get("expires")
now = time.time()
if (
isinstance(expires, bool)
or not isinstance(expires, (int, float))
or not math.isfinite(expires)
or expires <= time.time()
or expires > time.time() + self.ttl + 1
or expires <= now
or expires > now + self.ttl + 1
):
return None
payload: Any = document.get("data")
return ObjectDict(cast(dict[str, Any], payload)) if isinstance(payload, dict) else None
except (OSError, ValueError, TypeError, RecursionError):
except (ValueError, TypeError, RecursionError, OverflowError):
return None

def get(self, key: str) -> ObjectDict | None:
self._validate_key(key)
with self._lock:
encoded = self._memory.get(key)
if encoded is not None:
self._memory.move_to_end(key)

result = self._decode(encoded)
if result is not None:
return result

# Another process may have replaced an expired in-memory entry on disk.
if self.directory is not None:
try:
with (self.directory / (key + ".json")).open(encoding="utf-8") as source:
return self._decode(source.read(self.max_bytes + 1025))
except (OSError, UnicodeError):
pass
return None

def put(self, key: str, data: ObjectDict) -> None:
self._validate_key(key)
try:
Expand Down
15 changes: 9 additions & 6 deletions spotapi/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@


def _subcommands(parser: argparse.ArgumentParser) -> dict[str, argparse.ArgumentParser]:
"""Find child parsers via the public Action.choices interface."""
"""Find subcommand parsers among argparse actions."""
children: dict[str, argparse.ArgumentParser] = {}
for action in parser._actions:
choices: object = action.choices
Expand All @@ -90,8 +90,8 @@ class _CommandParser(argparse.ArgumentParser):
"""Compact errors with guidance, without changing argparse's exit codes."""

def error(self, message: str) -> NoReturn:
if "invalid choice:" in message and (
message.startswith("argument command:") or message.startswith("argument action:")
if "invalid choice:" in message and message.startswith(
("argument command:", "argument <command>:", "argument action:")
):
invalid = message.partition("invalid choice: ")[2].split(" (choose from", 1)[0]
command = invalid.strip().strip("'\"")
Expand Down Expand Up @@ -174,10 +174,13 @@ def visit(item: object, depth: int = 0, label: str = "") -> None:
for number, entry in enumerate(entries, 1):
if isinstance(entry, dict):
fields = cast("dict[str, object]", entry)
title = fields.get("name") or fields.get("title") or fields.get("uri")
lines.append(" " * depth + f"{number}. {title or 'Item'}")
heading = next(
(key for key in ("name", "title", "uri") if fields.get(key)), None
)
title = fields[heading] if heading is not None else "Item"
lines.append(" " * depth + f"{number}. {title}")
for key, subvalue in fields.items():
if title is not None and key in {"name", "title"}:
if key == heading and heading != "uri":
continue
visit(subvalue, depth + 1, key.replace("_", " "))
else:
Expand Down
5 changes: 3 additions & 2 deletions spotapi/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@
class SavedSession:
"""Persist an sp_dc cookie in the operating system's credential store.

Requires ``spotapi[keyring]`` and a supported backend. No plaintext-file
fallback is used. This object never includes the cookie in repr or info().
Requires ``spotapi[keyring]`` and a secure backend. SpotAPI does not provide
a plaintext-file fallback; custom keyring backends are the caller's responsibility.
This object never includes the cookie in repr or info().
Saving does not validate the session; open() authorizes it with Spotify.
"""

Expand Down
31 changes: 30 additions & 1 deletion tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
SearchResults,
SpotAPIError,
)
from spotapi.cli import _parser, main
from spotapi.cli import _human, _parser, main
from spotapi.login import SavedSession
from spotapi.types import BaseClientError

Expand Down Expand Up @@ -318,3 +318,32 @@ def import_module(name: str, package: str | None = None) -> object:
assert "Set SPOTIFY_COOKIE" in captured.err
assert "keyring backend" in captured.err
assert "No recommended backend" not in captured.err


def test_human_output_preserves_distinct_name_and_title() -> None:
output = _human([{"name": "Artist", "title": "Track", "uri": "spotify:track:one"}])
assert output == "1. Artist\n title: Track\n uri: spotify:track:one"


def test_human_output_preserves_empty_name_when_title_is_used() -> None:
output = _human([{"name": "", "title": "Track"}])
assert output == "1. Track\n name: "


def test_root_help_lists_every_command(capsys: pytest.CaptureFixture[str]) -> None:
from spotapi.cli import _subcommands

parser = _parser()
with pytest.raises(SystemExit) as exit_info:
main(["--help"])
assert exit_info.value.code == 0
output = capsys.readouterr().out
for command in _subcommands(parser):
assert f" {command} " in output


def test_cli_suggests_close_command(capsys: pytest.CaptureFixture[str]) -> None:
with pytest.raises(SystemExit) as exit_info:
main(["serach"])
assert exit_info.value.code == 2
assert "Did you mean 'search'?" in capsys.readouterr().err
30 changes: 30 additions & 0 deletions tests/test_feature_parity.py
Original file line number Diff line number Diff line change
Expand Up @@ -386,3 +386,33 @@ def test_generic_decoder_does_not_treat_error_metadata_as_an_exception() -> None

with pytest.raises(TypeError):
from_dict(BatchItem, {"index": 0, "value": "bad", "error": {"type": "ValueError"}})


def test_cache_reads_newer_disk_entry_after_memory_expires(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
clock = Mock(return_value=100.0)
monkeypatch.setattr("spotapi.cache.time.time", clock)
first = ResponseCache(tmp_path, ttl=10)
second = ResponseCache(tmp_path, ttl=10)
key = first.key("track", {"id": "one"}, "test")
first.put(key, ObjectDict({"name": "old"}))

clock.return_value = 108.0
second.put(key, ObjectDict({"name": "new"}))
assert first.get(key) == ObjectDict({"name": "old"})

clock.return_value = 111.0
assert first.get(key) == ObjectDict({"name": "new"})
clock.return_value = 119.0
assert first.get(key) is None


def test_cache_rejects_overflowing_expiry(tmp_path: Path) -> None:
cache = ResponseCache(tmp_path)
key = cache.key("track", {}, "test")
(tmp_path / f"{key}.json").write_text(
json.dumps({"version": 1, "expires": 10**400, "data": {"name": "bad"}}),
encoding="utf-8",
)
assert cache.get(key) is None
Loading