返回 last30days-skill
test_reddit_shreddit.py
根目录 / tests / test_reddit_shreddit.py
1 """Tests for scripts/lib/reddit_shreddit.py — keyless shreddit comment scrape."""
2
3 from pathlib import Path
4 import time
5 from unittest import mock
6
7 from lib import reddit_shreddit as rs
8
9 FIXTURE = Path(__file__).resolve().parent.parent / "fixtures" / "reddit_shreddit_comments_sample.html"
10
11
12 def _html():
13 return FIXTURE.read_text(encoding="utf-8")
14
15
16 # The partial after a DOM round-trip: HTML attribute names are case-insensitive,
17 # so a serializer writes ``thingId`` as ``thingid``. Values keep their case.
18 LOWERCASED_ATTR_HTML = """
19 <shreddit-comment-tree-stats total-comments="2" sort="TOP"></shreddit-comment-tree-stats>
20 <shreddit-comment created="2026-08-09T12:45:51+0000" author="AliceCooper" thingid="t1_aaa"
21 permalink="/r/videos/comments/x1/comment/aaa/" score="1136" depth="0">
22 <div id="t1_aaa-post-rtjson-content"><div><p>First body about $750 pending.</p></div></div>
23 </shreddit-comment>
24 <shreddit-comment created="2026-08-09T12:46:00+0000" author="bob" thingid="t1_bbb"
25 permalink="/r/videos/comments/x1/comment/bbb/" score="42" depth="0">
26 <div id="t1_bbb-post-rtjson-content"><div><p>Second body.</p></div></div>
27 </shreddit-comment>
28 """
29
30
31 class TestExtractPostRef:
32 def test_extracts_sub_and_id(self):
33 ref = rs.extract_post_ref("https://www.reddit.com/r/Rakuten/comments/1taeiw0/title/")
34 assert ref == ("Rakuten", "1taeiw0")
35
36 def test_non_thread_url_returns_none(self):
37 assert rs.extract_post_ref("https://www.reddit.com/r/Rakuten/") is None
38 assert rs.extract_post_ref("") is None
39
40 def test_svc_url_shape(self):
41 # sort=top guarantees the highest-scored comments land on page 1.
42 assert rs._svc_url("Rakuten", "1taeiw0") == (
43 "https://www.reddit.com/svc/shreddit/comments/r/Rakuten/t3_1taeiw0?sort=top"
44 )
45
46
47 class TestParseComments:
48 """parse_comments reads <shreddit-comment> elements into scored dicts."""
49
50 def test_happy_path(self):
51 comments = rs.parse_comments(_html())
52 assert len(comments) >= 1
53 for c in comments:
54 assert isinstance(c["score"], int)
55 assert c["author"] and c["author"] not in ("[deleted]", "[removed]")
56 assert c["body"]
57
58 def test_sorted_by_score_desc(self):
59 scores = [c["score"] for c in rs.parse_comments(_html())]
60 assert scores == sorted(scores, reverse=True)
61
62 def test_deleted_and_removed_filtered(self):
63 authors = [c["author"] for c in rs.parse_comments(_html())]
64 assert "[deleted]" not in authors and "[removed]" not in authors
65
66 def test_negative_score_retained(self):
67 scores = [c["score"] for c in rs.parse_comments(_html())]
68 assert -7 in scores # synthetic downvoted-but-real comment
69
70 def test_limit_honored(self):
71 assert len(rs.parse_comments(_html(), limit=2)) == 2
72
73 def test_body_text_extracted(self):
74 bodies = [c["body"] for c in rs.parse_comments(_html())]
75 assert any("$750" in b or "pending" in b for b in bodies)
76
77 def test_comment_url_built(self):
78 comments = rs.parse_comments(_html())
79 assert [c["url"] for c in comments] == [
80 f"https://reddit.com/r/Rakuten/comments/1taeiw0/comment/{comment_id}/"
81 for comment_id in (
82 "ol8tp8n", "olcy1iv", "olaqzjk", "omlbiqg", "ol8undb", "ol8w8w6", "synthneg"
83 )
84 ]
85
86 def test_empty_html_returns_empty(self):
87 assert rs.parse_comments("") == []
88 assert rs.parse_comments("<html>no comments here</html>") == []
89
90 def test_nested_replies_keep_their_depth(self):
91 depths = {c["url"].rstrip("/").rsplit("/", 1)[-1]: c["depth"]
92 for c in rs.parse_comments(_html())}
93 assert depths["ol8tp8n"] == 0
94 assert depths["olcy1iv"] == 1
95 assert depths["omlbiqg"] == 2
96
97 def test_lowercased_attribute_names_parsed(self):
98 comments = rs.parse_comments(LOWERCASED_ATTR_HTML)
99 assert [c["score"] for c in comments] == [1136, 42]
100 assert comments[0]["author"] == "AliceCooper" # values keep their case
101 assert "$750" in comments[0]["body"]
102
103 class TestBotFilter:
104 """Bot comments occupy top-comment slots without carrying community signal."""
105
106 @staticmethod
107 def _comment_html(author, thing_id="t1_botfilter1", score=999):
108 return (
109 f'<shreddit-comment author="{author}" thingId="{thing_id}" '
110 f'score="{score}" permalink="/r/test/comments/1/x/{thing_id}/">'
111 f'</shreddit-comment>'
112 f'<div id="{thing_id}-post-rtjson-content">'
113 f'<p>I will be messaging you in 3 days to remind you of this link.</p>'
114 f'</div>'
115 )
116
117 def test_known_bots_dropped(self):
118 for bot in ("RemindMeBot", "AutoModerator", "sneakpeekbot"):
119 assert rs.parse_comments(self._comment_html(bot)) == [], bot
120
121 def test_bot_match_is_case_insensitive(self):
122 assert rs.parse_comments(self._comment_html("remindmebot")) == []
123
124 def test_separator_suffix_bots_dropped(self):
125 for bot in ("some-random-bot", "subreddit_bot"):
126 assert rs.parse_comments(self._comment_html(bot)) == [], bot
127
128 def test_camelcase_bots_dropped(self):
129 # The separator-free convention is the common one on Reddit.
130 for bot in ("WikiTextBot", "RepostSleuthBot", "RemindMeBot2"):
131 assert rs.parse_comments(self._comment_html(bot)) == [], bot
132
133 def test_human_authors_kept(self):
134 # Names merely ending in "bot" are people, not bots. The capital B in
135 # the camelCase rule is what separates "WikiTextBot" from "Talbot".
136 for human in ("Talbot", "abbot", "u_bothell_local", "MSRS-",
137 "TheBotanist", "Botany101", "Robotics_fan"):
138 out = rs.parse_comments(self._comment_html(human))
139 assert len(out) == 1, human
140 assert out[0]["author"] == human
141
142 def test_bot_does_not_displace_human_from_slot(self):
143 # The reported failure was a bot *taking a slot*, not merely appearing:
144 # it outscores the humans, so it wins the ranking before truncation.
145 html = (self._comment_html("RemindMeBot", thing_id="t1_bot", score=999)
146 + self._comment_html("real_person", thing_id="t1_human", score=5))
147 out = rs.parse_comments(html, limit=1)
148 assert [c["author"] for c in out] == ["real_person"]
149
150 def test_is_bot_author_handles_blank(self):
151 assert rs._is_bot_author("") is False
152 assert rs._is_bot_author(None) is False
153
154
155 class TestTotalComments:
156 def test_reads_total(self):
157 assert rs._total_comments(_html()) == 14
158
159 def test_missing_returns_none(self):
160 assert rs._total_comments("<html></html>") is None
161
162
163 class TestFetchComments:
164 """fetch_comments wires URL -> svc fetch -> parse, never raising."""
165
166 def test_happy_path(self):
167 url = "https://www.reddit.com/r/Rakuten/comments/1taeiw0/title/"
168 with mock.patch.object(rs.http, "get_text", return_value=_html()) as m:
169 out = rs.fetch_comments(url)
170 # svc endpoint, not .json
171 assert "/svc/shreddit/comments/" in m.call_args[0][0]
172 assert ".json" not in m.call_args[0][0]
173 assert out["num_comments"] == 14
174 assert len(out["top_comments"]) >= 1
175 first = out["top_comments"][0]
176 assert {"score", "date", "author", "excerpt", "url"} <= set(first.keys())
177 assert isinstance(out["comment_insights"], list)
178
179 def test_bad_url_returns_empty(self):
180 out = rs.fetch_comments("https://www.reddit.com/r/Rakuten/")
181 assert out["top_comments"] == [] and out["num_comments"] is None
182
183 def test_fetch_failure_returns_empty(self):
184 url = "https://www.reddit.com/r/Rakuten/comments/1taeiw0/title/"
185 with mock.patch.object(rs.http, "get_text", return_value=None), \
186 mock.patch.object(rs.reddit_arctic, "fetch_post_comments", return_value=[]):
187 out = rs.fetch_comments(url)
188 assert out["top_comments"] == [] and out["num_comments"] is None
189
190
191 class TestEnrichmentBudget:
192 """Busy topics enrich more threads and carry more comments per thread."""
193
194 def test_enrich_limits_by_depth(self):
195 assert rs.ENRICH_LIMITS == {"quick": 4, "default": 8, "deep": 12}
196
197 def test_parse_comments_returns_up_to_twelve(self):
198 html = "".join(
199 f'<shreddit-comment author="user{i}" thingId="t1_c{i}" score="{100 - i}" '
200 f'permalink="/r/test/comments/1/x/t1_c{i}/"></shreddit-comment>'
201 f'<div id="t1_c{i}-post-rtjson-content"><p>comment number {i} body text</p></div>'
202 for i in range(30)
203 )
204 out = rs.parse_comments(html)
205 assert len(out) == rs.MAX_COMMENTS == 12
206 assert [c["score"] for c in out] == list(range(100, 88, -1))
207
208
209 class TestFetchCommentsFallback:
210 """fetch_comments falls back to the arctic-shift archive when the shreddit
211 comment partials return nothing (datacenter egress 403)."""
212
213 URL = "https://www.reddit.com/r/Rakuten/comments/1taeiw0/title/"
214
215 def _arctic_comment(self, score=10, body="great thread", author="u"):
216 return {
217 "score": score, "date": "2026-07-02", "author": author,
218 "body": body, "excerpt": body[:200], "permalink": "/r/Rakuten/comments/1taeiw0/x/",
219 "url": "https://reddit.com/r/Rakuten/comments/1taeiw0/x/",
220 }
221
222 def test_arctic_fallback_when_shreddit_empty(self):
223 comments = [self._arctic_comment(score=42)]
224 future_deadline = time.monotonic() + 123.0
225 with mock.patch.object(rs.http, "get_text", return_value=None), \
226 mock.patch.object(rs.reddit_arctic, "fetch_post_comments",
227 return_value=comments) as arctic:
228 out = rs.fetch_comments(self.URL, deadline=future_deadline)
229 assert out["top_comments"] == [{
230 "score": 42, "date": "2026-07-02", "author": "u",
231 "excerpt": "great thread", "url": "https://reddit.com/r/Rakuten/comments/1taeiw0/x/",
232 "depth": 0,
233 }]
234 assert out["comment_insights"] == [] or isinstance(out["comment_insights"], list)
235 assert out["num_comments"] is None # archive rows carry no post total
236 arctic.assert_called_once_with(
237 "1taeiw0", limit=rs.MAX_COMMENTS, skip_author=rs._is_bot_author,
238 deadline=future_deadline)
239
240 def test_shreddit_results_skip_arctic(self):
241 with mock.patch.object(rs.http, "get_text", return_value=_html()), \
242 mock.patch.object(rs.reddit_arctic, "fetch_post_comments") as arctic:
243 out = rs.fetch_comments(self.URL)
244 assert out["top_comments"] # shreddit parse results
245 assert out["num_comments"] == 14
246 arctic.assert_not_called()
247
248 def test_both_empty_returns_empty(self):
249 with mock.patch.object(rs.http, "get_text", return_value=None), \
250 mock.patch.object(rs.reddit_arctic, "fetch_post_comments", return_value=[]):
251 out = rs.fetch_comments(self.URL)
252 assert out["top_comments"] == [] and out["num_comments"] is None
253
254 def test_both_empty_keeps_shreddit_total(self):
255 html = '<shreddit-comment-tree-stats total-comments="37"></shreddit-comment-tree-stats>'
256 with mock.patch.object(rs.http, "get_text", return_value=html), \
257 mock.patch.object(rs.reddit_arctic, "fetch_post_comments", return_value=[]):
258 out = rs.fetch_comments(self.URL)
259 assert out["top_comments"] == [] and out["num_comments"] == 37
260
261 def test_never_raises_when_arctic_fails(self):
262 with mock.patch.object(rs.http, "get_text", return_value=None), \
263 mock.patch.object(rs.reddit_arctic, "fetch_post_comments",
264 side_effect=Exception("boom")):
265 out = rs.fetch_comments(self.URL)
266 assert out["top_comments"] == [] and out["num_comments"] is None
267
267 lines PYTHON