fix: improve show handling, cache validation and tests

Add extensive tests for the `show` command (happy path, empty/expired/malformed cache, out-of-range, zero/negative indices) and a test helper to write cache fixtures. Harden twitter_cli.cache._load_cache to validate payload types (dict/tweets list), filter non-dict entries, and treat malformed payloads as empty; also handle missing tweet id when resolving an index. Refactor CLI output logic by extracting _emit_tweet_detail and reuse it for both `tweet` and `show`; enforce 1-based indices for `show` via click.IntRange(1) and expand the "no cached results" error text to mention other list commands. These changes improve robustness against corrupted caches and increase test coverage for cache-based behavior.
This commit is contained in:
Pleasurecruise
2026-03-12 22:26:52 +00:00
parent 5335516d57
commit 72f62cedea
3 changed files with 123 additions and 17 deletions

View File

@@ -38,9 +38,14 @@ def _load_cache() -> Optional[List[dict]]:
if not _CACHE_FILE.exists():
return None
payload = json.loads(_CACHE_FILE.read_text(encoding="utf-8"))
if not isinstance(payload, dict):
return None
if time.time() - payload.get("created_at", 0) > _TTL:
return None
return payload.get("tweets", [])
entries = payload.get("tweets", [])
if not isinstance(entries, list):
return None
return [e for e in entries if isinstance(e, dict)]
except (OSError, json.JSONDecodeError):
return None
@@ -52,7 +57,8 @@ def get_tweet_id_by_index(index: int) -> Optional[str]:
return None
for entry in entries:
if entry.get("index") == index:
return str(entry["id"])
tweet_id = entry.get("id")
return str(tweet_id) if tweet_id is not None else None
return None