| 1 | """V2EX source: SOV2EX search, relevance gating, reply enrichment.""" |
| 2 | |
| 3 | import datetime |
| 4 | import urllib.parse |
| 5 | |
| 6 | from lib import normalize, pipeline, v2ex |
| 7 | |
| 8 | |
| 9 | def _hit(topic_id, title, *, content="", created="2026-11-20T08:00:00", member=None, replies=0, node=12): |
| 10 | return { |
| 11 | "_id": str(topic_id), |
| 12 | "_source": { |
| 13 | "id": topic_id, |
| 14 | "title": title, |
| 15 | "content": content or f"About {title}", |
| 16 | "created": created, |
| 17 | "member": member or f"user{topic_id}", |
| 18 | "node": node, |
| 19 | "replies": replies, |
| 20 | }, |
| 21 | } |
| 22 | |
| 23 | |
| 24 | def _reply(username, content, created=1795667778): |
| 25 | return {"member": {"username": username}, "content": content, "created": created} |
| 26 | |
| 27 | |
| 28 | class FakeApi: |
| 29 | def __init__(self, hits=None, replies=None, fail=(), search_body=None): |
| 30 | self.hits = hits or [] |
| 31 | self.replies = replies or {} |
| 32 | self.fail = set(fail) |
| 33 | self.search_body = search_body |
| 34 | self.calls = [] |
| 35 | |
| 36 | def __call__(self, method, url, headers=None, **kwargs): |
| 37 | self.calls.append(url) |
| 38 | parsed = urllib.parse.urlparse(url) |
| 39 | query = dict(urllib.parse.parse_qsl(parsed.query)) |
| 40 | if parsed.netloc == "www.sov2ex.com" and parsed.path == "/api/search": |
| 41 | if "search" in self.fail: |
| 42 | raise OSError("search down") |
| 43 | if self.search_body is not None: |
| 44 | return self.search_body |
| 45 | return {"took": 1, "total": len(self.hits), "hits": self.hits} |
| 46 | if parsed.netloc == "www.v2ex.com" and parsed.path == "/api/replies/show.json": |
| 47 | if "replies" in self.fail: |
| 48 | raise OSError("replies down") |
| 49 | return self.replies.get(query["topic_id"], []) |
| 50 | raise AssertionError(f"unexpected URL {url}") |
| 51 | |
| 52 | |
| 53 | def _install(monkeypatch, api): |
| 54 | monkeypatch.setattr(v2ex.http, "request", api) |
| 55 | return api |
| 56 | |
| 57 | |
| 58 | def _search_params(api): |
| 59 | return dict(urllib.parse.parse_qsl(urllib.parse.urlparse(api.calls[0]).query)) |
| 60 | |
| 61 | |
| 62 | def _source_items(hits): |
| 63 | parsed = v2ex.parse_v2ex_response({"topics": [h["_source"] for h in hits]}, query="claude code") |
| 64 | return normalize.normalize_source_items("v2ex", parsed, "2026-10-27", "2026-11-26") |
| 65 | |
| 66 | |
| 67 | def _diagnose_sources(argv, config=None): |
| 68 | import json |
| 69 | |
| 70 | from tests.test_diagnose_compat import FAKE_KEYLESS_CONFIG, _run_cli |
| 71 | |
| 72 | rc, out = _run_cli(["--diagnose", *argv], {**FAKE_KEYLESS_CONFIG, **(config or {})}) |
| 73 | assert rc == 0 |
| 74 | return json.loads(out)["available_sources"] |
| 75 | |
| 76 | |
| 77 | def test_v2ex_is_off_by_default(): |
| 78 | assert "v2ex" not in pipeline.available_sources({}, None, x_pending=False) |
| 79 | |
| 80 | |
| 81 | def test_include_sources_and_search_each_activate_it(): |
| 82 | assert "v2ex" in pipeline.available_sources({"INCLUDE_SOURCES": "v2ex"}, None, x_pending=False) |
| 83 | assert "v2ex" in pipeline.available_sources({}, ["v2ex"], x_pending=False) |
| 84 | |
| 85 | |
| 86 | def test_cli_activation_and_exclusion_through_diagnose(): |
| 87 | assert "v2ex" not in _diagnose_sources([]) |
| 88 | assert "v2ex" in _diagnose_sources(["--search", "reddit,v2ex"]) |
| 89 | assert "v2ex" in _diagnose_sources([], {"INCLUDE_SOURCES": "v2ex"}) |
| 90 | assert "v2ex" not in _diagnose_sources([], {"INCLUDE_SOURCES": "v2ex", "EXCLUDE_SOURCES": "v2ex"}) |
| 91 | |
| 92 | |
| 93 | def test_search_sends_window_bounds_and_requires_every_term(monkeypatch): |
| 94 | api = _install(monkeypatch, FakeApi()) |
| 95 | v2ex.search_v2ex("claude code", "2026-10-27", "2026-11-26", depth="deep", search_query='"claude code"') |
| 96 | params = _search_params(api) |
| 97 | assert params["q"] == "claude code" |
| 98 | assert params["size"] == "40" |
| 99 | assert params["sort"] == "sumup" |
| 100 | assert params["operator"] == "and" |
| 101 | utc = datetime.timezone.utc |
| 102 | assert int(params["gte"]) == int(datetime.datetime(2026, 10, 27, tzinfo=utc).timestamp()) |
| 103 | assert int(params["lte"]) == int(datetime.datetime(2026, 11, 26, 23, 59, 59, tzinfo=utc).timestamp()) |
| 104 | |
| 105 | |
| 106 | def test_search_size_stays_under_the_sov2ex_cap(): |
| 107 | assert max(v2ex.SEARCH_SIZE.values()) <= 50 |
| 108 | |
| 109 | |
| 110 | def test_offtopic_and_duplicate_hits_are_dropped(monkeypatch): |
| 111 | _install(monkeypatch, FakeApi(hits=[ |
| 112 | _hit(1, "Claude Code 和 Codex 怎么选", content="claude code 用了一个月"), |
| 113 | _hit(1, "Claude Code 和 Codex 怎么选", content="claude code 用了一个月"), |
| 114 | _hit(2, "招聘后端工程师", content="五险一金,弹性工作"), |
| 115 | ])) |
| 116 | result = v2ex.search_v2ex("claude code", "2026-10-27", "2026-11-26") |
| 117 | assert [t["id"] for t in result["topics"]] == [1] |
| 118 | assert "error" not in result |
| 119 | |
| 120 | |
| 121 | def test_chinese_topics_pass_relevance(monkeypatch): |
| 122 | _install(monkeypatch, FakeApi(hits=[_hit(1, "国产大模型评测对比", content="最近测了几个大模型")])) |
| 123 | result = v2ex.search_v2ex("大模型评测", "2026-10-27", "2026-11-26") |
| 124 | assert [t["id"] for t in result["topics"]] == [1] |
| 125 | |
| 126 | |
| 127 | def test_failed_search_reports_an_error(monkeypatch): |
| 128 | _install(monkeypatch, FakeApi(fail={"search"})) |
| 129 | result = v2ex.search_v2ex("claude code", "2026-10-27", "2026-11-26") |
| 130 | assert result["topics"] == [] |
| 131 | assert "search down" in result["error"] |
| 132 | |
| 133 | |
| 134 | def test_rejected_query_is_an_error_not_an_empty_result(monkeypatch): |
| 135 | _install(monkeypatch, FakeApi(search_body={"message": "too large size"})) |
| 136 | result = v2ex.search_v2ex("claude code", "2026-10-27", "2026-11-26") |
| 137 | assert result["topics"] == [] |
| 138 | assert "too large size" in result["error"] |
| 139 | |
| 140 | |
| 141 | def test_empty_query_makes_no_request(monkeypatch): |
| 142 | api = _install(monkeypatch, FakeApi()) |
| 143 | assert v2ex.search_v2ex("", "2026-10-27", "2026-11-26") == {"topics": []} |
| 144 | assert api.calls == [] |
| 145 | |
| 146 | |
| 147 | def test_parse_maps_topic_fields(): |
| 148 | long_content = "claude code " * 100 |
| 149 | [item] = v2ex.parse_v2ex_response( |
| 150 | {"topics": [_hit(1259973, "Claude Code & Codex", content=long_content, replies=12, member="alice")["_source"]]}, |
| 151 | query="claude code", |
| 152 | ) |
| 153 | assert item["id"] == "1259973" |
| 154 | assert item["url"] == "https://www.v2ex.com/t/1259973" |
| 155 | assert item["title"] == "Claude Code & Codex" |
| 156 | assert item["author"] == "alice" |
| 157 | assert item["date"] == "2026-11-20" |
| 158 | assert item["engagement"] == {"replies": 12} |
| 159 | assert item["text"].endswith("...") and len(item["text"]) == v2ex.TEXT_LIMIT + 3 |
| 160 | assert item["metadata"] == {"node_id": 12} |
| 161 | assert 0 < item["relevance"] <= 1 |
| 162 | |
| 163 | |
| 164 | def test_normalized_item_uses_v2ex_container(): |
| 165 | [item] = _source_items([_hit(1, "Claude Code 体验", content="claude code 很好用")]) |
| 166 | assert item.source == "v2ex" |
| 167 | assert item.container == "V2EX" |
| 168 | assert item.published_at == "2026-11-20" |
| 169 | assert item.date_confidence == "high" |
| 170 | assert item.snippet == "claude code 很好用" |
| 171 | |
| 172 | |
| 173 | def test_replies_put_topic_answers_first_and_skip_the_author(monkeypatch): |
| 174 | _install(monkeypatch, FakeApi(replies={"1": [ |
| 175 | _reply("op", "补充一下背景"), |
| 176 | _reply("bob", "@carol 同意"), |
| 177 | _reply("carol", "命令行就够了"), |
| 178 | _reply("dave", "@bob @carol 半天就适应了"), |
| 179 | _reply("erin", " "), |
| 180 | ]})) |
| 181 | count, comments = v2ex._fetch_replies("1", "op") |
| 182 | assert count == 5 |
| 183 | assert [(c["author"], c["text"]) for c in comments] == [ |
| 184 | ("carol", "命令行就够了"), |
| 185 | ("bob", "同意"), |
| 186 | ("dave", "半天就适应了"), |
| 187 | ] |
| 188 | assert comments[0]["date"] == "2026-11-26" |
| 189 | |
| 190 | |
| 191 | def test_enrichment_targets_top_items_and_refreshes_reply_counts(monkeypatch): |
| 192 | api = _install(monkeypatch, FakeApi(replies={ |
| 193 | "1": [_reply("bob", "claude code 好用"), _reply("carol", "确实")], |
| 194 | "2": [], |
| 195 | "3": [_reply("dave", "不错")], |
| 196 | })) |
| 197 | items = _source_items([ |
| 198 | _hit(1, "Claude Code one", replies=0), |
| 199 | _hit(2, "Claude Code two", replies=0), |
| 200 | _hit(3, "Claude Code three", replies=0), |
| 201 | _hit(4, "Claude Code four", replies=9), |
| 202 | ]) |
| 203 | v2ex.enrich_source_items(items) |
| 204 | fetched = sorted(dict(urllib.parse.parse_qsl(urllib.parse.urlparse(u).query))["topic_id"] for u in api.calls) |
| 205 | assert fetched == ["1", "2", "3"] |
| 206 | assert items[0].engagement["replies"] == 2 |
| 207 | assert [c["excerpt"] for c in items[0].metadata["top_comments"]] == ["claude code 好用", "确实"] |
| 208 | # Replies carry no votes: the score stays absent, not a measured zero. |
| 209 | assert items[0].metadata["top_comments"][0]["score"] is None |
| 210 | assert not items[1].metadata.get("top_comments") |
| 211 | assert items[3].engagement["replies"] == 9 |
| 212 | |
| 213 | |
| 214 | def test_refreshed_reply_count_reaches_the_engagement_score(monkeypatch): |
| 215 | from lib import signals |
| 216 | |
| 217 | _install(monkeypatch, FakeApi(replies={"1": [_reply(f"user{n}", f"回复 {n}") for n in range(60)]})) |
| 218 | [item] = _source_items([_hit(1, "Claude Code one", replies=0)]) |
| 219 | signals.annotate_stream([item], "claude code", "balanced_recent", reference_date="2026-11-26") |
| 220 | stale_score = item.engagement_score |
| 221 | v2ex.enrich_source_items([item]) |
| 222 | assert item.engagement["replies"] == 60 |
| 223 | assert item.engagement_score == signals.engagement_score(item) |
| 224 | # Zero replies measure no engagement at all (None), not a zero score. |
| 225 | assert stale_score is None |
| 226 | assert item.engagement_score > 0 |
| 227 | |
| 228 | |
| 229 | def test_malformed_reply_records_do_not_abort_enrichment(monkeypatch): |
| 230 | _install(monkeypatch, FakeApi(replies={"1": [ |
| 231 | {"member": "unexpected", "content": "坏回复"}, |
| 232 | {"member": ["unexpected"], "content": "另一条坏回复"}, |
| 233 | _reply("bob", "claude code 好用"), |
| 234 | ]})) |
| 235 | items = _source_items([_hit(1, "Claude Code one", replies=0)]) |
| 236 | v2ex.enrich_source_items(items) |
| 237 | assert items[0].title == "Claude Code one" |
| 238 | assert items[0].engagement["replies"] == 3 |
| 239 | assert [c["excerpt"] for c in items[0].metadata["top_comments"]] == ["claude code 好用"] |
| 240 | |
| 241 | |
| 242 | def test_failed_reply_fetch_keeps_the_item(monkeypatch): |
| 243 | _install(monkeypatch, FakeApi(fail={"replies"})) |
| 244 | items = _source_items([_hit(1, "Claude Code one", replies=4)]) |
| 245 | v2ex.enrich_source_items(items) |
| 246 | assert items[0].engagement["replies"] == 4 |
| 247 | assert not items[0].metadata.get("top_comments") |
| 248 | |
| 249 | |
| 250 | def test_enrichment_skips_when_the_deadline_has_passed(monkeypatch): |
| 251 | api = _install(monkeypatch, FakeApi()) |
| 252 | items = _source_items([_hit(1, "Claude Code one")]) |
| 253 | v2ex.enrich_source_items(items, deadline=0.0) |
| 254 | assert api.calls == [] |
| 255 | |
| 256 | |
| 257 | def test_enrichment_stops_waiting_at_its_time_limit(monkeypatch): |
| 258 | import threading |
| 259 | import time |
| 260 | |
| 261 | release = threading.Event() |
| 262 | |
| 263 | def stuck(topic_id, op): |
| 264 | release.wait(5) |
| 265 | return 1, [{"author": "a", "text": "late"}] |
| 266 | |
| 267 | monkeypatch.setattr(v2ex, "_fetch_replies", stuck) |
| 268 | monkeypatch.setattr(v2ex, "ENRICH_WAIT_SECONDS", 0.2) |
| 269 | items = _source_items([_hit(1, "Claude Code one")]) |
| 270 | started = time.monotonic() |
| 271 | v2ex.enrich_source_items(items) |
| 272 | elapsed = time.monotonic() - started |
| 273 | release.set() |
| 274 | assert elapsed < 2 |
| 275 | assert not items[0].metadata.get("top_comments") |
| 276 | |
| 277 | |
| 278 | def test_requests_carry_a_total_deadline(monkeypatch): |
| 279 | seen = {} |
| 280 | |
| 281 | def capture(method, url, headers=None, **kwargs): |
| 282 | seen.update(kwargs) |
| 283 | return {"hits": []} |
| 284 | |
| 285 | monkeypatch.setattr(v2ex.http, "request", capture) |
| 286 | v2ex.search_v2ex("claude code", "2026-10-27", "2026-11-26") |
| 287 | assert seen["owned_get"] is True |
| 288 | assert seen["deadline_monotonic"] is not None |
| 289 | |
| 290 | |
| 291 | def test_doctor_reports_v2ex_as_opt_in_until_enabled(): |
| 292 | from lib import doctor |
| 293 | |
| 294 | assert doctor._v2ex_record({})["status"] == "opt-in" |
| 295 | assert doctor._v2ex_record({"INCLUDE_SOURCES": "v2ex"})["status"] == "ok" |
| 296 | assert "v2ex" not in doctor._probeable_sources() |
| 297 | |
| 298 | |
| 299 | def _plan(sources): |
| 300 | from lib import schema |
| 301 | |
| 302 | return schema.QueryPlan( |
| 303 | intent="concept", |
| 304 | freshness_mode="balanced_recent", |
| 305 | cluster_mode="none", |
| 306 | raw_topic="claude code", |
| 307 | subqueries=[schema.SubQuery(label="primary", search_query="claude code", |
| 308 | ranking_query="q", sources=list(sources), weight=1.0)], |
| 309 | source_weights={source: 1.0 for source in sources}, |
| 310 | ) |
| 311 | |
| 312 | |
| 313 | def test_activated_v2ex_joins_a_plan_that_omits_it(): |
| 314 | plan = _plan(["hackernews"]) |
| 315 | pipeline._ensure_opt_in_source_in_plan(plan, ["hackernews", "v2ex"], "v2ex") |
| 316 | assert "v2ex" in plan.subqueries[0].sources |
| 317 | assert "v2ex" in plan.source_weights |
| 318 | |
| 319 | |
| 320 | def test_inactive_v2ex_is_not_added_to_a_plan(): |
| 321 | plan = _plan(["hackernews"]) |
| 322 | pipeline._ensure_opt_in_source_in_plan(plan, ["hackernews"], "v2ex") |
| 323 | assert plan.subqueries[0].sources == ["hackernews"] |
| 324 | |
| 325 | |
| 326 | def test_retrieve_stream_runs_search_and_parse(monkeypatch): |
| 327 | from lib import schema |
| 328 | |
| 329 | _install(monkeypatch, FakeApi(hits=[_hit(1, "Claude Code 体验", content="claude code 很好用")])) |
| 330 | subquery = schema.SubQuery(label="primary", search_query="claude code", |
| 331 | ranking_query="q", sources=["v2ex"], weight=1.0) |
| 332 | items, _artifact = pipeline._retrieve_stream_impl( |
| 333 | topic="claude code", subquery=subquery, source="v2ex", config={}, |
| 334 | depth="default", date_range=("2026-10-27", "2026-11-26"), |
| 335 | runtime=None, mock=False, |
| 336 | ) |
| 337 | assert [item["url"] for item in items] == ["https://www.v2ex.com/t/1"] |
| 338 |