| 1 | """Tests for reddit_arctic — keyless post-score lookup via arctic-shift (U6).""" |
| 2 | |
| 3 | import socket |
| 4 | from unittest import mock |
| 5 | from urllib.error import URLError |
| 6 | from urllib.parse import parse_qs, urlsplit |
| 7 | |
| 8 | import pytest |
| 9 | |
| 10 | from lib import reddit_arctic, reddit_keyless |
| 11 | |
| 12 | |
| 13 | @pytest.fixture(autouse=True) |
| 14 | def _no_arctic_network(): |
| 15 | # Override conftest's stub so this module exercises the real fetch_scores; |
| 16 | # network is mocked per-test at http.get. Clear the in-run cache each time. |
| 17 | reddit_arctic._cache.clear() |
| 18 | yield |
| 19 | reddit_arctic._cache.clear() |
| 20 | |
| 21 | |
| 22 | def _resp(rows): |
| 23 | return {"data": rows} |
| 24 | |
| 25 | |
| 26 | def _tree(rows): |
| 27 | """A /comments/tree response: each comment wrapped as a t1 node.""" |
| 28 | return {"data": [{"kind": "t1", "data": row} for row in rows]} |
| 29 | |
| 30 | |
| 31 | class TestFetchScores: |
| 32 | def test_returns_scores_by_id(self): |
| 33 | with mock.patch.object(reddit_arctic.http, "get", |
| 34 | return_value=_resp([{"id": "abc", "score": 1531, "num_comments": 336}])): |
| 35 | out = reddit_arctic.fetch_scores(["abc"]) |
| 36 | assert out == {"abc": {"score": 1531, "num_comments": 336}} |
| 37 | |
| 38 | def test_strips_t3_prefix(self): |
| 39 | with mock.patch.object(reddit_arctic.http, "get", |
| 40 | return_value=_resp([{"id": "t3_xyz", "score": 5, "num_comments": 2}])): |
| 41 | out = reddit_arctic.fetch_scores(["xyz"]) |
| 42 | assert out["xyz"]["score"] == 5 |
| 43 | |
| 44 | def test_rate_limit_response_degrades(self): |
| 45 | # arctic-shift answers {"error": "...slow down"} with no data list. |
| 46 | with mock.patch.object(reddit_arctic.http, "get", |
| 47 | return_value={"error": "Timeout. Maybe slow down a bit"}): |
| 48 | out = reddit_arctic.fetch_scores(["abc"]) |
| 49 | assert out == {} |
| 50 | |
| 51 | def test_network_error_degrades(self): |
| 52 | with mock.patch.object(reddit_arctic.http, "get", side_effect=Exception("boom")): |
| 53 | out = reddit_arctic.fetch_scores(["abc"]) |
| 54 | assert out == {} |
| 55 | |
| 56 | def test_in_run_cache_avoids_refetch(self): |
| 57 | with mock.patch.object(reddit_arctic.http, "get", |
| 58 | return_value=_resp([{"id": "abc", "score": 9, "num_comments": 1}])) as g: |
| 59 | reddit_arctic.fetch_scores(["abc"]) |
| 60 | reddit_arctic.fetch_scores(["abc"]) # served from cache, no 2nd call |
| 61 | assert g.call_count == 1 |
| 62 | |
| 63 | def test_dedupes_into_single_batch(self): |
| 64 | with mock.patch.object(reddit_arctic.http, "get", |
| 65 | return_value=_resp([{"id": "a", "score": 1, "num_comments": 0}, |
| 66 | {"id": "b", "score": 2, "num_comments": 0}])) as g: |
| 67 | out = reddit_arctic.fetch_scores(["a", "b", "a", ""]) |
| 68 | assert g.call_count == 1 |
| 69 | assert set(out) == {"a", "b"} |
| 70 | |
| 71 | |
| 72 | def _listing_row(pid="abc123", title="matcha farm tour", score=406, ncmt=88, |
| 73 | created=1783000000, subreddit="tea", permalink="/r/tea/comments/abc123/x/"): |
| 74 | return { |
| 75 | "id": pid, "title": title, "score": score, "num_comments": ncmt, |
| 76 | "created_utc": created, "subreddit": subreddit, |
| 77 | "permalink": permalink, "author": "u", "selftext": "", |
| 78 | } |
| 79 | |
| 80 | |
| 81 | @pytest.fixture |
| 82 | def listing_clock(monkeypatch): |
| 83 | now = [0.0] |
| 84 | |
| 85 | def advance(seconds): |
| 86 | now[0] += seconds |
| 87 | |
| 88 | monkeypatch.setattr(reddit_arctic.time, "time", lambda: now[0]) |
| 89 | monkeypatch.setattr(reddit_arctic.time, "monotonic", lambda: now[0]) |
| 90 | monkeypatch.setattr(reddit_arctic.time, "sleep", advance) |
| 91 | return advance |
| 92 | |
| 93 | |
| 94 | class TestFetchListings: |
| 95 | """fetch_listings serves scored subreddit listings from the archive — |
| 96 | the keyless fallback for hosts where shreddit partials 403.""" |
| 97 | |
| 98 | def test_returns_normalized_scored_posts(self): |
| 99 | with mock.patch.object( |
| 100 | reddit_arctic.http, "get", |
| 101 | return_value=_resp([_listing_row()]), |
| 102 | ) as g: |
| 103 | out = reddit_arctic.fetch_listings(["tea"], query="matcha") |
| 104 | assert len(out) == 1 |
| 105 | post = out[0] |
| 106 | assert post["title"] == "matcha farm tour" |
| 107 | assert post["score"] == 406 |
| 108 | assert post["engagement"]["score"] == 406 |
| 109 | assert post["num_comments"] == 88 |
| 110 | assert post["subreddit"] == "tea" |
| 111 | assert post["metadata"]["post_id"] == "abc123" # t3_ prefix stripped |
| 112 | assert post["date"] == "2026-07-02" # created_utc -> YYYY-MM-DD |
| 113 | assert post["url"].startswith("https://www.reddit.com/r/tea/comments/") |
| 114 | assert post["why_relevant"] == "Reddit listing (arctic-shift)" |
| 115 | # one call per subreddit, recent-first, depth-default volume |
| 116 | assert g.call_count == 1 |
| 117 | assert parse_qs(urlsplit(g.call_args[0][0]).query) == { |
| 118 | "subreddit": ["tea"], "limit": ["25"], "sort": ["desc"], |
| 119 | } |
| 120 | |
| 121 | def test_strips_r_prefix_and_skips_all(self): |
| 122 | with mock.patch.object(reddit_arctic.http, "get", |
| 123 | return_value=_resp([_listing_row(subreddit="tea")])) as g: |
| 124 | out = reddit_arctic.fetch_listings(["r/tea", "all", ""]) |
| 125 | assert len(out) == 1 |
| 126 | assert g.call_count == 1 # only r/tea fetched; "all"/"" skipped |
| 127 | |
| 128 | def test_processes_all_subreddits_no_cap(self, listing_clock): |
| 129 | """All requested subreddits are processed (no hard cap).""" |
| 130 | subs = [f"sub{i}" for i in range(20)] |
| 131 | with mock.patch.object(reddit_arctic.http, "get", |
| 132 | return_value=_resp([_listing_row()])) as g: |
| 133 | reddit_arctic.fetch_listings(subs) |
| 134 | # All 20 should be fetched (no cap). |
| 135 | assert g.call_count == 20 |
| 136 | |
| 137 | def test_depth_controls_volume(self): |
| 138 | for depth, want in (("quick", 10), ("default", 25), ("deep", 50)): |
| 139 | with mock.patch.object(reddit_arctic.http, "get", |
| 140 | return_value=_resp([_listing_row()])) as g: |
| 141 | reddit_arctic.fetch_listings(["tea"], depth=depth) |
| 142 | assert f"limit={want}" in g.call_args[0][0], depth |
| 143 | |
| 144 | def test_multi_sort_request_increases_limit(self): |
| 145 | """When multiple sorts are requested, fetch 2x posts to compensate.""" |
| 146 | with mock.patch.object(reddit_arctic.http, "get", |
| 147 | return_value=_resp([_listing_row()])) as g: |
| 148 | reddit_arctic.fetch_listings(["tea"], depth="default", sorts=["top", "hot", "new"]) |
| 149 | # default depth = 25, with 3 sorts → 25 * 2 = 50 |
| 150 | assert "limit=50" in g.call_args[0][0] |
| 151 | |
| 152 | def test_single_sort_uses_base_limit(self): |
| 153 | """Single sort uses base limit, no multiplier.""" |
| 154 | with mock.patch.object(reddit_arctic.http, "get", |
| 155 | return_value=_resp([_listing_row()])) as g: |
| 156 | reddit_arctic.fetch_listings(["tea"], depth="default", sorts=["top"]) |
| 157 | assert "limit=25" in g.call_args[0][0] |
| 158 | |
| 159 | def test_dedupes_by_url(self): |
| 160 | rows = [_listing_row(), _listing_row()] |
| 161 | with mock.patch.object(reddit_arctic.http, "get", return_value=_resp(rows)): |
| 162 | out = reddit_arctic.fetch_listings(["tea"]) |
| 163 | assert len(out) == 1 |
| 164 | |
| 165 | def test_network_error_degrades_to_empty(self): |
| 166 | with mock.patch.object(reddit_arctic.http, "get", side_effect=Exception("boom")): |
| 167 | assert reddit_arctic.fetch_listings(["tea"]) == [] |
| 168 | |
| 169 | def test_rate_limit_response_degrades_to_empty(self): |
| 170 | with mock.patch.object(reddit_arctic.http, "get", |
| 171 | return_value={"error": "Timeout. Maybe slow down a bit"}): |
| 172 | assert reddit_arctic.fetch_listings(["tea"]) == [] |
| 173 | |
| 174 | def test_empty_subreddits_returns_empty(self): |
| 175 | assert reddit_arctic.fetch_listings([]) == [] |
| 176 | |
| 177 | def test_removed_author_normalized(self): |
| 178 | row = _listing_row() |
| 179 | row["author"] = "[deleted]" |
| 180 | with mock.patch.object(reddit_arctic.http, "get", return_value=_resp([row])): |
| 181 | out = reddit_arctic.fetch_listings(["tea"]) |
| 182 | assert out[0]["author"] == "[deleted]" |
| 183 | |
| 184 | def test_cache_is_size_bounded(self): |
| 185 | # The in-run memo never grows past CACHE_MAX; scores are still returned |
| 186 | # for the current call once the cache is full. |
| 187 | with mock.patch.object(reddit_arctic, "CACHE_MAX", 1), \ |
| 188 | mock.patch.object(reddit_arctic.http, "get", |
| 189 | return_value=_resp([{"id": "a", "score": 1, "num_comments": 0}, |
| 190 | {"id": "b", "score": 2, "num_comments": 0}])): |
| 191 | out = reddit_arctic.fetch_scores(["a", "b"]) |
| 192 | assert set(out) == {"a", "b"} # both returned |
| 193 | assert len(reddit_arctic._cache) <= 1 # cache stayed bounded |
| 194 | |
| 195 | def test_empty_input_makes_no_call(self): |
| 196 | with mock.patch.object(reddit_arctic.http, "get") as g: |
| 197 | out = reddit_arctic.fetch_scores([]) |
| 198 | assert out == {} |
| 199 | g.assert_not_called() |
| 200 | |
| 201 | def test_malformed_rows_skipped(self): |
| 202 | rows = [{"id": "ok", "score": 7, "num_comments": 3}, |
| 203 | {"id": "", "score": 1}, # no id |
| 204 | "not-a-dict", # junk |
| 205 | {"id": "bad", "score": "x"}] # unparseable score |
| 206 | with mock.patch.object(reddit_arctic.http, "get", return_value=_resp(rows)): |
| 207 | out = reddit_arctic.fetch_scores(["ok", "bad"]) |
| 208 | assert out == {"ok": {"score": 7, "num_comments": 3}} |
| 209 | |
| 210 | |
| 211 | class TestWindowedFetchListings: |
| 212 | def test_dns_retries_cannot_spend_other_subreddits_request_time(self, listing_clock): |
| 213 | requested = [] |
| 214 | |
| 215 | def open_request(request, timeout): |
| 216 | requested.append(parse_qs(urlsplit(request.full_url).query)["subreddit"][0]) |
| 217 | listing_clock(timeout) |
| 218 | raise URLError(socket.gaierror(socket.EAI_AGAIN, "temporary DNS failure")) |
| 219 | |
| 220 | with mock.patch.object(reddit_arctic.http, "_open_request", side_effect=open_request): |
| 221 | out = reddit_arctic.fetch_listings( |
| 222 | ["tea", "coffee", "cocoa"], from_date="2026-09-20", to_date="2026-10-20", |
| 223 | ) |
| 224 | |
| 225 | assert out == [] |
| 226 | assert requested == ["tea", "coffee", "cocoa"] |
| 227 | assert reddit_arctic.time.monotonic() <= reddit_arctic._LISTING_DEADLINE_SECONDS |
| 228 | |
| 229 | def test_slow_first_subreddit_does_not_starve_other_subreddits(self, listing_clock): |
| 230 | requested = [] |
| 231 | |
| 232 | def get(url, **kwargs): |
| 233 | sub = parse_qs(urlsplit(url).query)["subreddit"][0] |
| 234 | requested.append(sub) |
| 235 | listing_clock(kwargs["timeout"]) |
| 236 | if sub == "tea": |
| 237 | raise TimeoutError("slow subreddit") |
| 238 | return _resp([_listing_row( |
| 239 | pid=sub, subreddit=sub, permalink=f"/r/{sub}/comments/{sub}/x/", |
| 240 | )]) |
| 241 | |
| 242 | with mock.patch.object(reddit_arctic.http, "get", side_effect=get): |
| 243 | out = reddit_arctic.fetch_listings( |
| 244 | ["tea", "coffee", "cocoa"], from_date="2026-09-20", to_date="2026-10-20", |
| 245 | ) |
| 246 | |
| 247 | assert requested == ["tea", "coffee", "cocoa"] |
| 248 | assert [post["subreddit"] for post in out] == ["coffee", "cocoa"] |
| 249 | assert reddit_arctic.time.time() <= reddit_arctic._LISTING_DEADLINE_SECONDS |
| 250 | |
| 251 | @pytest.mark.parametrize(("start", "end", "boundaries"), [ |
| 252 | # Newest slice first, so a deadline drops the oldest week. |
| 253 | ("2026-09-20", "2026-10-20", [ |
| 254 | ("2026-10-14", "2026-10-20"), |
| 255 | ("2026-10-06", "2026-10-14"), |
| 256 | ("2026-09-28", "2026-10-06"), |
| 257 | ("2026-09-20", "2026-09-28"), |
| 258 | ]), |
| 259 | ("2026-10-19", "2026-10-20", [("2026-10-19", "2026-10-20")]), |
| 260 | ]) |
| 261 | def test_slices_cover_requested_boundaries(self, listing_clock, start, end, boundaries): |
| 262 | with mock.patch.object(reddit_arctic.http, "get", return_value=_resp([])) as get: |
| 263 | reddit_arctic.fetch_listings(["tea"], from_date=start, to_date=end) |
| 264 | |
| 265 | queries = [parse_qs(urlsplit(call.args[0]).query) for call in get.call_args_list] |
| 266 | assert [(query["after"][0], query["before"][0]) for query in queries] == boundaries |
| 267 | assert all(query["limit"] == ["100"] and query["sort"] == ["desc"] for query in queries) |
| 268 | |
| 269 | def test_visits_every_subreddit_before_the_next_slice(self, listing_clock): |
| 270 | with mock.patch.object(reddit_arctic.http, "get", return_value=_resp([])) as get: |
| 271 | reddit_arctic.fetch_listings( |
| 272 | ["tea", "coffee"], from_date="2026-09-20", to_date="2026-10-20", |
| 273 | ) |
| 274 | |
| 275 | queries = [parse_qs(urlsplit(call.args[0]).query) for call in get.call_args_list] |
| 276 | assert [query["subreddit"][0] for query in queries] == ["tea", "coffee"] * 4 |
| 277 | assert [query["after"][0] for query in queries] == [ |
| 278 | "2026-10-14", "2026-10-14", "2026-10-06", "2026-10-06", |
| 279 | "2026-09-28", "2026-09-28", "2026-09-20", "2026-09-20", |
| 280 | ] |
| 281 | |
| 282 | def test_keeps_highest_scores_across_slices_per_subreddit(self, listing_clock): |
| 283 | scores = {"tea": iter([500, 1, 300, 2]), "coffee": iter([4, 70, 10, 60])} |
| 284 | |
| 285 | def get(url, **kwargs): |
| 286 | sub = parse_qs(urlsplit(url).query)["subreddit"][0] |
| 287 | score = next(scores[sub]) |
| 288 | return _resp([_listing_row( |
| 289 | pid=f"{sub}{score}", subreddit=sub, score=str(score), |
| 290 | permalink=f"/r/{sub}/comments/{sub}{score}/x/", |
| 291 | )]) |
| 292 | |
| 293 | with mock.patch.object(reddit_arctic.http, "get", side_effect=get): |
| 294 | out = reddit_arctic.fetch_listings( |
| 295 | ["tea", "coffee"], limit=2, from_date="2026-09-20", to_date="2026-10-20", |
| 296 | ) |
| 297 | |
| 298 | assert [(post["subreddit"], post["score"]) for post in out] == [ |
| 299 | ("tea", 500), ("tea", 300), ("coffee", 70), ("coffee", 60), |
| 300 | ] |
| 301 | |
| 302 | def test_duplicate_slice_rows_do_not_consume_selection_slots(self, listing_clock): |
| 303 | best = _listing_row(score=100) |
| 304 | second = _listing_row(pid="second", score=90, permalink="/r/tea/comments/second/x/") |
| 305 | with mock.patch.object(reddit_arctic.http, "get", side_effect=[ |
| 306 | _resp([best]), _resp([best, second]), _resp([]), _resp([]), |
| 307 | ]): |
| 308 | out = reddit_arctic.fetch_listings( |
| 309 | ["tea"], limit=2, from_date="2026-09-20", to_date="2026-10-20", |
| 310 | ) |
| 311 | |
| 312 | assert [post["metadata"]["post_id"] for post in out] == ["abc123", "second"] |
| 313 | |
| 314 | @pytest.mark.parametrize("failure", [TimeoutError("unreachable"), {"data": None}]) |
| 315 | def test_failed_slice_keeps_other_slices(self, listing_clock, failure): |
| 316 | later = _listing_row(pid="later", score=900, permalink="/r/tea/comments/later/x/") |
| 317 | with mock.patch.object(reddit_arctic.http, "get", side_effect=[ |
| 318 | _resp([_listing_row()]), failure, _resp([later]), _resp([]), |
| 319 | ]) as get: |
| 320 | out = reddit_arctic.fetch_listings( |
| 321 | ["tea"], from_date="2026-09-20", to_date="2026-10-20", |
| 322 | ) |
| 323 | |
| 324 | assert get.call_count == 4 |
| 325 | assert [post["metadata"]["post_id"] for post in out] == ["later", "abc123"] |
| 326 | |
| 327 | def test_deadline_keeps_best_posts_from_completed_slices(self, listing_clock): |
| 328 | scores = iter([10, 90, 70, 1000]) |
| 329 | timeouts = [] |
| 330 | |
| 331 | def get(url, **kwargs): |
| 332 | timeouts.append(kwargs["timeout"]) |
| 333 | listing_clock(kwargs["timeout"]) |
| 334 | score = next(scores) |
| 335 | return _resp([_listing_row( |
| 336 | pid=str(score), score=score, permalink=f"/r/tea/comments/{score}/x/", |
| 337 | )]) |
| 338 | |
| 339 | with mock.patch.object(reddit_arctic.http, "get", side_effect=get): |
| 340 | out = reddit_arctic.fetch_listings( |
| 341 | ["tea"], limit=2, from_date="2026-09-20", to_date="2026-10-20", |
| 342 | ) |
| 343 | |
| 344 | assert [post["score"] for post in out] == [90, 70] |
| 345 | assert timeouts == pytest.approx([15, 15, 14.2]) |
| 346 | assert reddit_arctic.time.time() <= reddit_arctic._LISTING_DEADLINE_SECONDS |
| 347 | |
| 348 | def test_pacing_does_not_start_request_after_deadline(self, listing_clock): |
| 349 | def get(url, **kwargs): |
| 350 | listing_clock(0.8) |
| 351 | return _resp([_listing_row()]) |
| 352 | |
| 353 | with mock.patch.object(reddit_arctic, "_LISTING_DEADLINE_SECONDS", 1), \ |
| 354 | mock.patch.object(reddit_arctic.http, "get", side_effect=get) as request: |
| 355 | out = reddit_arctic.fetch_listings( |
| 356 | ["tea", "coffee"], from_date="2026-09-20", to_date="2026-10-20", |
| 357 | ) |
| 358 | |
| 359 | assert request.call_count == 1 |
| 360 | assert [post["metadata"]["post_id"] for post in out] == ["abc123"] |
| 361 | assert reddit_arctic.time.time() == pytest.approx(1) |
| 362 | |
| 363 | def test_discovery_forwards_dates_to_dedicated_and_category_listings(self, listing_clock): |
| 364 | queries = [] |
| 365 | |
| 366 | def get(url, **kwargs): |
| 367 | query = parse_qs(urlsplit(url).query) |
| 368 | queries.append(query) |
| 369 | sub = query["subreddit"][0] |
| 370 | return _resp([_listing_row( |
| 371 | pid=sub, subreddit=sub, permalink=f"/r/{sub}/comments/{sub}/x/", |
| 372 | )]) |
| 373 | |
| 374 | with mock.patch.object(reddit_keyless.reddit_search, "search", return_value=[]), \ |
| 375 | mock.patch.object(reddit_keyless.reddit_listing, "fetch_listings", return_value=[]), \ |
| 376 | mock.patch.object(reddit_arctic.http, "get", side_effect=get): |
| 377 | out = reddit_keyless._discover( |
| 378 | "matcha", "quick", ["tea"], dedicated_subreddits=["matcha"], |
| 379 | from_date="2026-09-20", to_date="2026-10-20", |
| 380 | ) |
| 381 | |
| 382 | assert [post["subreddit"] for post in out] == ["matcha", "tea"] |
| 383 | assert out[0]["dedicated"] is True |
| 384 | for sub in ("matcha", "tea"): |
| 385 | sub_queries = [query for query in queries if query["subreddit"] == [sub]] |
| 386 | assert len(sub_queries) == 4 |
| 387 | assert sub_queries[0]["before"] == ["2026-10-20"] |
| 388 | assert sub_queries[-1]["after"] == ["2026-09-20"] |
| 389 | |
| 390 | |
| 391 | def _comment_row(pid="mjwb1hg", author="u", body="great thread", score=42, |
| 392 | created=1783000000, permalink="/r/tea/comments/abc123/x/mjwb1hg/"): |
| 393 | return { |
| 394 | "id": pid, "author": author, "body": body, "score": score, |
| 395 | "created_utc": created, "permalink": permalink, "link_id": "t3_abc123", |
| 396 | } |
| 397 | |
| 398 | |
| 399 | class TestFetchPostComments: |
| 400 | """fetch_post_comments serves a post's top comments from the archive — |
| 401 | the keyless fallback for hosts where the shreddit comment partials 403.""" |
| 402 | |
| 403 | def test_returns_normalized_comments_sorted_desc(self): |
| 404 | rows = [_comment_row(score=1), _comment_row(score=99), _comment_row(score=42)] |
| 405 | with mock.patch.object(reddit_arctic.http, "get", return_value=_tree(rows)) as g: |
| 406 | out = reddit_arctic.fetch_post_comments("abc123", limit=10) |
| 407 | assert [c["score"] for c in out] == [99, 42, 1] |
| 408 | first = out[0] |
| 409 | assert first["author"] == "u" |
| 410 | assert first["body"] == "great thread" |
| 411 | assert first["excerpt"] == "great thread" |
| 412 | assert first["date"] == "2026-07-02" |
| 413 | assert first["url"] == "https://reddit.com/r/tea/comments/abc123/x/mjwb1hg/" |
| 414 | # link_id uses the t3_ prefix; the comment tree, ranked client-side |
| 415 | assert "link_id=t3_abc123" in g.call_args[0][0] |
| 416 | assert f"limit={reddit_arctic.FALLBACK_COMMENT_ROWS}" in g.call_args[0][0] |
| 417 | |
| 418 | def test_requests_the_comment_tree_not_a_recency_slice(self): |
| 419 | # The search endpoint sorts only by created_utc, so a capped slice of a |
| 420 | # busy thread held only its newest replies and missed the top-voted ones. |
| 421 | with mock.patch.object(reddit_arctic.http, "get", return_value=_tree([])) as g: |
| 422 | reddit_arctic.fetch_post_comments("abc123") |
| 423 | url = urlsplit(g.call_args[0][0]) |
| 424 | assert url.path == "/api/comments/tree" |
| 425 | assert "sort" not in parse_qs(url.query) |
| 426 | |
| 427 | def test_nested_replies_ranked_with_top_level(self): |
| 428 | # A top-voted reply nested under a low-scored parent must still rank |
| 429 | # first; more-stubs and non-dict children are skipped. |
| 430 | def node(score, replies="", pid="c", depth=0): |
| 431 | return {"kind": "t1", "data": dict(_comment_row(pid=pid, score=score), |
| 432 | replies=replies, depth=depth)} |
| 433 | more = {"kind": "more", "data": {"count": 12, "children": ["x1", "x2"]}} |
| 434 | listing = {"kind": "Listing", |
| 435 | "data": {"children": [node(139, pid="deep", depth=1), more, "junk"]}} |
| 436 | tree = {"data": [node(3, replies=listing, pid="parent"), node(64, pid="top")]} |
| 437 | with mock.patch.object(reddit_arctic.http, "get", return_value=tree): |
| 438 | out = reddit_arctic.fetch_post_comments("abc123", limit=10) |
| 439 | assert [(c["score"], c["depth"]) for c in out] == [(139, 1), (64, 0), (3, 0)] |
| 440 | |
| 441 | def test_depth_comes_from_the_parent(self): |
| 442 | top = dict(_comment_row(pid="a1", score=9), parent_id="t3_abc123") |
| 443 | nested = dict(_comment_row(pid="b2", score=5), parent_id="t1_a1") |
| 444 | with mock.patch.object(reddit_arctic.http, "get", return_value=_tree([top, nested])): |
| 445 | out = reddit_arctic.fetch_post_comments("abc123") |
| 446 | assert [c["depth"] for c in out] == [0, 1] |
| 447 | |
| 448 | def test_request_bounded_by_single_deadline(self): |
| 449 | with mock.patch.object(reddit_arctic.http, "get", return_value=_resp([])) as g, \ |
| 450 | mock.patch.object(reddit_arctic.time, "monotonic", return_value=100.0): |
| 451 | reddit_arctic.fetch_post_comments("abc123") |
| 452 | kwargs = g.call_args.kwargs |
| 453 | assert kwargs["retries"] == 1 |
| 454 | assert kwargs["deadline_monotonic"] == 100.0 + reddit_arctic.TIMEOUT |
| 455 | |
| 456 | def test_caller_deadline_clamps_request(self): |
| 457 | with mock.patch.object(reddit_arctic.http, "get", return_value=_resp([])) as g, \ |
| 458 | mock.patch.object(reddit_arctic.time, "monotonic", return_value=100.0): |
| 459 | reddit_arctic.fetch_post_comments("abc123", deadline=105.0) |
| 460 | assert g.call_args.kwargs["deadline_monotonic"] == 105.0 |
| 461 | assert g.call_args.kwargs["timeout"] == 5.0 |
| 462 | |
| 463 | def test_spent_budget_skips_request(self): |
| 464 | with mock.patch.object(reddit_arctic.http, "get") as g, \ |
| 465 | mock.patch.object(reddit_arctic.time, "monotonic", return_value=100.0): |
| 466 | assert reddit_arctic.fetch_post_comments("abc123", deadline=100.5) == [] |
| 467 | g.assert_not_called() |
| 468 | |
| 469 | def test_strips_t3_prefix_from_post_id(self): |
| 470 | with mock.patch.object(reddit_arctic.http, "get", return_value=_tree([_comment_row()])) as g: |
| 471 | reddit_arctic.fetch_post_comments("t3_abc123") |
| 472 | assert "link_id=t3_abc123" in g.call_args[0][0] |
| 473 | |
| 474 | def test_limit_capped(self): |
| 475 | rows = [_comment_row(score=i) for i in range(5)] |
| 476 | with mock.patch.object(reddit_arctic.http, "get", return_value=_tree(rows)): |
| 477 | out = reddit_arctic.fetch_post_comments("abc123", limit=2) |
| 478 | assert len(out) == 2 |
| 479 | |
| 480 | def test_deleted_and_removed_filtered(self): |
| 481 | rows = [_comment_row(author="[deleted]"), _comment_row(body="[removed]"), |
| 482 | _comment_row(score=7)] |
| 483 | with mock.patch.object(reddit_arctic.http, "get", return_value=_tree(rows)): |
| 484 | out = reddit_arctic.fetch_post_comments("abc123") |
| 485 | assert len(out) == 1 and out[0]["score"] == 7 |
| 486 | |
| 487 | def test_skip_author_filters_before_limit(self): |
| 488 | rows = [_comment_row(author="AutoModerator", score=500), _comment_row(score=7)] |
| 489 | with mock.patch.object(reddit_arctic.http, "get", return_value=_tree(rows)): |
| 490 | out = reddit_arctic.fetch_post_comments( |
| 491 | "abc123", limit=1, skip_author=lambda a: a == "AutoModerator") |
| 492 | assert [c["score"] for c in out] == [7] |
| 493 | |
| 494 | def test_network_error_degrades_to_empty(self): |
| 495 | with mock.patch.object(reddit_arctic.http, "get", side_effect=Exception("boom")): |
| 496 | assert reddit_arctic.fetch_post_comments("abc123") == [] |
| 497 | |
| 498 | def test_rate_limit_response_degrades_to_empty(self): |
| 499 | with mock.patch.object(reddit_arctic.http, "get", |
| 500 | return_value={"error": "Timeout. Maybe slow down a bit"}): |
| 501 | assert reddit_arctic.fetch_post_comments("abc123") == [] |
| 502 | |
| 503 | def test_empty_post_id_returns_empty(self): |
| 504 | with mock.patch.object(reddit_arctic.http, "get") as g: |
| 505 | assert reddit_arctic.fetch_post_comments("") == [] |
| 506 | assert reddit_arctic.fetch_post_comments(None) == [] |
| 507 | g.assert_not_called() |
| 508 |