From a32ff2907456124e71db0801bb78fb849894b80f Mon Sep 17 00:00:00 2001 From: Aran <96021763+Aran404@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:14:02 -0500 Subject: [PATCH 1/4] Fix stale cache reads and preserve CLI display fields --- CHANGELOG.md | 2 +- docs/connect.md | 7 ++++--- spotapi/_parsing.py | 2 +- spotapi/cache.py | 37 ++++++++++++++++++++++++------------ spotapi/cli.py | 11 +++++++---- spotapi/login.py | 5 +++-- tests/test_cli.py | 31 +++++++++++++++++++++++++++++- tests/test_feature_parity.py | 30 +++++++++++++++++++++++++++++ 8 files changed, 101 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a94a031..fcfdfc6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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). diff --git a/docs/connect.md b/docs/connect.md index fb284f2..9db8bfd 100644 --- a/docs/connect.md +++ b/docs/connect.md @@ -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. diff --git a/spotapi/_parsing.py b/spotapi/_parsing.py index 5c1504a..556a65f 100644 --- a/spotapi/_parsing.py +++ b/spotapi/_parsing.py @@ -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 () diff --git a/spotapi/cache.py b/spotapi/cache.py index 7b06a03..ffb5ca5 100644 --- a/spotapi/cache.py +++ b/spotapi/cache.py @@ -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) @@ -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: diff --git a/spotapi/cli.py b/spotapi/cli.py index 6fa6ab9..6f8bbb7 100644 --- a/spotapi/cli.py +++ b/spotapi/cli.py @@ -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 @@ -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: diff --git a/spotapi/login.py b/spotapi/login.py index 84999ba..f3c60d8 100644 --- a/spotapi/login.py +++ b/spotapi/login.py @@ -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. """ diff --git a/tests/test_cli.py b/tests/test_cli.py index bb0f9e8..b425944 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -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 @@ -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 diff --git a/tests/test_feature_parity.py b/tests/test_feature_parity.py index c7d160c..fb22927 100644 --- a/tests/test_feature_parity.py +++ b/tests/test_feature_parity.py @@ -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 From b3a864b6267ea06c54c78bb636f5aaf831962c29 Mon Sep 17 00:00:00 2001 From: Aran <96021763+Aran404@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:14:16 -0500 Subject: [PATCH 2/4] Test clean distribution installs and optional dependencies in CI --- .github/workflows/publish.yml | 20 +++++++++++++++----- .github/workflows/spotify-public.yml | 12 ++++++++++-- docs/release-checks.md | 7 +++++-- 3 files changed, 30 insertions(+), 9 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index c575862..da9834a 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -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 diff --git a/.github/workflows/spotify-public.yml b/.github/workflows/spotify-public.yml index c924a53..636dc27 100644 --- a/.github/workflows/spotify-public.yml +++ b/.github/workflows/spotify-public.yml @@ -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: @@ -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 diff --git a/docs/release-checks.md b/docs/release-checks.md index 23485a0..61bd971 100644 --- a/docs/release-checks.md +++ b/docs/release-checks.md @@ -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** From 0a09945bc31bffed9adfeeb9f92ebf8f87971247 Mon Sep 17 00:00:00 2001 From: Aran <96021763+Aran404@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:15:12 -0500 Subject: [PATCH 3/4] Fix typo suggestions for the root command metavar --- spotapi/cli.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spotapi/cli.py b/spotapi/cli.py index 6f8bbb7..db20eb6 100644 --- a/spotapi/cli.py +++ b/spotapi/cli.py @@ -91,7 +91,7 @@ class _CommandParser(argparse.ArgumentParser): def error(self, message: str) -> NoReturn: if "invalid choice:" in message and ( - message.startswith("argument command:") or message.startswith("argument action:") + message.startswith(("argument command:", "argument :", "argument action:")) ): invalid = message.partition("invalid choice: ")[2].split(" (choose from", 1)[0] command = invalid.strip().strip("'\"") From 9c7474a519b93dc3a47d1dd2c660a1282993e286 Mon Sep 17 00:00:00 2001 From: Aran <96021763+Aran404@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:15:20 -0500 Subject: [PATCH 4/4] Simplify command error condition --- spotapi/cli.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spotapi/cli.py b/spotapi/cli.py index db20eb6..c9926a6 100644 --- a/spotapi/cli.py +++ b/spotapi/cli.py @@ -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:", "argument :", "argument action:")) + if "invalid choice:" in message and message.startswith( + ("argument command:", "argument :", "argument action:") ): invalid = message.partition("invalid choice: ")[2].split(" (choose from", 1)[0] command = invalid.strip().strip("'\"")