返回 last30days-skill
test_reddit.py
根目录 / tests / test_reddit.py
1 import unittest
2
3 import pytest
4
5 from lib.reddit import (
6 _extract_date,
7 _extract_score,
8 _extract_subreddit_name,
9 _normalize_reddit_id,
10 _total_engagement,
11 enrich_with_comments,
12 )
13
14
15 class TestExtractSubredditName(unittest.TestCase):
16 def test_from_string(self):
17 self.assertEqual("openclaw", _extract_subreddit_name("openclaw"))
18
19 def test_from_dict_with_name(self):
20 self.assertEqual(
21 "openclaw",
22 _extract_subreddit_name({"id": "t5_ghydwa", "name": "openclaw"}),
23 )
24
25 def test_from_dict_with_display_name(self):
26 self.assertEqual(
27 "LocalLLM",
28 _extract_subreddit_name({"display_name": "LocalLLM"}),
29 )
30
31 def test_from_dict_name_preferred_over_display_name(self):
32 self.assertEqual(
33 "name_wins",
34 _extract_subreddit_name({"name": "name_wins", "display_name": "display"}),
35 )
36
37 def test_empty_string(self):
38 self.assertEqual("", _extract_subreddit_name(""))
39
40 def test_empty_dict(self):
41 self.assertEqual("", _extract_subreddit_name({}))
42
43 def test_strips_whitespace(self):
44 self.assertEqual("test", _extract_subreddit_name(" test "))
45
46
47 class TestExtractScore(unittest.TestCase):
48 def test_ups(self):
49 self.assertEqual(42, _extract_score({"ups": 42}))
50
51 def test_score_field(self):
52 self.assertEqual(77, _extract_score({"score": 77}))
53
54 def test_votes(self):
55 self.assertEqual(99, _extract_score({"votes": 99}))
56
57 def test_ups_preferred_over_votes(self):
58 self.assertEqual(10, _extract_score({"ups": 10, "votes": 99}))
59
60 def test_missing(self):
61 self.assertEqual(0, _extract_score({}))
62
63 def test_zero_preserved(self):
64 self.assertEqual(0, _extract_score({"ups": 0}))
65
66 def test_zero_ups_does_not_fall_through(self):
67 # ups=0 should be returned, not fall through to score
68 self.assertEqual(0, _extract_score({"ups": 0, "score": 5}))
69
70
71 class TestExtractDate(unittest.TestCase):
72 def test_unix_timestamp(self):
73 self.assertEqual("2024-05-03", _extract_date({"created_utc": 1714694957}))
74
75 def test_iso_string(self):
76 result = _extract_date({"created_at": "2024-05-03T01:09:17.620000+0000"})
77 self.assertEqual("2024-05-03", result)
78
79 def test_iso_with_z_suffix(self):
80 result = _extract_date({"created_at": "2024-05-03T01:09:17Z"})
81 self.assertEqual("2024-05-03", result)
82
83 def test_created_utc_preferred(self):
84 result = _extract_date({"created_utc": 1714694957, "created_at": "2025-01-01T00:00:00Z"})
85 self.assertEqual("2024-05-03", result)
86
87 def test_missing(self):
88 self.assertIsNone(_extract_date({}))
89
90
91 class TestNormalizeRedditId(unittest.TestCase):
92 def test_strips_t3_prefix(self):
93 self.assertEqual("abc123", _normalize_reddit_id("t3_abc123"))
94
95 def test_no_prefix(self):
96 self.assertEqual("abc123", _normalize_reddit_id("abc123"))
97
98 def test_empty(self):
99 self.assertEqual("", _normalize_reddit_id(""))
100
101 def test_none(self):
102 self.assertEqual("", _normalize_reddit_id(None))
103
104
105 class TestTotalEngagement(unittest.TestCase):
106 def test_score_plus_comments(self):
107 item = {"engagement": {"score": 100, "num_comments": 50}}
108 self.assertEqual(150, _total_engagement(item))
109
110 def test_high_comments_low_score(self):
111 item = {"engagement": {"score": 1, "num_comments": 1387}}
112 self.assertEqual(1388, _total_engagement(item))
113
114 def test_missing_engagement(self):
115 self.assertEqual(0, _total_engagement({}))
116
117 def test_none_values(self):
118 item = {"engagement": {"score": None, "num_comments": None}}
119 self.assertEqual(0, _total_engagement(item))
120
121 def test_score_only(self):
122 item = {"engagement": {"score": 42}}
123 self.assertEqual(42, _total_engagement(item))
124
125
126 class TestEnrichSelectsTopEngagement(unittest.TestCase):
127 """Verify enrich_with_comments picks threads by total engagement, not list order."""
128
129 def test_high_comment_thread_enriched_over_low_engagement(self):
130 """A thread with 1387 comments but score:1 should be enriched before
131 a thread with score:5 and 0 comments."""
132 from unittest.mock import patch
133
134 items = [
135 # Low engagement thread (first in list)
136 {
137 "id": "R1",
138 "url": "https://www.reddit.com/r/test/comments/low",
139 "engagement": {"score": 5, "num_comments": 0},
140 },
141 # High engagement thread (second in list)
142 {
143 "id": "R2",
144 "url": "https://www.reddit.com/r/test/comments/high",
145 "engagement": {"score": 1, "num_comments": 1387},
146 },
147 # Medium engagement
148 {
149 "id": "R3",
150 "url": "https://www.reddit.com/r/test/comments/med",
151 "engagement": {"score": 50, "num_comments": 10},
152 },
153 ]
154
155 enriched_urls = []
156
157 def mock_fetch_comments(url, token, **kwargs):
158 enriched_urls.append(url)
159 return [{"body": "Great thread!", "ups": 10, "author": "testuser"}]
160
161 # Only allow 1 enrichment to prove selection order matters
162 with patch("lib.reddit.fetch_post_comments", side_effect=mock_fetch_comments):
163 result = enrich_with_comments(items, token="fake", depth="quick")
164
165 # With quick depth (3 enrichments), all 3 should be enriched.
166 # But the key assertion: the high-comment thread (R2) must be included.
167 self.assertIn(
168 "https://www.reddit.com/r/test/comments/high",
169 enriched_urls,
170 "High-comment thread should always be selected for enrichment",
171 )
172
173 def test_enrichment_order_by_engagement(self):
174 """With a budget of 1, only the highest-engagement thread gets enriched."""
175 from unittest.mock import patch
176
177 items = [
178 {
179 "id": "R1",
180 "url": "https://www.reddit.com/r/test/comments/a",
181 "engagement": {"score": 200, "num_comments": 5},
182 },
183 {
184 "id": "R2",
185 "url": "https://www.reddit.com/r/test/comments/b",
186 "engagement": {"score": 1, "num_comments": 1500},
187 },
188 ]
189
190 enriched_urls = []
191
192 def mock_fetch_comments(url, token, **kwargs):
193 enriched_urls.append(url)
194 return [{"body": "Comment", "ups": 5, "author": "user"}]
195
196 # Override DEPTH_CONFIG to allow only 1 enrichment
197 custom_config = {"comment_enrichments": 1}
198 with patch("lib.reddit.DEPTH_CONFIG", {"test": custom_config, "default": custom_config}), \
199 patch("lib.reddit.fetch_post_comments", side_effect=mock_fetch_comments):
200 enrich_with_comments(items, token="fake", depth="test")
201
202 # R2 has 1501 total engagement vs R1's 205 -- R2 should be picked
203 self.assertEqual(len(enriched_urls), 1)
204 self.assertEqual(
205 enriched_urls[0],
206 "https://www.reddit.com/r/test/comments/b",
207 )
208
209
210 class TestEnrichmentBudget(unittest.TestCase):
211 """Tests for the enrichment time budget in enrich_with_comments()."""
212
213 def _make_items(self, n):
214 return [
215 {"url": f"https://reddit.com/r/test/comments/{i}/post", "score": 100 - i, "num_comments": 50,
216 "engagement": {"score": 100 - i, "num_comments": 50}}
217 for i in range(n)
218 ]
219
220 def test_all_complete_within_budget(self):
221 """When enrichment is fast, all items get comments."""
222 from unittest.mock import patch
223 items = self._make_items(3)
224 fast_comments = [{"body": "Great post!", "score": 42, "author": "user1"}]
225
226 with patch("lib.reddit.fetch_post_comments", return_value=fast_comments):
227 result = enrich_with_comments(items, "fake-token", depth="quick", budget_seconds=60)
228
229 enriched = [i for i in result if i.get("top_comments")]
230 self.assertEqual(len(enriched), 3)
231
232 def test_budget_zero_returns_items_unenriched(self):
233 """With budget=0, items are returned without enrichment (not discarded)."""
234 from unittest.mock import patch
235
236 items = self._make_items(3)
237
238 with patch("lib.reddit.fetch_post_comments") as fetch:
239 result = enrich_with_comments(items, "fake-token", depth="quick", budget_seconds=0)
240 self.assertIs(result, items)
241 self.assertEqual(len(result), 3)
242 self.assertTrue(all("top_comments" not in item for item in result))
243 fetch.assert_not_called()
244
245 def test_empty_items_returns_immediately(self):
246 result = enrich_with_comments([], "fake-token", depth="default", budget_seconds=60)
247 self.assertEqual(result, [])
248
249 def test_exceptions_dont_crash(self):
250 """If enrichment raises, items are returned without comments."""
251 from unittest.mock import patch
252 items = self._make_items(3)
253
254 with patch("lib.reddit.fetch_post_comments", side_effect=ConnectionError("boom")):
255 result = enrich_with_comments(items, "fake-token", depth="quick", budget_seconds=60)
256
257 self.assertEqual(len(result), 3)
258 enriched = [i for i in result if i.get("top_comments")]
259 self.assertEqual(len(enriched), 0)
260
261 if __name__ == "__main__":
262 unittest.main()
263
264
265 def test_window_to_time_filter_rounds_up_for_rolling_buckets(monkeypatch):
266 """Recent calendar windows need the next Reddit rolling bucket (Greptile on #860)."""
267 from datetime import date
268 from lib import reddit
269
270 class _FrozenDateTime:
271 @staticmethod
272 def now(tz=None):
273 class _D:
274 @staticmethod
275 def date():
276 return date(2026, 7, 24)
277 return _D()
278
279 monkeypatch.setattr(reddit, "datetime", _FrozenDateTime)
280 assert reddit._window_to_time_filter("2026-07-23", "2026-07-24") == "week"
281 assert reddit._window_to_time_filter("2026-07-17", "2026-07-24") == "month"
282 assert reddit._window_to_time_filter("2026-06-24", "2026-07-24") == "month"
283 # Just past the month bucket (+1 slack) needs year.
284 assert reddit._window_to_time_filter("2026-06-23", "2026-07-24") == "year"
285
286
287 def test_window_to_time_filter_covers_historical_from_date(monkeypatch):
288 """Short historical windows must still reach from_date (Greptile follow-up on #860)."""
289 from datetime import date
290 from lib import reddit
291
292 class _FrozenDateTime:
293 @staticmethod
294 def now(tz=None):
295 class _D:
296 @staticmethod
297 def date():
298 return date(2026, 7, 24)
299 return _D()
300
301 monkeypatch.setattr(reddit, "datetime", _FrozenDateTime)
302 # One-day request ending two weeks ago: span alone would pick "week" and
303 # miss the entire range; age of from_date requires "month".
304 assert reddit._window_to_time_filter("2026-07-09", "2026-07-10") == "month"
305
306
307 @pytest.mark.parametrize(
308 "depth,from_date,to_date,expected",
309 [
310 ("default", "2026-04-25", "2026-07-24", "year"),
311 ("quick", "2026-06-24", "2026-07-24", "month"),
312 ("deep", "2026-04-25", "2026-07-24", "year"),
313 ("quick", "2026-07-09", "2026-07-10", "month"),
314 ("default", "2026-07-23", "2026-07-24", "week"),
315 ("deep", "2026-07-23", "2026-07-24", "week"),
316 ],
317 )
318 def test_search_reddit_requests_complete_date_window(monkeypatch, depth, from_date, to_date, expected):
319 from datetime import datetime, timezone
320 from unittest.mock import Mock
321
322 from lib import reddit
323
324 clock = Mock()
325 clock.now.return_value = datetime(2026, 7, 24, tzinfo=timezone.utc)
326 monkeypatch.setattr(reddit, "datetime", clock)
327 global_search = Mock(return_value=[])
328 subreddit_search = Mock(return_value=[])
329 monkeypatch.setattr(reddit, "_global_search", global_search)
330 monkeypatch.setattr(reddit, "_subreddit_search", subreddit_search)
331
332 reddit.search_reddit(
333 "Python", from_date, to_date, depth=depth,
334 token="dummy-scrapecreators-key", subreddits=["Python"],
335 )
336
337 assert global_search.call_count > 0
338 assert subreddit_search.call_count > 0
339 assert {call.args[-1] for call in global_search.call_args_list} == {expected}
340 assert {call.args[-1] for call in subreddit_search.call_args_list} == {expected}
341
341 lines PYTHON