From 6e38d3f2ef2c6dce9802d53f3a38a264fa878f8e Mon Sep 17 00:00:00 2001 From: Afonso Coutinho Date: Wed, 3 Jun 2026 05:29:01 +0100 Subject: [PATCH] fix: youtube (services) comment formatter crashes on a non-dict comment (#1746) --- services/youtube/youtube_handler.py | 2 ++ tests/test_youtube_svc_comments_nondict.py | 15 +++++++++++++++ 2 files changed, 17 insertions(+) create mode 100644 tests/test_youtube_svc_comments_nondict.py diff --git a/services/youtube/youtube_handler.py b/services/youtube/youtube_handler.py index b8f1384..810aee6 100644 --- a/services/youtube/youtube_handler.py +++ b/services/youtube/youtube_handler.py @@ -256,6 +256,8 @@ def format_comments_for_context(comments_data: Dict[str, Any], url: str) -> str: ctx += f"URL: {url}\n\n" for i, c in enumerate(comments, 1): + if not isinstance(c, dict): + continue likes = c.get("likes", 0) likes_str = f" [{likes} likes]" if likes else "" ctx += f"{i}. @{c['author']}{likes_str}: {c['text']}\n\n" diff --git a/tests/test_youtube_svc_comments_nondict.py b/tests/test_youtube_svc_comments_nondict.py new file mode 100644 index 0000000..0f8b7ec --- /dev/null +++ b/tests/test_youtube_svc_comments_nondict.py @@ -0,0 +1,15 @@ +from services.youtube.youtube_handler import format_comments_for_context + + +def test_format_comments_skips_non_dict_entries(): + # comments come from json.loads of yt-dlp output; a malformed entry (None + # or a bare string) made the old loop call .get on a non-dict and crash. + data = {"success": True, "comments": [ + {"author": "alice", "text": "great", "likes": 4}, + "junk-row", + None, + {"author": "bob", "text": "nice", "likes": 1}, + ]} + out = format_comments_for_context(data, "https://youtu.be/x") + assert "@alice" in out and "@bob" in out + assert "junk-row" not in out