| 1 | """Offline tests for evaluate_search_quality.py --reddit-coverage.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import contextlib |
| 6 | import io |
| 7 | import json |
| 8 | import sys |
| 9 | from pathlib import Path |
| 10 | from unittest import mock |
| 11 | |
| 12 | import evaluate_search_quality as evaluator |
| 13 | |
| 14 | ROOT = Path(__file__).resolve().parents[1] |
| 15 | TOPICS_FIXTURE = ROOT / "fixtures" / "reddit_coverage_topics.json" |
| 16 | |
| 17 | |
| 18 | def _thread(title: str, *, comments: int = 0, source: str = "arctic") -> dict: |
| 19 | return { |
| 20 | "item_id": title, "source": "reddit", "title": title, "url": f"https://www.reddit.com/r/t/comments/{abs(hash(title)) % 99999}/", |
| 21 | "metadata": {"top_comments": [{"id": f"c{i}"} for i in range(comments)], "engagement_source": source}, |
| 22 | } |
| 23 | |
| 24 | |
| 25 | def _report(threads: list[dict], detail: str = "web+arctic served 3") -> dict: |
| 26 | return { |
| 27 | "topic": "x", |
| 28 | "ranked_candidates": [], |
| 29 | "items_by_source": {"reddit": threads}, |
| 30 | "source_status": {"reddit": {"source": "reddit", "state": "ok", "detail": detail}}, |
| 31 | } |
| 32 | |
| 33 | |
| 34 | def _v2_report(threads: list[dict]) -> dict: |
| 35 | """A pre-v3 engine's report: a top-level reddit list with no topic bar.""" |
| 36 | return {"reddit": [{"title": t["title"], "url": t["url"], "top_comments": [{"id": "c"}]} for t in threads]} |
| 37 | |
| 38 | |
| 39 | def _in_process_judge(topic: str, titles: list[str]) -> list[bool]: |
| 40 | from lib import rerank |
| 41 | |
| 42 | entity = rerank._primary_entity(topic).lower() |
| 43 | return [rerank._entity_grounded(title, entity) if entity else True for title in titles] |
| 44 | |
| 45 | |
| 46 | def test_fixture_has_about_twelve_topics_with_the_required_kinds(): |
| 47 | rows = evaluator.load_reddit_coverage_topics(TOPICS_FIXTURE) |
| 48 | assert 10 <= len(rows) <= 14 |
| 49 | kinds = [row["kind"] for row in rows] |
| 50 | assert kinds.count("no_coverage") == 1 |
| 51 | assert "homonym" in kinds and "breaking" in kinds |
| 52 | no_coverage = next(row for row in rows if row["kind"] == "no_coverage") |
| 53 | assert no_coverage["expect_coverage"] is False |
| 54 | assert all(row["expect_coverage"] for row in rows if row["kind"] != "no_coverage") |
| 55 | assert len({row["topic"].lower() for row in rows}) == len(rows) |
| 56 | |
| 57 | |
| 58 | def test_coverage_env_never_loads_config_or_keychain(monkeypatch): |
| 59 | with mock.patch.object(evaluator.envlib, "get_config", side_effect=AssertionError("config loaded")): |
| 60 | run_env = evaluator.create_reddit_coverage_env() |
| 61 | assert run_env["LAST30DAYS_SKIP_KEYCHAIN"] == "1" |
| 62 | |
| 63 | |
| 64 | def test_coverage_env_has_no_sc_key_no_session_and_no_config(monkeypatch): |
| 65 | monkeypatch.setenv("SCRAPECREATORS_API_KEY", "dummy-sc-key") |
| 66 | monkeypatch.setenv("REDDIT_SESSION_COOKIE", "dummy-cookie") |
| 67 | monkeypatch.setenv("XAI_API_KEY", "dummy-xai-key") |
| 68 | with mock.patch.object(evaluator.envlib, "get_config", return_value={ |
| 69 | "SCRAPECREATORS_API_KEY": "dummy-config-sc-key", "REDDIT_BROWSER_CONSENT": "true", |
| 70 | }): |
| 71 | run_env = evaluator.create_reddit_coverage_env() |
| 72 | # The default eval env still forwards the key; only coverage drops it. |
| 73 | assert evaluator.create_eval_env().get("SCRAPECREATORS_API_KEY") |
| 74 | assert "SCRAPECREATORS_API_KEY" not in run_env |
| 75 | assert "REDDIT_SESSION_COOKIE" not in run_env |
| 76 | assert run_env["REDDIT_BROWSER_CONSENT"] == "false" |
| 77 | assert run_env["FROM_BROWSER"] == "off" |
| 78 | assert run_env["LAST30DAYS_SKIP_KEYCHAIN"] == "1" |
| 79 | assert run_env["LAST30DAYS_CONFIG_DIR"] == "" |
| 80 | assert run_env["XAI_API_KEY"] == "dummy-xai-key" |
| 81 | |
| 82 | |
| 83 | def test_coverage_env_closes_the_reddit_session_gate(monkeypatch): |
| 84 | from lib import env |
| 85 | |
| 86 | run_env = evaluator.create_reddit_coverage_env() |
| 87 | config = {key: run_env[key] for key in ("REDDIT_BROWSER_CONSENT", "FROM_BROWSER")} |
| 88 | config["_BROWSER_COOKIE_MODE"] = "read" |
| 89 | allowed, why = env.reddit_session_gate(config) |
| 90 | assert allowed is False and "FROM_BROWSER=off" in why |
| 91 | |
| 92 | |
| 93 | def test_same_off_topic_thread_is_off_topic_for_baseline_and_candidate(): |
| 94 | off_topic = _thread("Best pizza in Chicago?", comments=4) |
| 95 | on_topic = _thread("Claude Code hooks are underrated", comments=2) |
| 96 | candidate = evaluator.summarize_reddit_coverage(_report([on_topic, off_topic]), "Claude Code", _in_process_judge) |
| 97 | baseline = evaluator.summarize_reddit_coverage(_v2_report([on_topic, off_topic]), "Claude Code", _in_process_judge) |
| 98 | assert candidate["threads"] == baseline["threads"] == 2 |
| 99 | assert candidate["on_topic"] == baseline["on_topic"] == 1 |
| 100 | # Comments are counted on on-topic threads only. |
| 101 | assert candidate["comments"] == 2 |
| 102 | |
| 103 | |
| 104 | def test_title_judge_runs_the_candidate_trees_rerank_check(): |
| 105 | judge = evaluator.make_title_judge(ROOT) |
| 106 | titles = ["Claude Code hooks are underrated", "Best pizza in Chicago?"] |
| 107 | assert judge("Claude Code", titles) == _in_process_judge("Claude Code", titles) == [True, False] |
| 108 | assert judge("Claude Code", []) == [] |
| 109 | |
| 110 | |
| 111 | def test_summary_reports_served_path_and_pending_share(): |
| 112 | threads = [ |
| 113 | _thread("Steam Deck OLED battery", comments=3, source="arctic-pending"), |
| 114 | _thread("Steam Deck dock review", comments=1, source="arctic"), |
| 115 | _thread("Unrelated", source="arctic-pending"), |
| 116 | ] |
| 117 | summary = evaluator.summarize_reddit_coverage(_report(threads, "web+arctic served 3"), "Steam Deck", _in_process_judge) |
| 118 | assert summary == { |
| 119 | "threads": 3, "on_topic": 2, "pending_share": 0.5, "comments": 4, |
| 120 | "served_path": "web+arctic served 3", |
| 121 | } |
| 122 | assert evaluator.reddit_served_path({}) == "-" |
| 123 | assert evaluator.reddit_served_path({"source_status": {"reddit": {"state": "no-results"}}}) == "no-results" |
| 124 | |
| 125 | |
| 126 | def _run_main(tmp_path, topics, reports, *, baseline="WORKTREE"): |
| 127 | topics_file = tmp_path / "topics.json" |
| 128 | topics_file.write_text(json.dumps(topics)) |
| 129 | argv = [ |
| 130 | "evaluate_search_quality.py", "--reddit-coverage", f"--baseline={baseline}", "--candidate=WORKTREE", |
| 131 | "--topics-file", str(topics_file), "--output-dir", str(tmp_path / "out"), |
| 132 | ] |
| 133 | calls = [] |
| 134 | |
| 135 | def fake_run(repo_dir, topic, **kwargs): |
| 136 | calls.append({"topic": topic, **kwargs}) |
| 137 | return reports[topic] |
| 138 | |
| 139 | with ( |
| 140 | mock.patch.object(sys, "argv", argv), |
| 141 | mock.patch.object(evaluator, "run_last30days", side_effect=fake_run), |
| 142 | mock.patch.object(evaluator, "make_title_judge", return_value=_in_process_judge), |
| 143 | contextlib.redirect_stdout(io.StringIO()), |
| 144 | contextlib.redirect_stderr(io.StringIO()), |
| 145 | ): |
| 146 | code = evaluator.main() |
| 147 | return code, calls, tmp_path / "out" |
| 148 | |
| 149 | |
| 150 | def test_mode_parses_topics_and_builds_a_per_topic_table(tmp_path): |
| 151 | topics = [ |
| 152 | {"topic": "Claude Code", "kind": "mainstream"}, |
| 153 | {"topic": "Quillmark Vesperloom firmware", "kind": "no_coverage", "expect_coverage": False}, |
| 154 | ] |
| 155 | reports = { |
| 156 | "Claude Code": _report([_thread("Claude Code tips", comments=5), _thread("Pizza")]), |
| 157 | "Quillmark Vesperloom firmware": _report([], "no path served; brave empty"), |
| 158 | } |
| 159 | code, calls, out = _run_main(tmp_path, topics, reports) |
| 160 | assert code == 0 |
| 161 | # Floor only: Reddit search, no consent or envelope flags, an env with no SC key. |
| 162 | assert {call["search"] for call in calls} == {"reddit"} |
| 163 | assert all("SCRAPECREATORS_API_KEY" not in call["env"] for call in calls) |
| 164 | assert len(calls) == 4 # baseline and candidate for each topic |
| 165 | payload = json.loads((out / "reddit-coverage.json").read_text()) |
| 166 | rows = {row["topic"]: row for row in payload["topics"]} |
| 167 | assert rows["Claude Code"]["candidate"]["on_topic"] == 1 |
| 168 | assert rows["Claude Code"]["candidate"]["comments"] == 5 |
| 169 | assert rows["Claude Code"]["baseline"]["on_topic"] == 1 |
| 170 | table = (out / "reddit-coverage.md").read_text() |
| 171 | assert "| Claude Code | mainstream | 1/2 | 0% | 5 | web+arctic served 3 | 1/2 | 0% | 5 | web+arctic served 3 | |" in table |
| 172 | |
| 173 | |
| 174 | def test_no_coverage_topic_reports_zero_without_failing(tmp_path): |
| 175 | topics = [{"topic": "Quillmark Vesperloom firmware", "kind": "no_coverage", "expect_coverage": False}] |
| 176 | reports = {"Quillmark Vesperloom firmware": _report([], "no path served; brave empty")} |
| 177 | code, _calls, out = _run_main(tmp_path, topics, reports, baseline="none") |
| 178 | assert code == 0 |
| 179 | payload = json.loads((out / "reddit-coverage.json").read_text()) |
| 180 | assert payload["failures"] == [] |
| 181 | assert payload["baseline"] is None |
| 182 | row = payload["topics"][0] |
| 183 | assert row["candidate"]["on_topic"] == 0 |
| 184 | assert row["baseline"] is None |
| 185 | assert row["flag"] == "no coverage (expected)" |
| 186 | assert "| - | - | - | - |" in (out / "reddit-coverage.md").read_text() |
| 187 | |
| 188 | |
| 189 | def test_engine_failure_is_recorded_and_exits_nonzero(tmp_path): |
| 190 | topics = [{"topic": "Claude Code", "kind": "mainstream"}] |
| 191 | topics_file = tmp_path / "topics.json" |
| 192 | topics_file.write_text(json.dumps(topics)) |
| 193 | argv = ["evaluate_search_quality.py", "--reddit-coverage", "--baseline=none", "--candidate=WORKTREE", |
| 194 | "--topics-file", str(topics_file), "--output-dir", str(tmp_path / "out")] |
| 195 | with ( |
| 196 | mock.patch.object(sys, "argv", argv), |
| 197 | mock.patch.object(evaluator, "run_last30days", side_effect=RuntimeError("engine exit 1")), |
| 198 | mock.patch.object(evaluator, "make_title_judge", return_value=_in_process_judge), |
| 199 | contextlib.redirect_stdout(io.StringIO()), |
| 200 | contextlib.redirect_stderr(io.StringIO()), |
| 201 | ): |
| 202 | assert evaluator.main() == 1 |
| 203 | payload = json.loads((tmp_path / "out" / "reddit-coverage.json").read_text()) |
| 204 | assert payload["failures"] == [{"topic": "Claude Code", "error": "engine exit 1"}] |
| 205 | |
| 206 | |
| 207 | def test_mode_defaults_to_the_coverage_fixture(tmp_path): |
| 208 | rows = evaluator.load_reddit_coverage_topics(TOPICS_FIXTURE) |
| 209 | argv = ["evaluate_search_quality.py", "--reddit-coverage", "--baseline=none", "--candidate=WORKTREE", |
| 210 | "--limit-topics", "2", "--output-dir", str(tmp_path / "out")] |
| 211 | seen = [] |
| 212 | with ( |
| 213 | mock.patch.object(sys, "argv", argv), |
| 214 | mock.patch.object(evaluator, "run_last30days", side_effect=lambda _d, topic, **_k: seen.append(topic) or _report([])), |
| 215 | mock.patch.object(evaluator, "make_title_judge", return_value=_in_process_judge), |
| 216 | contextlib.redirect_stdout(io.StringIO()), |
| 217 | contextlib.redirect_stderr(io.StringIO()), |
| 218 | ): |
| 219 | assert evaluator.main() == 0 |
| 220 | assert seen == [row["topic"] for row in rows[:2]] |
| 221 |