返回 last30days-skill
test_juejin.py
根目录 / tests / test_juejin.py
1 """Juejin source: paged search, window and relevance gating, comments."""
2
3 import datetime
4
5 import pytest
6
7 from lib import health, juejin, normalize, pipeline
8
9 UTC = datetime.timezone.utc
10
11
12 def _ts(day, hour=8):
13 return str(int(datetime.datetime.fromisoformat(f"{day}T{hour:02d}:00:00").replace(tzinfo=UTC).timestamp()))
14
15
16 def _row(article_id, title, *, brief="", day="2026-11-20", likes=0, comments=0, saves=0, views=10,
17 author="alice", author_id="100", tags=("AI编程",)):
18 return {
19 "result_type": 2,
20 "result_model": {
21 "article_id": str(article_id),
22 "article_info": {
23 "article_id": str(article_id),
24 "title": title,
25 "brief_content": brief or f"About {title}",
26 "ctime": _ts(day),
27 "digg_count": likes,
28 "comment_count": comments,
29 "collect_count": saves,
30 "view_count": views,
31 "user_id": author_id,
32 },
33 "author_user_info": {"user_name": author, "user_id": author_id},
34 "tags": [{"tag_name": t} for t in tags],
35 "category": {"category_name": "人工智能"},
36 },
37 }
38
39
40 def _comment(user, text, *, likes=0, user_id=None, bot_id="0"):
41 return {
42 "comment_info": {
43 "comment_content": text,
44 "digg_count": likes,
45 "user_id": user_id or f"u-{user}",
46 "bot_id": bot_id,
47 "ctime": 1795667778,
48 },
49 "user_info": {"user_name": user, "user_id": user_id or f"u-{user}"},
50 }
51
52
53 class FakeApi:
54 def __init__(self, pages=None, comments=None, fail=(), search_body=None):
55 self.pages = pages or [[]]
56 self.comments = comments or {}
57 self.fail = set(fail)
58 self.search_body = search_body
59 self.calls = []
60
61 def __call__(self, method, url, headers=None, json_data=None, **kwargs):
62 assert method == "POST"
63 self.calls.append((url, json_data, kwargs))
64 if url == juejin.SEARCH_URL:
65 page = int(json_data["cursor"])
66 if page in self.fail or "search" in self.fail:
67 raise OSError(f"page {page + 1} down")
68 if self.search_body is not None:
69 return self.search_body
70 rows = self.pages[page] if page < len(self.pages) else []
71 has_more = page + 1 < len(self.pages)
72 return {"err_no": 0, "err_msg": "success", "data": rows, "has_more": has_more, "cursor": str(page + 1)}
73 if url == juejin.COMMENTS_URL:
74 if "comments" in self.fail:
75 raise OSError("comments down")
76 return {"err_no": 0, "data": self.comments.get(json_data["item_id"], [])}
77 raise AssertionError(f"unexpected URL {url}")
78
79
80 def _install(monkeypatch, api):
81 monkeypatch.setattr(juejin.http, "request", api)
82 return api
83
84
85 def _search_calls(api):
86 return [body for url, body, _ in api.calls if url == juejin.SEARCH_URL]
87
88
89 def _source_items(rows):
90 parsed = juejin.parse_juejin_response({"articles": [r["result_model"] for r in rows]}, query="claude code")
91 return normalize.normalize_source_items("juejin", parsed, "2026-10-28", "2026-11-27")
92
93
94 def _diagnose_sources(argv, config=None):
95 import json
96
97 from tests.test_diagnose_compat import FAKE_KEYLESS_CONFIG, _run_cli
98
99 rc, out = _run_cli(["--diagnose", *argv], {**FAKE_KEYLESS_CONFIG, **(config or {})})
100 assert rc == 0
101 return json.loads(out)["available_sources"]
102
103
104 def test_juejin_is_off_by_default():
105 assert "juejin" not in pipeline.available_sources({}, None, x_pending=False)
106
107
108 def test_include_sources_and_search_each_activate_it():
109 assert "juejin" in pipeline.available_sources({"INCLUDE_SOURCES": "juejin"}, None, x_pending=False)
110 assert "juejin" in pipeline.available_sources({}, ["juejin"], x_pending=False)
111
112
113 def test_cli_activation_and_exclusion_through_diagnose():
114 assert "juejin" not in _diagnose_sources([])
115 assert "juejin" in _diagnose_sources(["--search", "reddit,juejin"])
116 assert "juejin" in _diagnose_sources([], {"INCLUDE_SOURCES": "juejin"})
117 assert "juejin" not in _diagnose_sources([], {"INCLUDE_SOURCES": "juejin", "EXCLUDE_SOURCES": "juejin"})
118
119
120 def test_search_sends_newest_first_query_without_quotes(monkeypatch):
121 api = _install(monkeypatch, FakeApi())
122 juejin.search_juejin("claude code", "2026-10-28", "2026-11-27", search_query='"claude code"')
123 [body] = _search_calls(api)
124 assert body["key_word"] == "claude code"
125 assert body["sort_type"] == 1
126 assert body["id_type"] == 2
127 assert body["cursor"] == "0"
128
129
130 def test_pages_follow_the_cursor_up_to_the_depth_cap(monkeypatch):
131 pages = [[_row(n * 10 + i, f"Claude Code {n}{i}") for i in range(2)] for n in range(8)]
132 api = _install(monkeypatch, FakeApi(pages=pages))
133 juejin.search_juejin("claude code", "2026-10-28", "2026-11-27", depth="default")
134 assert [b["cursor"] for b in _search_calls(api)] == ["0", "1", "2"]
135 api.calls.clear()
136 juejin.search_juejin("claude code", "2026-10-28", "2026-11-27", depth="quick")
137 assert [b["cursor"] for b in _search_calls(api)] == ["0"]
138
139
140 def test_paging_stops_when_a_whole_page_predates_the_window(monkeypatch):
141 pages = [
142 [_row(1, "Claude Code one", day="2026-11-20"), _row(2, "Claude Code two", day="2026-09-01")],
143 [_row(3, "Claude Code three", day="2026-08-01"), _row(4, "Claude Code four", day="2026-07-01")],
144 [_row(5, "Claude Code five", day="2026-11-21")],
145 ]
146 api = _install(monkeypatch, FakeApi(pages=pages))
147 result = juejin.search_juejin("claude code", "2026-10-28", "2026-11-27", depth="deep")
148 assert [b["cursor"] for b in _search_calls(api)] == ["0", "1"]
149 assert [r["article_id"] for r in result["articles"]] == ["1"]
150
151
152 def test_window_relevance_dedupe_and_engagement_ranking(monkeypatch):
153 pages = [
154 [
155 _row(1, "Claude Code 上手", views=40),
156 _row(2, "Claude Code 实战", likes=12, comments=3, views=900),
157 _row(3, "周末去爬山", brief="风景很好"),
158 _row(4, "Claude Code 旧文", day="2026-09-01", likes=500),
159 _row(5, "Claude Code 来自未来", day="2026-12-25"),
160 ],
161 [_row(2, "Claude Code 实战", likes=12, comments=3, views=900)],
162 ]
163 _install(monkeypatch, FakeApi(pages=pages))
164 result = juejin.search_juejin("claude code", "2026-10-28", "2026-11-27")
165 assert [r["article_id"] for r in result["articles"]] == ["2", "1"]
166 assert "error" not in result
167
168
169 def test_keep_limit_caps_results_by_depth(monkeypatch):
170 rows = [_row(n, f"Claude Code {n}", likes=n) for n in range(15)]
171 _install(monkeypatch, FakeApi(pages=[rows]))
172 result = juejin.search_juejin("claude code", "2026-10-28", "2026-11-27", depth="quick")
173 assert len(result["articles"]) == juejin.KEEP_LIMIT["quick"]
174 assert result["articles"][0]["article_id"] == "14"
175
176
177 def test_ranking_uses_the_engagement_mix_not_likes_first(monkeypatch):
178 rows = [_row(n, f"Claude Code {n}", likes=1) for n in range(20)]
179 rows.append(_row(99, "Claude Code 深度实践", likes=0, comments=100, saves=50, views=10000))
180 _install(monkeypatch, FakeApi(pages=[rows]))
181 result = juejin.search_juejin("claude code", "2026-10-28", "2026-11-27", depth="default")
182 assert result["articles"][0]["article_id"] == "99"
183 assert len(result["articles"]) == juejin.KEEP_LIMIT["default"]
184
185
186 def test_changed_reply_shape_is_an_error_not_an_empty_result(monkeypatch):
187 _install(monkeypatch, FakeApi(search_body={"err_no": 0, "err_msg": "success", "data": {"items": []}}))
188 result = juejin.search_juejin("claude code", "2026-10-28", "2026-11-27")
189 assert result["articles"] == []
190 assert "unexpected Juejin search data: dict" in result["error"]
191
192
193 def test_chinese_topics_pass_relevance(monkeypatch):
194 _install(monkeypatch, FakeApi(pages=[[_row(1, "鸿蒙原生应用开发实践", brief="从零开发一个鸿蒙应用")]]))
195 result = juejin.search_juejin("鸿蒙开发", "2026-10-28", "2026-11-27")
196 assert [r["article_id"] for r in result["articles"]] == ["1"]
197
198
199 def test_first_page_failure_is_an_error(monkeypatch):
200 _install(monkeypatch, FakeApi(fail={"search"}))
201 result = juejin.search_juejin("claude code", "2026-10-28", "2026-11-27")
202 assert result["articles"] == []
203 assert "page 1 down" in result["error"]
204
205
206 def test_api_error_code_is_an_error_not_an_empty_result(monkeypatch):
207 _install(monkeypatch, FakeApi(search_body={"err_no": 2, "err_msg": "参数错误"}))
208 result = juejin.search_juejin("claude code", "2026-10-28", "2026-11-27")
209 assert result["articles"] == []
210 assert "参数错误" in result["error"]
211
212
213 def test_later_page_failure_keeps_the_pages_fetched(monkeypatch):
214 pages = [[_row(1, "Claude Code one")], [_row(2, "Claude Code two")], [_row(3, "Claude Code three")]]
215 _install(monkeypatch, FakeApi(pages=pages, fail={1}))
216 result = juejin.search_juejin("claude code", "2026-10-28", "2026-11-27")
217 assert [r["article_id"] for r in result["articles"]] == ["1"]
218 assert "error" not in result
219
220
221 @pytest.mark.parametrize(("title", "expected_urls", "expected_state"), [
222 ("Claude Code one", ["https://juejin.cn/post/1"], health.PARTIAL),
223 ("Weekend hiking trails", [], health.ERROR),
224 ])
225 def test_malformed_later_page_reports_outcome_for_retained_items(
226 monkeypatch, title, expected_urls, expected_state,
227 ):
228 from lib import schema
229
230 def request(method, url, headers=None, json_data=None, **kwargs):
231 assert url == juejin.SEARCH_URL
232 if json_data["cursor"] == "0":
233 return {"err_no": 0, "data": [_row(1, title)],
234 "has_more": True, "cursor": "1"}
235 return {"err_no": 0, "data": {"items": []}}
236
237 monkeypatch.setattr(juejin.http, "request", request)
238 subquery = schema.SubQuery(label="primary", search_query="claude code",
239 ranking_query="q", sources=["juejin"], weight=1.0)
240 items, artifact = pipeline._retrieve_stream_impl(
241 topic="claude code", subquery=subquery, source="juejin", config={},
242 depth="default", date_range=("2026-10-28", "2026-11-27"),
243 runtime=None, mock=False,
244 )
245 assert [item["url"] for item in items] == expected_urls
246 outcome = artifact["_source_outcome"]
247 assert outcome["state"] == expected_state
248 assert "page 2" in outcome["detail"]
249 assert outcome["attempted"] is True
250
251
252 def test_empty_query_makes_no_request(monkeypatch):
253 api = _install(monkeypatch, FakeApi())
254 assert juejin.search_juejin("", "2026-10-28", "2026-11-27") == {"articles": []}
255 assert api.calls == []
256
257
258 def test_requests_carry_a_total_deadline(monkeypatch):
259 api = _install(monkeypatch, FakeApi())
260 juejin.search_juejin("claude code", "2026-10-28", "2026-11-27")
261 _url, _body, kwargs = api.calls[0]
262 assert kwargs["deadline_monotonic"] is not None
263
264
265 def test_parse_maps_article_fields():
266 long_brief = "claude code " * 100
267 [item] = juejin.parse_juejin_response(
268 {"articles": [_row(7607, "Claude Code &amp; Codex", brief=long_brief, likes=5, comments=2, saves=3,
269 views=400, author="bob", author_id="42")["result_model"]]},
270 query="claude code",
271 )
272 assert item["id"] == "7607"
273 assert item["url"] == "https://juejin.cn/post/7607"
274 assert item["title"] == "Claude Code & Codex"
275 assert item["author"] == "bob"
276 assert item["date"] == "2026-11-20"
277 assert item["engagement"] == {"likes": 5, "comments": 2, "saves": 3, "views": 400}
278 assert item["text"].endswith("...") and len(item["text"]) == juejin.TEXT_LIMIT + 3
279 assert item["metadata"] == {"tags": ["AI编程"], "category": "人工智能", "author_id": "42"}
280 assert 0 < item["relevance"] <= 1
281
282
283 def test_search_tolerates_negative_and_huge_engagement(monkeypatch):
284 # math.log1p raises on a negative count and overflows on a huge int; both
285 # used to abort the source after its network phase had already finished.
286 for likes in (-3, 10**1000):
287 _install(monkeypatch, FakeApi(pages=[[_row(1, "Claude Code one", likes=likes)]]))
288 result = juejin.search_juejin("claude code", "2026-10-28", "2026-11-27", depth="quick")
289 assert [row["article_id"] for row in result["articles"]] == ["1"]
290
291
292 def test_parse_treats_a_malformed_ctime_as_missing():
293 # Out-of-range seconds, a pre-epoch value, and a non-finite JSON number
294 # all fail fromtimestamp; the item should still be usable with no date.
295 for ctime in (10**18, -1, float("inf")):
296 row = _row(1, "Claude Code")
297 row["result_model"]["article_info"]["ctime"] = ctime
298 [item] = juejin.parse_juejin_response(
299 {"articles": [row["result_model"]]}, query="claude code"
300 )
301 assert item["date"] == ""
302
303
304 def test_normalized_item_with_a_malformed_ctime_has_low_date_confidence():
305 row = _row(1, "Claude Code one")
306 row["result_model"]["article_info"]["ctime"] = float("inf")
307 [item] = _source_items([row])
308 assert item.published_at in (None, "")
309 assert item.date_confidence == "low"
310
311
312 def test_parse_clamps_negative_engagement_counts():
313 row = _row(1, "Claude Code", likes=-3, comments=-2)
314 [item] = juejin.parse_juejin_response(
315 {"articles": [row["result_model"]]}, query="claude code"
316 )
317 assert item["engagement"]["likes"] == 0
318 assert item["engagement"]["comments"] == 0
319
320
321 def test_parse_tolerates_huge_engagement_counts():
322 row = _row(1, "Claude Code", likes=10**1000, comments=10**1000)
323 [item] = juejin.parse_juejin_response(
324 {"articles": [row["result_model"]]}, query="claude code"
325 )
326 assert 0 <= item["relevance"] <= 1
327
328
329 def test_normalized_item_uses_juejin_container():
330 [item] = _source_items([_row(1, "Claude Code 体验", brief="claude code 很好用")])
331 assert item.source == "juejin"
332 assert item.container == "Juejin"
333 assert item.published_at == "2026-11-20"
334 assert item.date_confidence == "high"
335 assert item.snippet == "claude code 很好用"
336
337
338 def test_comments_rank_by_likes_and_drop_bots_and_the_author(monkeypatch):
339 _install(monkeypatch, FakeApi(comments={"1": [
340 _comment("carol", "写得很清楚", likes=1),
341 _comment("alice", "作者补充:已更新", likes=9, user_id="100"),
342 _comment("helper", "AI 总结:本文介绍了", likes=5, bot_id="7"),
343 _comment("dave", "踩过同样的坑", likes=4),
344 _comment("erin", " "),
345 ]}))
346 comments = juejin._fetch_comments("1", "100")
347 assert [(c["author"], c["text"], c["likes"]) for c in comments] == [
348 ("dave", "踩过同样的坑", 4),
349 ("carol", "写得很清楚", 1),
350 ]
351 assert comments[0]["date"] == "2026-11-26"
352
353
354 def test_enrichment_targets_top_items_with_comments(monkeypatch):
355 api = _install(monkeypatch, FakeApi(comments={
356 "1": [_comment("bob", "claude code 好用", likes=3)],
357 "3": [_comment("dave", "不错")],
358 }))
359 items = _source_items([
360 _row(1, "Claude Code one", comments=2),
361 _row(2, "Claude Code two", comments=0),
362 _row(3, "Claude Code three", comments=1),
363 _row(4, "Claude Code four", comments=1),
364 _row(5, "Claude Code five", comments=1),
365 ])
366 juejin.enrich_source_items(items)
367 fetched = sorted(body["item_id"] for url, body, _ in api.calls if url == juejin.COMMENTS_URL)
368 assert fetched == ["1", "3", "4"]
369 assert [(c["excerpt"], c["score"]) for c in items[0].metadata["top_comments"]] == [("claude code 好用", 3)]
370 assert not items[1].metadata.get("top_comments")
371
372
373 def test_malformed_comment_records_do_not_abort_enrichment(monkeypatch):
374 malformed_info = {"comment_info": "unexpected", "user_info": {"user_name": "bob"}}
375 malformed_user = _comment("carol", "这条评论不应丢失正文")
376 malformed_user["user_info"] = ["unexpected"]
377 _install(monkeypatch, FakeApi(comments={"1": [
378 malformed_info,
379 malformed_user,
380 _comment("dave", "claude code 好用", likes=3),
381 ]}))
382 items = _source_items([_row(1, "Claude Code one", comments=3)])
383 juejin.enrich_source_items(items)
384 assert items[0].title == "Claude Code one"
385 assert [(c["author"], c["excerpt"]) for c in items[0].metadata["top_comments"]] == [
386 ("dave", "claude code 好用"),
387 ]
388
389
390 def test_failed_comment_fetch_keeps_the_item(monkeypatch):
391 _install(monkeypatch, FakeApi(fail={"comments"}))
392 items = _source_items([_row(1, "Claude Code one", comments=4)])
393 juejin.enrich_source_items(items)
394 assert not items[0].metadata.get("top_comments")
395
396
397 def test_enrichment_skips_when_the_deadline_has_passed(monkeypatch):
398 api = _install(monkeypatch, FakeApi())
399 items = _source_items([_row(1, "Claude Code one", comments=2)])
400 juejin.enrich_source_items(items, deadline=0.0)
401 assert api.calls == []
402
403
404 def test_enrichment_stops_waiting_at_its_time_limit(monkeypatch):
405 import threading
406 import time
407
408 release = threading.Event()
409
410 def stuck(article_id, author_id):
411 release.wait(5)
412 return [{"author": "a", "text": "late", "likes": 1}]
413
414 monkeypatch.setattr(juejin, "_fetch_comments", stuck)
415 monkeypatch.setattr(juejin, "ENRICH_WAIT_SECONDS", 0.2)
416 items = _source_items([_row(1, "Claude Code one", comments=2)])
417 started = time.monotonic()
418 juejin.enrich_source_items(items)
419 elapsed = time.monotonic() - started
420 release.set()
421 assert elapsed < 2
422 assert not items[0].metadata.get("top_comments")
423
424
425 def test_engagement_score_counts_views_on_a_like_free_article():
426 from lib import signals
427
428 [quiet] = _source_items([_row(1, "Claude Code one", views=35)])
429 [busy] = _source_items([_row(2, "Claude Code two", likes=8, comments=3, saves=4, views=1200)])
430 assert 15 <= signals.engagement_score(quiet) <= 30
431 assert 80 <= signals.engagement_score(busy) <= 95
432
433
434 def test_doctor_reports_juejin_as_opt_in_until_enabled():
435 from lib import doctor
436
437 assert doctor._juejin_record({})["status"] == "opt-in"
438 assert doctor._juejin_record({"INCLUDE_SOURCES": "juejin"})["status"] == "ok"
439 assert "juejin" not in doctor._probeable_sources()
440
441
442 def _plan(sources):
443 from lib import schema
444
445 return schema.QueryPlan(
446 intent="concept",
447 freshness_mode="balanced_recent",
448 cluster_mode="none",
449 raw_topic="claude code",
450 subqueries=[schema.SubQuery(label="primary", search_query="claude code",
451 ranking_query="q", sources=list(sources), weight=1.0)],
452 source_weights={source: 1.0 for source in sources},
453 )
454
455
456 def test_activated_juejin_joins_a_plan_that_omits_it():
457 plan = _plan(["hackernews"])
458 pipeline._ensure_opt_in_source_in_plan(plan, ["hackernews", "juejin"], "juejin")
459 assert "juejin" in plan.subqueries[0].sources
460 assert "juejin" in plan.source_weights
461
462
463 def test_retrieve_stream_runs_search_and_parse(monkeypatch):
464 from lib import schema
465
466 _install(monkeypatch, FakeApi(pages=[[_row(1, "Claude Code 体验", brief="claude code 很好用")]]))
467 subquery = schema.SubQuery(label="primary", search_query="claude code",
468 ranking_query="q", sources=["juejin"], weight=1.0)
469 items, _artifact = pipeline._retrieve_stream_impl(
470 topic="claude code", subquery=subquery, source="juejin", config={},
471 depth="default", date_range=("2026-10-28", "2026-11-27"),
472 runtime=None, mock=False,
473 )
474 assert [item["url"] for item in items] == ["https://juejin.cn/post/1"]
475
475 lines PYTHON