| 1 | """Tests for scripts/lib/reddit_listing.py — keyless scored listing scrape.""" |
| 2 | |
| 3 | from pathlib import Path |
| 4 | from unittest import mock |
| 5 | |
| 6 | from lib import reddit_listing as rl |
| 7 | |
| 8 | FIXTURE = Path(__file__).resolve().parent.parent / "fixtures" / "reddit_listing_cards_sample.html" |
| 9 | |
| 10 | |
| 11 | def _html(): |
| 12 | return FIXTURE.read_text(encoding="utf-8") |
| 13 | |
| 14 | |
| 15 | class TestParseCards: |
| 16 | """parse_cards reads <shreddit-post> cards into scored post dicts.""" |
| 17 | |
| 18 | def test_parses_five_cards(self): |
| 19 | posts = rl.parse_cards(_html(), query="netherlands") |
| 20 | assert len(posts) == 5 |
| 21 | |
| 22 | def test_real_score_and_count(self): |
| 23 | posts = rl.parse_cards(_html()) |
| 24 | top = posts[0] |
| 25 | assert top["score"] == 52692 # the real upvote count |
| 26 | assert top["engagement"]["score"] == 52692 |
| 27 | assert top["num_comments"] == 1743 |
| 28 | assert top["engagement"]["num_comments"] == 1743 |
| 29 | |
| 30 | def test_normalized_shape(self): |
| 31 | post = rl.parse_cards(_html())[0] |
| 32 | required = {"id", "title", "url", "score", "num_comments", "subreddit", |
| 33 | "created_utc", "author", "selftext", "date", |
| 34 | "engagement", "relevance", "why_relevant", "metadata"} |
| 35 | assert required.issubset(set(post.keys())) |
| 36 | assert post["why_relevant"] == "Reddit listing" |
| 37 | assert post["metadata"]["post_id"] # post id captured for backfill |
| 38 | |
| 39 | def test_fields_populated(self): |
| 40 | post = rl.parse_cards(_html())[0] |
| 41 | assert post["title"] |
| 42 | assert post["author"] == "AdSpecialist6598" |
| 43 | assert post["subreddit"] == "technology" |
| 44 | assert "/comments/" in post["url"] |
| 45 | assert post["date"] and len(post["date"]) == 10 |
| 46 | |
| 47 | def test_empty_html_returns_empty(self): |
| 48 | assert rl.parse_cards("") == [] |
| 49 | assert rl.parse_cards("<div>no cards</div>") == [] |
| 50 | |
| 51 | |
| 52 | class TestListingUrl: |
| 53 | def test_top_includes_timeframe(self): |
| 54 | u = rl._listing_url("technology", "top") |
| 55 | assert "community-more-posts/top/" in u and "name=technology" in u and "t=month" in u |
| 56 | |
| 57 | def test_hot_no_timeframe(self): |
| 58 | u = rl._listing_url("r/technology", "hot") |
| 59 | assert "community-more-posts/hot/" in u and "name=technology" in u and "t=" not in u |
| 60 | assert ".json" not in u |
| 61 | |
| 62 | |
| 63 | class TestFetchListings: |
| 64 | def test_dedupes_across_sorts(self): |
| 65 | with mock.patch.object(rl.http, "get_text", return_value=_html()): |
| 66 | posts = rl.fetch_listings(["technology"], depth="default") |
| 67 | urls = [p["url"] for p in posts] |
| 68 | assert len(urls) == len(set(urls)) # top + hot return same cards -> deduped |
| 69 | |
| 70 | def test_no_subreddits_returns_empty(self): |
| 71 | assert rl.fetch_listings([], depth="default") == [] |
| 72 | |
| 73 | def test_all_fetches_fail_returns_empty(self): |
| 74 | with mock.patch.object(rl.http, "get_text", return_value=None): |
| 75 | assert rl.fetch_listings(["technology"]) == [] |
| 76 | |
| 77 | |
| 78 | class TestScoreIndex: |
| 79 | def test_builds_post_id_to_score_map(self): |
| 80 | with mock.patch.object(rl.http, "get_text", return_value=_html()): |
| 81 | idx = rl.score_index(["technology"], depth="quick") |
| 82 | assert idx # non-empty |
| 83 | first = next(iter(idx.values())) |
| 84 | assert set(first.keys()) == {"score", "num_comments"} |
| 85 | assert any(v["score"] == 52692 for v in idx.values()) |
| 86 | |
| 87 | |
| 88 | class TestFetchDiscoveryListingsFallback: |
| 89 | """fetch_discovery_listings supplements with arctic-shift. Arctic is recency-only |
| 90 | and cannot "recover" failed hot/top/rising lanes — errors are preserved.""" |
| 91 | |
| 92 | def test_arctic_supplement_preserves_shreddit_errors(self): |
| 93 | """Arctic supplements posts but cannot clear shreddit errors (recency-only).""" |
| 94 | arctic_post = { |
| 95 | "id": "", "title": "matcha farm tour", "url": "https://www.reddit.com/r/tea/comments/abc/x/", |
| 96 | "score": 406, "num_comments": 88, "subreddit": "tea", "created_utc": None, |
| 97 | "author": "u", "selftext": "", "date": "2026-07-02", |
| 98 | "engagement": {"score": 406, "num_comments": 88, "upvote_ratio": None}, |
| 99 | "relevance": 0.5, "why_relevant": "Reddit listing (arctic-shift)", |
| 100 | "metadata": {"post_id": "abc"}, |
| 101 | } |
| 102 | with mock.patch.object(rl.http, "get_text", return_value=None), \ |
| 103 | mock.patch("lib.reddit_arctic.fetch_listings", return_value=[arctic_post]) as arctic: |
| 104 | result = rl.fetch_discovery_listings(["tea"], query="matcha", depth="quick") |
| 105 | assert result["items"] == [arctic_post] |
| 106 | # Arctic is recency-only — it can supplement but cannot "recover" a failed |
| 107 | # rising/top lane. Errors for failed shreddit lanes are preserved. |
| 108 | assert result["errors"] # shreddit errors preserved |
| 109 | arctic.assert_called_once() |
| 110 | |
| 111 | def test_errors_preserved_when_both_shreddit_and_arctic_empty(self): |
| 112 | with mock.patch.object(rl.http, "get_text", return_value=None), \ |
| 113 | mock.patch("lib.reddit_arctic.fetch_listings", return_value=[]): |
| 114 | result = rl.fetch_discovery_listings(["tea"], query="matcha", depth="quick") |
| 115 | assert result["items"] == [] |
| 116 | assert result["errors"] # the shreddit failures still surface |
| 117 | |
| 118 | def test_arctic_supplements_shreddit_success(self): |
| 119 | """Arctic is always called to supplement shreddit; results are deduped.""" |
| 120 | arctic_post = { |
| 121 | "id": "", "title": "netherlands tech news extra", "url": "https://www.reddit.com/r/technology/comments/arctic/x/", |
| 122 | "score": 100, "num_comments": 10, "subreddit": "technology", "created_utc": None, |
| 123 | "author": "u", "selftext": "", "date": "2026-07-02", |
| 124 | "engagement": {"score": 100, "num_comments": 10, "upvote_ratio": None}, |
| 125 | "relevance": 0.5, "why_relevant": "Reddit listing (arctic-shift)", |
| 126 | "metadata": {"post_id": "arctic"}, |
| 127 | } |
| 128 | with mock.patch.object(rl.http, "get_text", return_value=_html()), \ |
| 129 | mock.patch("lib.reddit_arctic.fetch_listings", return_value=[arctic_post]) as arctic: |
| 130 | result = rl.fetch_discovery_listings(["technology"], query="netherlands", depth="quick") |
| 131 | # Both shreddit cards and arctic supplement should be in the result. |
| 132 | urls = {item["url"] for item in result["items"]} |
| 133 | assert arctic_post["url"] in urls |
| 134 | assert len(result["items"]) > 1 # shreddit + arctic |
| 135 | assert result["errors"] == [] |
| 136 | arctic.assert_called_once() |
| 137 | |
| 138 | def test_no_subreddits_skips_fallback(self): |
| 139 | with mock.patch("lib.reddit_arctic.fetch_listings") as arctic: |
| 140 | result = rl.fetch_discovery_listings([], query="matcha", depth="quick") |
| 141 | assert result == {"items": [], "errors": []} |
| 142 | arctic.assert_not_called() |
| 143 | |
| 144 | def test_multi_sub_partial_arctic_keeps_all_shreddit_errors(self): |
| 145 | """AE4: arctic supplements but cannot clear shreddit sort-lane errors.""" |
| 146 | # Request tea and coffee; shreddit fails for both, arctic returns tea posts. |
| 147 | arctic_post = { |
| 148 | "id": "", "title": "matcha farm tour", "url": "https://www.reddit.com/r/tea/comments/abc/x/", |
| 149 | "score": 406, "num_comments": 88, "subreddit": "tea", "created_utc": None, |
| 150 | "author": "u", "selftext": "", "date": "2026-07-02", |
| 151 | "engagement": {"score": 406, "num_comments": 88, "upvote_ratio": None}, |
| 152 | "relevance": 0.5, "why_relevant": "Reddit listing (arctic-shift)", |
| 153 | "metadata": {"post_id": "abc"}, |
| 154 | } |
| 155 | with mock.patch.object(rl.http, "get_text", return_value=None), \ |
| 156 | mock.patch("lib.reddit_arctic.fetch_listings", return_value=[arctic_post]): |
| 157 | result = rl.fetch_discovery_listings(["tea", "coffee"], query="matcha", depth="quick") |
| 158 | assert result["items"] == [arctic_post] |
| 159 | # Both subs had shreddit errors. Arctic is recency-only and cannot recover |
| 160 | # failed sort lanes, so ALL errors are preserved. |
| 161 | coffee_errors = [e for e in result["errors"] if "r/coffee" in e.lower()] |
| 162 | assert coffee_errors, "shreddit errors for coffee should be preserved" |
| 163 | tea_errors = [e for e in result["errors"] if "r/tea" in e.lower()] |
| 164 | assert tea_errors, "arctic supplement cannot clear shreddit sort-lane errors" |
| 165 | |
| 166 | def test_arctic_rows_failing_keyword_gate_keep_errors(self): |
| 167 | """AE5: arctic rows that fail the keyword gate do not count as recovery.""" |
| 168 | # Arctic returns a row from tea, but the title doesn't match the query. |
| 169 | offtopic_post = { |
| 170 | "id": "", "title": "best oolong guide", "url": "https://www.reddit.com/r/tea/comments/xyz/x/", |
| 171 | "score": 999, "num_comments": 200, "subreddit": "tea", "created_utc": None, |
| 172 | "author": "u", "selftext": "", "date": "2026-07-02", |
| 173 | "engagement": {"score": 999, "num_comments": 200, "upvote_ratio": None}, |
| 174 | "relevance": 0.0, "why_relevant": "Reddit listing (arctic-shift)", |
| 175 | "metadata": {"post_id": "xyz"}, |
| 176 | } |
| 177 | with mock.patch.object(rl.http, "get_text", return_value=None), \ |
| 178 | mock.patch("lib.reddit_arctic.fetch_listings", return_value=[offtopic_post]): |
| 179 | result = rl.fetch_discovery_listings(["tea"], query="matcha", depth="quick") |
| 180 | # "matcha" is not in "best oolong guide", so the row fails the keyword gate. |
| 181 | # With no surviving rows, arctic didn't effectively recover → errors kept. |
| 182 | assert result["items"] == [] |
| 183 | assert result["errors"], "keyword-rejected rows should not clear errors" |
| 184 | |
| 185 | def test_empty_query_skips_keyword_gate(self): |
| 186 | """Global --discover (empty query) skips the keyword gate entirely.""" |
| 187 | offtopic_post = { |
| 188 | "id": "", "title": "best oolong guide", "url": "https://www.reddit.com/r/tea/comments/xyz/x/", |
| 189 | "score": 999, "num_comments": 200, "subreddit": "tea", "created_utc": None, |
| 190 | "author": "u", "selftext": "", "date": "2026-07-02", |
| 191 | "engagement": {"score": 999, "num_comments": 200, "upvote_ratio": None}, |
| 192 | "relevance": 0.0, "why_relevant": "Reddit listing (arctic-shift)", |
| 193 | "metadata": {"post_id": "xyz"}, |
| 194 | } |
| 195 | with mock.patch.object(rl.http, "get_text", return_value=None), \ |
| 196 | mock.patch("lib.reddit_arctic.fetch_listings", return_value=[offtopic_post]): |
| 197 | # Empty query = global discover, no keyword gate. |
| 198 | result = rl.fetch_discovery_listings(["tea"], query="", depth="quick") |
| 199 | # No keyword gate → post survives. But arctic is recency-only, so shreddit |
| 200 | # errors for failed sort lanes are preserved. |
| 201 | assert result["items"] == [offtopic_post] |
| 202 | assert result["errors"] # shreddit errors preserved despite arctic supplement |
| 203 | |
| 204 | |
| 205 | class TestSortLaneErrorPreservation: |
| 206 | """Verify errors are cleared per (sub, sort) pair, not per subreddit.""" |
| 207 | |
| 208 | def test_shreddit_partial_success_keeps_failed_sort_errors(self): |
| 209 | """One sort succeeds, another fails → only the failed lane's error is kept. |
| 210 | |
| 211 | This is the key test: shreddit rising succeeds for a sub, shreddit top fails, |
| 212 | arctic supplements with recency posts. The failed top error is preserved |
| 213 | because arctic is recency-only and cannot claim to have recovered a "top" lane. |
| 214 | """ |
| 215 | # Shreddit returns posts for "rising" but None for "top". |
| 216 | def shreddit_response(url, *args, **kwargs): |
| 217 | if "rising" in url: |
| 218 | return _html() # success for rising |
| 219 | return None # fail for top |
| 220 | |
| 221 | arctic_post = { |
| 222 | "id": "", "title": "extra from arctic", "url": "https://www.reddit.com/r/technology/comments/arctic/x/", |
| 223 | "score": 100, "num_comments": 10, "subreddit": "technology", "created_utc": None, |
| 224 | "author": "u", "selftext": "", "date": "2026-07-02", |
| 225 | "engagement": {"score": 100, "num_comments": 10, "upvote_ratio": None}, |
| 226 | "relevance": 0.5, "why_relevant": "Reddit listing (arctic-shift)", |
| 227 | "metadata": {"post_id": "arctic"}, |
| 228 | } |
| 229 | with mock.patch.object(rl.http, "get_text", side_effect=shreddit_response), \ |
| 230 | mock.patch("lib.reddit_arctic.fetch_listings", return_value=[arctic_post]): |
| 231 | result = rl.fetch_discovery_listings(["technology"], query="netherlands", depth="quick") |
| 232 | |
| 233 | # Shreddit rising succeeded → no error for rising. |
| 234 | # Shreddit top failed → error for top is preserved. |
| 235 | # Arctic supplement cannot clear shreddit errors (recency-only). |
| 236 | rising_errors = [e for e in result["errors"] if "rising" in e.lower()] |
| 237 | top_errors = [e for e in result["errors"] if " top:" in e.lower()] |
| 238 | assert not rising_errors, "successful rising lane should have no error" |
| 239 | assert top_errors, "failed top lane error should be preserved" |
| 240 | # Posts from both shreddit and arctic should be in the result. |
| 241 | assert len(result["items"]) > 1 |
| 242 | |
| 243 | def test_arctic_does_not_recover_shreddit_sort_lanes(self): |
| 244 | """Arctic supplement adds posts but cannot clear shreddit sort-lane errors.""" |
| 245 | arctic_post = { |
| 246 | "id": "", "title": "foobar topic", "url": "https://www.reddit.com/r/foobar/comments/abc/x/", |
| 247 | "score": 500, "num_comments": 50, "subreddit": "foobar", "created_utc": None, |
| 248 | "author": "u", "selftext": "", "date": "2026-07-02", |
| 249 | "engagement": {"score": 500, "num_comments": 50, "upvote_ratio": None}, |
| 250 | "relevance": 0.5, "why_relevant": "Reddit listing (arctic-shift)", |
| 251 | "metadata": {"post_id": "abc"}, |
| 252 | } |
| 253 | # Shreddit fails for both subs; arctic supplements for foobar only. |
| 254 | with mock.patch.object(rl.http, "get_text", return_value=None), \ |
| 255 | mock.patch("lib.reddit_arctic.fetch_listings", return_value=[arctic_post]): |
| 256 | result = rl.fetch_discovery_listings(["foo", "foobar"], query="topic", depth="quick") |
| 257 | # Arctic is recency-only — it cannot recover failed rising/top lanes. |
| 258 | # ALL shreddit errors should be preserved. |
| 259 | assert result["items"] == [arctic_post] |
| 260 | foo_errors = [e for e in result["errors"] if e.lower().startswith("r/foo ")] |
| 261 | assert foo_errors, "shreddit errors for r/foo should be preserved" |
| 262 | foobar_errors = [e for e in result["errors"] if e.lower().startswith("r/foobar ")] |
| 263 | assert foobar_errors, "arctic cannot clear shreddit errors — foobar errors preserved" |
| 264 | |
| 265 | |
| 266 | class TestMatchesDiscoveryDomainParity: |
| 267 | """Verify the copied _matches_discovery_domain stays in sync with pipeline.py.""" |
| 268 | |
| 269 | def test_parity_with_pipeline_implementation(self): |
| 270 | # Import both implementations and verify they agree on test cases. |
| 271 | from lib import pipeline |
| 272 | test_cases = [ |
| 273 | ("matcha", "matcha farm tour", True), |
| 274 | ("matcha", "best oolong guide", False), |
| 275 | ("AI", "New AI model release", True), # "ai" is generic but no anchors → use domain_terms |
| 276 | ("OpenClaw", "My OpenClaw setup", True), |
| 277 | ("OpenClaw", "Generic post about nothing", False), |
| 278 | ("Stripe payments", "Stripe is great", True), |
| 279 | ("bias", "cognitive bias research", True), # no naive stem corruption |
| 280 | ] |
| 281 | for domain, text, expected in test_cases: |
| 282 | pipeline_result = pipeline._matches_discovery_domain(domain, text) |
| 283 | listing_result = rl._matches_discovery_domain(domain, text) |
| 284 | assert pipeline_result == listing_result, ( |
| 285 | f"Parity mismatch for ({domain!r}, {text!r}): " |
| 286 | f"pipeline={pipeline_result}, listing={listing_result}" |
| 287 | ) |
| 288 | assert pipeline_result == expected, ( |
| 289 | f"Expected {expected} for ({domain!r}, {text!r}), got {pipeline_result}" |
| 290 | ) |
| 291 |