| 1 | """Offline tests for the scheduled Reddit canary (scripts/reddit_canary.py).""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import json |
| 6 | import os |
| 7 | from datetime import datetime, timedelta, timezone |
| 8 | from pathlib import Path |
| 9 | from types import SimpleNamespace |
| 10 | |
| 11 | import pytest |
| 12 | import yaml |
| 13 | |
| 14 | import reddit_canary as canary |
| 15 | from lib import env, reddit_arctic |
| 16 | |
| 17 | ROOT = Path(__file__).resolve().parents[1] |
| 18 | WORKFLOW = ROOT / ".github" / "workflows" / "reddit-canary.yml" |
| 19 | FIXTURES = ROOT / "fixtures" |
| 20 | NOW = datetime(2026, 11, 15, 13, 30, tzinfo=timezone.utc) |
| 21 | |
| 22 | BRAVE_PAGE = (FIXTURES / "brave_reddit_serp.html").read_text(encoding="utf-8") |
| 23 | ARCTIC_OK = json.dumps({"data": [ |
| 24 | {"id": pid, "title": f"Known thread {pid}", "subreddit": "test", "score": 10, |
| 25 | "num_comments": 2, "created_utc": 1740800000, "permalink": f"/r/test/comments/{pid}/x/"} |
| 26 | for pid in canary.KNOWN_THREAD_IDS |
| 27 | ]}) |
| 28 | DDG_NO_RESULTS = ( |
| 29 | '<div class="no-results__container result__title"><span class="no-results">' |
| 30 | '<div class="no-results__message"><h1>No more results found</h1></div></span></div>' |
| 31 | ) |
| 32 | |
| 33 | |
| 34 | def _fetcher(pages: dict[str, tuple]): |
| 35 | """A fetch stub: the first key that is a prefix of the URL answers.""" |
| 36 | calls: list[str] = [] |
| 37 | |
| 38 | def fetch(url: str, accept: str = "text/html"): |
| 39 | calls.append(url) |
| 40 | for prefix, answer in pages.items(): |
| 41 | if url.startswith(prefix): |
| 42 | return answer |
| 43 | raise AssertionError(f"unexpected fetch {url}") |
| 44 | |
| 45 | fetch.calls = calls |
| 46 | return fetch |
| 47 | |
| 48 | |
| 49 | def _hydrate_ok(refs, **_kwargs): |
| 50 | items = [{"engagement_source": "arctic", "top_comments": [{"id": "c1"}]} for _ in refs] |
| 51 | return SimpleNamespace(items=items, arctic_state="ok", detail=f"web+arctic served {len(items)}") |
| 52 | |
| 53 | |
| 54 | def _run(pages, tmp_path, *, now=NOW, hydrate=_hydrate_ok, state_name="state.json"): |
| 55 | return canary.run( |
| 56 | fetch=_fetcher(pages), hydrate=hydrate, topics=("Claude Code",), |
| 57 | state_file=tmp_path / state_name, now=now, sleep=lambda _s: None, |
| 58 | ) |
| 59 | |
| 60 | |
| 61 | BRAVE = "https://search.brave.com/" |
| 62 | DDG = "https://html.duckduckgo.com/" |
| 63 | STARTPAGE = "https://www.startpage.com/" |
| 64 | ARCTIC = reddit_arctic.API |
| 65 | |
| 66 | |
| 67 | def _states(report) -> dict[str, str]: |
| 68 | return {check["name"]: check["state"] for check in report["checks"]} |
| 69 | |
| 70 | |
| 71 | # --- workflow static checks ------------------------------------------------- |
| 72 | |
| 73 | |
| 74 | def test_workflow_never_runs_on_pull_requests_and_is_least_privilege(): |
| 75 | workflow = yaml.safe_load(WORKFLOW.read_text(encoding="utf-8")) |
| 76 | triggers = workflow.get("on", workflow.get(True)) |
| 77 | assert set(triggers) == {"schedule", "workflow_dispatch"} |
| 78 | assert "pull_request" not in triggers and "pull_request_target" not in triggers |
| 79 | assert triggers["schedule"][0]["cron"] |
| 80 | # Top level grants nothing; the one job reads repository contents only. |
| 81 | assert workflow["permissions"] in ({}, "read-all") |
| 82 | for job in workflow["jobs"].values(): |
| 83 | assert job.get("permissions", {}) in ({}, {"contents": "read"}) |
| 84 | assert job.get("timeout-minutes") |
| 85 | |
| 86 | |
| 87 | def test_workflow_pins_every_action_by_full_sha_and_runs_the_canary(): |
| 88 | workflow = yaml.safe_load(WORKFLOW.read_text(encoding="utf-8")) |
| 89 | steps = [step for job in workflow["jobs"].values() for step in job["steps"]] |
| 90 | uses = [step["uses"] for step in steps if "uses" in step] |
| 91 | assert uses |
| 92 | for ref in uses: |
| 93 | _, _, sha = ref.partition("@") |
| 94 | assert len(sha) == 40 and all(c in "0123456789abcdef" for c in sha), ref |
| 95 | checkout = next(step for step in steps if step.get("uses", "").startswith("actions/checkout@")) |
| 96 | assert checkout["with"]["persist-credentials"] is False |
| 97 | runs = " ".join(step.get("run", "") for step in steps) |
| 98 | assert "reddit_canary.py" in runs and "--state-file" in runs |
| 99 | # The state survives a failed run so the two-day rule can see it. |
| 100 | save = next(step for step in steps if step.get("uses", "").startswith("actions/cache/save@")) |
| 101 | assert save["if"] == "always()" |
| 102 | |
| 103 | |
| 104 | def test_canary_is_excluded_from_install_time_scans(): |
| 105 | entries = (ROOT / "skills" / "last30days" / ".skillignore").read_text(encoding="utf-8").split() |
| 106 | assert "scripts/reddit_canary.py" in entries |
| 107 | |
| 108 | |
| 109 | # --- classification --------------------------------------------------------- |
| 110 | |
| 111 | |
| 112 | @pytest.mark.parametrize("status,text,threads,parsed,expected", [ |
| 113 | (200, "<html>results</html>", 3, 3, canary.OK), |
| 114 | (202, "", 0, 0, canary.CHALLENGED), |
| 115 | (429, "", 0, 0, canary.CHALLENGED), |
| 116 | (200, "<div>please solve this CAPTCHA</div>", 0, 0, canary.CHALLENGED), |
| 117 | (200, '<div class="anomaly-modal">', 0, 0, canary.CHALLENGED), |
| 118 | (200, "<html>new markup</html>", 0, 0, canary.PARSER_BROKE), |
| 119 | (200, DDG_NO_RESULTS, 0, 0, canary.DOWN), |
| 120 | (200, "<html>other sites</html>", 0, 4, canary.DOWN), |
| 121 | (403, "Forbidden", 0, 0, canary.DOWN), |
| 122 | (503, "", 0, 0, canary.DOWN), |
| 123 | (None, "", 0, 0, canary.DOWN), |
| 124 | ]) |
| 125 | def test_classify_page(status, text, threads, parsed, expected): |
| 126 | assert canary.classify_page("ddg", status, text, threads, parsed) == expected |
| 127 | |
| 128 | |
| 129 | def test_startpage_challenge_marker_is_reused_from_the_engine(): |
| 130 | page = '<script>var x = {"challenge":{"issuedAt":1}}</script>' |
| 131 | assert canary.classify_page("startpage", 200, page, 0, 0) == canary.CHALLENGED |
| 132 | |
| 133 | |
| 134 | def test_healthy_run_passes_and_hydrates_discovered_threads(tmp_path): |
| 135 | code, report = _run({ |
| 136 | BRAVE: (200, BRAVE_PAGE), DDG: (200, DDG_NO_RESULTS), STARTPAGE: (429, ""), ARCTIC: (200, ARCTIC_OK), |
| 137 | }, tmp_path) |
| 138 | states = _states(report) |
| 139 | assert code == 0, report["failures"] |
| 140 | assert states["brave: Claude Code"] == canary.OK |
| 141 | assert states["ddg: Claude Code"] == canary.DOWN |
| 142 | assert states["startpage: Claude Code"] == canary.CHALLENGED |
| 143 | assert states["hydrate: Claude Code"] == canary.OK |
| 144 | assert states["arctic: known ids"] == canary.OK |
| 145 | assert report["no_rung_served"] is False |
| 146 | assert "PASS" in canary.render(report) |
| 147 | |
| 148 | |
| 149 | def test_stubbed_200_with_zero_parseable_results_fails_as_parser_broke(tmp_path): |
| 150 | code, report = _run({ |
| 151 | BRAVE: (200, "<html><body>a redesigned results page</body></html>"), |
| 152 | DDG: (200, DDG_NO_RESULTS), STARTPAGE: (429, ""), ARCTIC: (200, ARCTIC_OK), |
| 153 | }, tmp_path) |
| 154 | assert code != 0 |
| 155 | assert _states(report)["brave: Claude Code"] == canary.PARSER_BROKE |
| 156 | assert any("parser-broke" in reason for reason in report["failures"]) |
| 157 | |
| 158 | |
| 159 | def test_stubbed_arctic_503_on_fixed_ids_fails_as_down(tmp_path): |
| 160 | code, report = _run({ |
| 161 | BRAVE: (200, BRAVE_PAGE), DDG: (202, ""), STARTPAGE: (429, ""), ARCTIC: (503, ""), |
| 162 | }, tmp_path) |
| 163 | assert code != 0 |
| 164 | assert _states(report)["arctic: known ids"] == canary.DOWN |
| 165 | assert any("Arctic hydration is down" in reason for reason in report["failures"]) |
| 166 | |
| 167 | |
| 168 | def test_arctic_answer_without_known_threads_is_parser_broke(tmp_path): |
| 169 | code, report = _run({ |
| 170 | BRAVE: (200, BRAVE_PAGE), DDG: (202, ""), STARTPAGE: (429, ""), ARCTIC: (200, '{"data": []}'), |
| 171 | }, tmp_path) |
| 172 | assert code != 0 |
| 173 | assert _states(report)["arctic: known ids"] == canary.PARSER_BROKE |
| 174 | |
| 175 | |
| 176 | def test_arctic_slow_down_is_challenged_not_down(tmp_path): |
| 177 | code, report = _run({ |
| 178 | BRAVE: (200, BRAVE_PAGE), DDG: (202, ""), STARTPAGE: (429, ""), ARCTIC: (422, "slow down"), |
| 179 | }, tmp_path) |
| 180 | assert code == 0 |
| 181 | assert _states(report)["arctic: known ids"] == canary.CHALLENGED |
| 182 | |
| 183 | |
| 184 | def test_topic_hydration_down_fails(tmp_path): |
| 185 | def hydrate_down(refs, **_kwargs): |
| 186 | return SimpleNamespace(items=[], arctic_state="down", detail="web served 3; arctic down") |
| 187 | |
| 188 | code, report = _run({ |
| 189 | BRAVE: (200, BRAVE_PAGE), DDG: (202, ""), STARTPAGE: (429, ""), ARCTIC: (200, ARCTIC_OK), |
| 190 | }, tmp_path, hydrate=hydrate_down) |
| 191 | assert code != 0 |
| 192 | assert _states(report)["hydrate: Claude Code"] == canary.DOWN |
| 193 | |
| 194 | |
| 195 | def test_comment_tree_outage_fails_even_when_post_lookups_work(tmp_path): |
| 196 | def hydrate_no_comments(refs, **_kwargs): |
| 197 | items = [{"engagement_source": "arctic", "top_comments": []} for _ in refs] |
| 198 | return SimpleNamespace(items=items, arctic_state="ok", detail=f"web+arctic served {len(items)}", |
| 199 | comment_fills=0, comment_failures=3) |
| 200 | |
| 201 | code, report = _run({ |
| 202 | BRAVE: (200, BRAVE_PAGE), DDG: (202, ""), STARTPAGE: (429, ""), ARCTIC: (200, ARCTIC_OK), |
| 203 | }, tmp_path, hydrate=hydrate_no_comments) |
| 204 | assert code != 0 |
| 205 | assert _states(report)["hydrate: Claude Code"] == canary.DOWN |
| 206 | |
| 207 | |
| 208 | def test_comment_tree_slow_downs_are_challenged_not_down(tmp_path): |
| 209 | def hydrate_throttled(refs, **_kwargs): |
| 210 | items = [{"engagement_source": "arctic", "top_comments": []} for _ in refs] |
| 211 | return SimpleNamespace(items=items, arctic_state="ok", detail=f"web+arctic served {len(items)}", |
| 212 | comment_fills=0, comment_failures=2, comment_throttles=2) |
| 213 | |
| 214 | code, report = _run({ |
| 215 | BRAVE: (200, BRAVE_PAGE), DDG: (202, ""), STARTPAGE: (429, ""), ARCTIC: (200, ARCTIC_OK), |
| 216 | }, tmp_path, hydrate=hydrate_throttled) |
| 217 | assert _states(report)["hydrate: Claude Code"] == canary.CHALLENGED |
| 218 | |
| 219 | |
| 220 | def test_empty_comment_trees_are_not_an_outage(tmp_path): |
| 221 | def hydrate_empty_trees(refs, **_kwargs): |
| 222 | items = [{"engagement_source": "arctic", "top_comments": []} for _ in refs] |
| 223 | return SimpleNamespace(items=items, arctic_state="ok", detail=f"web+arctic served {len(items)}", |
| 224 | comment_fills=0, comment_failures=0) |
| 225 | |
| 226 | code, report = _run({ |
| 227 | BRAVE: (200, BRAVE_PAGE), DDG: (202, ""), STARTPAGE: (429, ""), ARCTIC: (200, ARCTIC_OK), |
| 228 | }, tmp_path, hydrate=hydrate_empty_trees) |
| 229 | assert code == 0, report["failures"] |
| 230 | assert _states(report)["hydrate: Claude Code"] == canary.OK |
| 231 | |
| 232 | |
| 233 | def test_stubbed_202_is_challenged_and_exits_zero_on_day_one(tmp_path): |
| 234 | pages = {BRAVE: (202, ""), DDG: (202, ""), STARTPAGE: (202, ""), ARCTIC: (200, ARCTIC_OK)} |
| 235 | code, report = _run(pages, tmp_path) |
| 236 | assert code == 0, report["failures"] |
| 237 | assert {_states(report)[f"{rung}: Claude Code"] for rung in canary.RUNGS} == {canary.CHALLENGED} |
| 238 | assert report["no_rung_served"] is True |
| 239 | # No thread was discovered, so there is nothing to hydrate per topic; the |
| 240 | # fixed-id check still covers the hydrator. |
| 241 | assert "hydrate: Claude Code" not in _states(report) |
| 242 | assert _states(report)["arctic: known ids"] == canary.OK |
| 243 | |
| 244 | # A same-day rerun does not count as a second day. |
| 245 | code, report = _run(pages, tmp_path, now=NOW + timedelta(hours=3)) |
| 246 | assert code == 0 |
| 247 | assert report["no_serve_since"] == NOW.isoformat(timespec="seconds") |
| 248 | |
| 249 | # The next day's run, still challenged everywhere, fails. |
| 250 | code, report = _run(pages, tmp_path, now=NOW + timedelta(days=1)) |
| 251 | assert code != 0 |
| 252 | assert any("two days running" in reason for reason in report["failures"]) |
| 253 | |
| 254 | |
| 255 | def test_a_served_day_resets_the_challenged_streak(tmp_path): |
| 256 | challenged = {BRAVE: (202, ""), DDG: (202, ""), STARTPAGE: (202, ""), ARCTIC: (200, ARCTIC_OK)} |
| 257 | healthy = {**challenged, BRAVE: (200, BRAVE_PAGE)} |
| 258 | assert _run(challenged, tmp_path)[0] == 0 |
| 259 | code, report = _run(healthy, tmp_path, now=NOW + timedelta(days=1)) |
| 260 | assert code == 0 and report["no_serve_since"] is None |
| 261 | assert _run(challenged, tmp_path, now=NOW + timedelta(days=2))[0] == 0 |
| 262 | |
| 263 | |
| 264 | def test_a_stale_previous_state_starts_a_new_streak(tmp_path): |
| 265 | challenged = {BRAVE: (202, ""), DDG: (202, ""), STARTPAGE: (202, ""), ARCTIC: (200, ARCTIC_OK)} |
| 266 | assert _run(challenged, tmp_path)[0] == 0 |
| 267 | code, _report = _run(challenged, tmp_path, now=NOW + timedelta(days=4)) |
| 268 | assert code == 0 |
| 269 | |
| 270 | |
| 271 | def test_every_rung_down_fails_on_day_one(tmp_path): |
| 272 | code, report = _run({ |
| 273 | BRAVE: (None, ""), DDG: (403, ""), STARTPAGE: (500, ""), ARCTIC: (200, ARCTIC_OK), |
| 274 | }, tmp_path) |
| 275 | assert code != 0 |
| 276 | assert "every discovery rung is down" in report["failures"] |
| 277 | |
| 278 | |
| 279 | def test_state_file_round_trips_and_unreadable_state_is_ignored(tmp_path): |
| 280 | state = tmp_path / "state.json" |
| 281 | state.write_text("{not json", encoding="utf-8") |
| 282 | code, report = _run({ |
| 283 | BRAVE: (202, ""), DDG: (202, ""), STARTPAGE: (202, ""), ARCTIC: (200, ARCTIC_OK), |
| 284 | }, tmp_path) |
| 285 | assert code == 0 |
| 286 | saved = json.loads(state.read_text(encoding="utf-8")) |
| 287 | assert saved["no_rung_served"] is True |
| 288 | assert saved["checks"] == report["checks"] |
| 289 | |
| 290 | |
| 291 | def test_known_ids_are_asked_in_one_archive_request(tmp_path): |
| 292 | fetch = _fetcher({BRAVE: (202, ""), DDG: (202, ""), STARTPAGE: (202, ""), ARCTIC: (200, ARCTIC_OK)}) |
| 293 | canary.run(fetch=fetch, hydrate=_hydrate_ok, topics=("Claude Code",), state_file=None, |
| 294 | now=NOW, sleep=lambda _s: None) |
| 295 | arctic_calls = [url for url in fetch.calls if url.startswith(ARCTIC)] |
| 296 | assert arctic_calls == [f"{ARCTIC}?ids={','.join(canary.KNOWN_THREAD_IDS)}"] |
| 297 | |
| 298 | |
| 299 | def test_rung_queries_are_the_floor_query_month_filtered(tmp_path): |
| 300 | fetch = _fetcher({BRAVE: (202, ""), DDG: (202, ""), STARTPAGE: (202, ""), ARCTIC: (200, ARCTIC_OK)}) |
| 301 | canary.run(fetch=fetch, hydrate=_hydrate_ok, topics=("Claude Code",), state_file=None, |
| 302 | now=NOW, sleep=lambda _s: None) |
| 303 | rung_calls = [url for url in fetch.calls if not url.startswith(ARCTIC)] |
| 304 | assert len(rung_calls) == len(canary.RUNGS) |
| 305 | assert all("site%3Areddit.com+Claude+Code" in url for url in rung_calls) |
| 306 | assert "tf=pm" in rung_calls[0] and "df=m" in rung_calls[1] and "with_date=m" in rung_calls[2] |
| 307 | |
| 308 | |
| 309 | def test_clean_environment_drops_keys_session_and_config(monkeypatch): |
| 310 | monkeypatch.setenv("SCRAPECREATORS_API_KEY", "dummy-sc-key") |
| 311 | monkeypatch.setenv(env.REDDIT_SESSION_COOKIE_VAR, "dummy-cookie") |
| 312 | monkeypatch.setenv("REDDIT_BROWSER_CONSENT", "true") |
| 313 | for key in canary.CLEAN_ENV: |
| 314 | monkeypatch.setenv(key, os.environ.get(key, "placeholder")) |
| 315 | monkeypatch.setattr(env, "CONFIG_DIR", Path("/tmp/should-not-be-used")) |
| 316 | monkeypatch.setattr(env, "CONFIG_FILE", Path("/tmp/should-not-be-used/.env")) |
| 317 | canary.clean_environment() |
| 318 | assert "SCRAPECREATORS_API_KEY" not in os.environ |
| 319 | assert env.REDDIT_SESSION_COOKIE_VAR not in os.environ |
| 320 | assert os.environ["REDDIT_BROWSER_CONSENT"] == "false" |
| 321 | assert os.environ["FROM_BROWSER"] == "off" |
| 322 | assert env.CONFIG_DIR is None and env.CONFIG_FILE is None |
| 323 | allowed, _why = env.reddit_session_gate(env.get_config()) |
| 324 | assert allowed is False |
| 325 | |
| 326 | |
| 327 | def test_main_writes_report_and_step_summary(tmp_path, monkeypatch): |
| 328 | summary = tmp_path / "summary.md" |
| 329 | monkeypatch.setenv("GITHUB_STEP_SUMMARY", str(summary)) |
| 330 | monkeypatch.setattr(canary, "clean_environment", lambda: None) |
| 331 | monkeypatch.setattr(canary, "http_fetch", _fetcher({ |
| 332 | BRAVE: (202, ""), DDG: (202, ""), STARTPAGE: (202, ""), ARCTIC: (200, ARCTIC_OK), |
| 333 | })) |
| 334 | monkeypatch.setattr(canary, "TOPICS", ("Claude Code",)) |
| 335 | monkeypatch.setattr(canary, "PAUSE_SECONDS", 0) |
| 336 | monkeypatch.setattr(canary.time, "sleep", lambda _s: None) |
| 337 | # run() binds its defaults at definition time; route main through stubs. |
| 338 | real_run = canary.run |
| 339 | monkeypatch.setattr(canary, "run", lambda **kw: real_run( |
| 340 | fetch=canary.http_fetch, hydrate=_hydrate_ok, topics=canary.TOPICS, |
| 341 | now=NOW, sleep=lambda _s: None, **kw, |
| 342 | )) |
| 343 | report_path = tmp_path / "out" / "report.json" |
| 344 | code = canary.main(["--state-file", str(tmp_path / "state.json"), "--report", str(report_path)]) |
| 345 | assert code == 0 |
| 346 | assert json.loads(report_path.read_text())["checks"] |
| 347 | assert "| arctic: known ids | ok |" in summary.read_text() |
| 348 |