返回 last30days-skill
test_hackernews_comment_floor.py
根目录 / tests / test_hackernews_comment_floor.py
1 """Hacker News comments must survive the per-source top-comment floor.
2
3 HN comments arrive as ``{author, text, points}`` while every downstream reader
4 keys on ``score``/``excerpt``. Before the fix, ``_normalize_hackernews`` stored
5 them raw, so ``render._top_comments_list`` evaluated ``(c.get("score") or 0) >= 5``
6 against a key that was never present and rejected the entire source.
7 """
8
9 from unittest.mock import patch
10
11 from lib import hackernews, normalize, render, schema
12
13 FROM_DATE = "2026-06-26"
14 TO_DATE = "2026-07-26"
15
16
17 def _hn_item():
18 return {
19 "id": "42",
20 "title": "Show HN: a thing",
21 "url": "https://example.test/thing",
22 "hn_url": "https://news.ycombinator.com/item?id=42",
23 "author": "pg",
24 "date": "2026-07-20",
25 "engagement": {"points": 420, "comments": 2},
26 "top_comments": [
27 {
28 "author": "alice",
29 "text": "The single clearest explanation I have read.",
30 "points": 93,
31 },
32 {
33 "author": "bob",
34 "text": "Counterpoint: the benchmark skips the hard cases.",
35 "points": None,
36 },
37 ],
38 }
39
40
41 def _reddit_item():
42 return {
43 "id": "r1",
44 "title": "a reddit thread",
45 "url": "https://reddit.test/r1",
46 "author": "carol",
47 "date": "2026-07-20",
48 "engagement": {"upvotes": 300, "comments": 2},
49 "top_comments": [
50 {
51 "author": "alice",
52 "excerpt": "The single clearest explanation I have read.",
53 "score": 93,
54 },
55 {
56 "author": "bob",
57 "excerpt": "Counterpoint: the benchmark skips the hard cases.",
58 "score": 51,
59 },
60 ],
61 }
62
63
64 def test_hn_comments_are_remapped_to_the_shared_shape():
65 item = normalize._normalize_hackernews(
66 "hackernews", _hn_item(), 0, FROM_DATE, TO_DATE
67 )
68 comments = item.metadata["top_comments"]
69 assert comments, "HN comments should survive normalisation"
70 for comment in comments:
71 assert "score" in comment, (
72 f"expected the shared score key, got {sorted(comment)}"
73 )
74 assert "excerpt" in comment, (
75 f"expected the shared excerpt key, got {sorted(comment)}"
76 )
77 assert comments[0]["score"] == 93, "points must carry through as score"
78
79
80 def test_hn_comments_clear_the_per_source_floor():
81 item = normalize._normalize_hackernews(
82 "hackernews", _hn_item(), 0, FROM_DATE, TO_DATE
83 )
84 assert render._top_comments_list(item), (
85 "HN comments must not be filtered out by a floor keyed on a field the "
86 "source never populated"
87 )
88
89
90 def test_hn_floor_is_zero_because_hn_has_no_per_comment_points():
91 """The Algolia items endpoint returns points=null for every comment child.
92
93 Any positive threshold therefore rejects the whole source rather than
94 filtering it, so this constant is load-bearing rather than a tuning knob.
95 """
96 assert render._TOP_COMMENT_MIN_SCORE["hackernews"] == 0
97
98
99 def test_reddit_control_is_unchanged():
100 item = normalize._normalize_reddit("reddit", _reddit_item(), 0, FROM_DATE, TO_DATE)
101 assert len(render._top_comments_list(item)) == 2
102
103
104 def _candidate(source, item):
105 return schema.Candidate(
106 candidate_id="c1",
107 item_id=item.item_id,
108 source=source,
109 title=item.title,
110 url=item.url,
111 snippet="",
112 subquery_labels=[],
113 native_ranks={},
114 local_relevance=0.9,
115 freshness=1,
116 engagement=100,
117 source_quality=0.9,
118 rrf_score=1.0,
119 source_items=[item],
120 final_score=50.0,
121 explanation="llm-rerank",
122 )
123
124
125 def _report(item, candidate):
126 return schema.Report(
127 topic="HN comments",
128 range_from=FROM_DATE,
129 range_to=TO_DATE,
130 generated_at=f"{TO_DATE}T00:00:00+00:00",
131 provider_runtime=schema.ProviderRuntime(
132 reasoning_provider="local",
133 planner_model="local",
134 rerank_model="local",
135 ),
136 query_plan=schema.QueryPlan(
137 intent="general",
138 freshness_mode="balanced_recent",
139 cluster_mode="story",
140 raw_topic="HN comments",
141 subqueries=[
142 schema.SubQuery(
143 label="primary",
144 search_query="HN comments",
145 ranking_query="What are the top HN comments?",
146 sources=["hackernews"],
147 )
148 ],
149 source_weights={"hackernews": 1.0},
150 ),
151 clusters=[],
152 ranked_candidates=[candidate],
153 items_by_source={"hackernews": [item]},
154 errors_by_source={},
155 )
156
157
158 def _render_vote_paths(points):
159 raw = _hn_item()
160 with patch("lib.hackernews.http.request") as request:
161 request.return_value = {
162 "children": [
163 {
164 "author": "alice",
165 "text": raw["top_comments"][0]["text"],
166 "points": 93,
167 },
168 {
169 "author": "bob",
170 "text": raw["top_comments"][1]["text"],
171 "points": points,
172 },
173 ]
174 }
175 raw["top_comments"] = hackernews._fetch_item_comments("42")["comments"]
176 hn = normalize._normalize_hackernews(
177 "hackernews", raw, 0, FROM_DATE, TO_DATE
178 )
179 candidate = _candidate("hackernews", hn)
180 report = _report(hn, candidate)
181 return hn.metadata["top_comments"][1]["score"], {
182 "full": render.render_full(report),
183 "candidate": "\n".join(render._render_candidate(candidate, prefix="1.")),
184 "top_comments": "\n".join(render._render_top_comments(report)),
185 }
186
187
188 def _points(path, count):
189 """How a path prints an HN vote count: the quote pool uses the quote
190 line's own shape, the other two the parenthesised one."""
191 return f"· {count} points" if path == "top_comments" else f"({count} points)"
192
193
194 def test_absent_hn_vote_is_omitted_across_comment_renderers():
195 """A missing vote must not display a fabricated numeric measurement."""
196 normalized_score, rendered_paths = _render_vote_paths(None)
197 assert normalized_score is None
198 for path, rendered in rendered_paths.items():
199 assert _points(path, 0) not in rendered, f"{path}:\n{rendered}"
200 assert _points(path, 93) in rendered, f"{path} dropped a real vote count"
201 assert '" 🟡 bob on Hacker News — ' in rendered_paths["top_comments"]
202
203
204 def test_explicit_zero_hn_vote_is_rendered_across_comment_renderers():
205 """A measured zero remains visible in every zero-admitting comment path."""
206 normalized_score, rendered_paths = _render_vote_paths(0)
207 assert normalized_score == 0
208 for path, rendered in rendered_paths.items():
209 assert _points(path, 0) in rendered, f"{path} hid an explicit numeric zero"
210
211
212 def test_best_takes_uses_normalized_hn_comment_excerpt():
213 """Best Takes should display HN comment text, not only the story title."""
214 first_raw = _hn_item()
215 first_raw["title"] = "Show HN: a deliberately long story title for testing"
216 first_raw["top_comments"] = [
217 {"author": "alice", "text": "A sharp HN take.", "points": None}
218 ]
219 second_raw = _hn_item()
220 second_raw["id"] = "43"
221 second_raw["title"] = "Ask HN: another deliberately long story title for testing"
222 second_raw["top_comments"] = [
223 {"author": "bob", "text": "Another good take.", "points": None}
224 ]
225 first = _candidate(
226 "hackernews",
227 normalize._normalize_hackernews(
228 "hackernews", first_raw, 0, FROM_DATE, TO_DATE
229 ),
230 )
231 second = _candidate(
232 "hackernews",
233 normalize._normalize_hackernews(
234 "hackernews", second_raw, 1, FROM_DATE, TO_DATE
235 ),
236 )
237 first.fun_score = 80.0
238 second.fun_score = 80.0
239
240 rendered = "\n".join(
241 render._render_best_takes([first, second], threshold=70.0, vote_weight=0.0)
242 )
243 assert "A sharp HN take." in rendered
244 assert "Another good take." in rendered
245
246
247 def test_best_takes_uses_hn_comment_longer_than_story_title():
248 """HN comment excerpts remain the take even when longer than the title."""
249 first_raw = _hn_item()
250 first_raw["title"] = "Short story"
251 first_raw["top_comments"] = [
252 {
253 "author": "alice",
254 "text": "This longer Hacker News comment is the actual sharp take.",
255 "points": None,
256 }
257 ]
258 second_raw = _hn_item()
259 second_raw["id"] = "43"
260 second_raw["top_comments"] = [
261 {"author": "bob", "text": "Another good take.", "points": None}
262 ]
263 first = _candidate(
264 "hackernews",
265 normalize._normalize_hackernews(
266 "hackernews", first_raw, 0, FROM_DATE, TO_DATE
267 ),
268 )
269 second = _candidate(
270 "hackernews",
271 normalize._normalize_hackernews(
272 "hackernews", second_raw, 1, FROM_DATE, TO_DATE
273 ),
274 )
275 first.fun_score = 80.0
276 second.fun_score = 80.0
277
278 rendered = "\n".join(
279 render._render_best_takes([first, second], threshold=70.0, vote_weight=0.0)
280 )
281 assert "This longer Hacker News comment is the actual sharp take." in rendered
282 assert '"Short story"' not in rendered
283
284
285 def test_best_takes_uses_hn_excerpt_retained_by_fused_candidate():
286 """A non-HN representative must not hide its retained HN comment."""
287 reddit = normalize._normalize_reddit(
288 "reddit", _reddit_item(), 0, FROM_DATE, TO_DATE
289 )
290 hn_raw = _hn_item()
291 hn_raw["top_comments"] = [
292 {"author": "alice", "text": "The retained HN take.", "points": 93}
293 ]
294 hn = normalize._normalize_hackernews(
295 "hackernews", hn_raw, 0, FROM_DATE, TO_DATE
296 )
297 fused = _candidate("reddit", reddit)
298 fused.source_items = [reddit, hn]
299 assert fused.source != "hackernews"
300 control_raw = _reddit_item()
301 control_raw["id"] = "r2"
302 control_raw["title"] = "a separate reddit thread"
303 control = _candidate(
304 "reddit",
305 normalize._normalize_reddit(
306 "reddit", control_raw, 1, FROM_DATE, TO_DATE
307 ),
308 )
309 fused.fun_score = 80.0
310 control.fun_score = 80.0
311
312 top_comments = "\n".join(
313 render._render_top_comments(
314 _report(reddit, fused),
315 candidates=[fused, control],
316 )
317 )
318 rendered = "\n".join(
319 render._render_best_takes([fused, control], threshold=70.0, vote_weight=0.0)
320 )
321 assert "The retained HN take." in rendered
322 fused_line = next(
323 line for line in rendered.splitlines() if "The retained HN take." in line
324 )
325 assert "-- Hacker News " in fused_line
326 assert "Reddit" not in fused_line
327 assert "r/" not in fused_line
328 retained_line = next(
329 line for line in top_comments.splitlines() if "The retained HN take." in line
330 )
331 assert '" 🟡 alice on Hacker News · 93 points' in retained_line
332 assert "upvotes" not in retained_line
333 assert "u/alice" not in retained_line
334 assert retained_line.endswith(" — top comment — funny")
335
336
337 # --- Comment permalinks (R7/R8): a quote links to where it was said. -------
338
339 ARTICLE_URL = "https://example.test/thing"
340
341
342 def _fetched_hn_item(children):
343 """Run Algolia children through fetch -> normalize, like the live path."""
344 raw = _hn_item()
345 with patch("lib.hackernews.http.request") as request:
346 request.return_value = {"children": children}
347 raw["top_comments"] = hackernews._fetch_item_comments("42")["comments"]
348 return normalize._normalize_hackernews("hackernews", raw, 0, FROM_DATE, TO_DATE)
349
350
351 def _comment_lines(rendered, *needles):
352 return [
353 line for line in rendered.splitlines() if any(n in line for n in needles)
354 ]
355
356
357 def _render_comment_paths(hn):
358 candidate = _candidate("hackernews", hn)
359 report = _report(hn, candidate)
360 return {
361 "top_comments": "\n".join(render._render_top_comments(report)),
362 "cluster": "\n".join(render._render_candidate(candidate, prefix="1.")),
363 }
364
365
366 def test_hn_comment_with_id_links_its_own_permalink():
367 hn = _fetched_hn_item(
368 [
369 {"id": 4242, "author": "alice", "text": "The single clearest explanation I have read.", "points": None},
370 {"id": 4243, "author": "bob", "text": "Counterpoint: the benchmark skips the hard cases.", "points": None},
371 ]
372 )
373 assert hn.metadata["top_comments"][0]["url"] == "https://news.ycombinator.com/item?id=4242"
374 for path, rendered in _render_comment_paths(hn).items():
375 (line,) = _comment_lines(rendered, "clearest explanation")
376 assert "https://news.ycombinator.com/item?id=4242" in line, f"{path}: {line}"
377 assert ARTICLE_URL not in line, f"{path}: {line}"
378
379
380 def test_hn_comment_without_id_links_the_discussion_page():
381 hn = _fetched_hn_item(
382 [
383 {"author": "alice", "text": "The single clearest explanation I have read.", "points": None},
384 {"author": "bob", "text": "Counterpoint: the benchmark skips the hard cases.", "points": None},
385 ]
386 )
387 for path, rendered in _render_comment_paths(hn).items():
388 lines = _comment_lines(rendered, "clearest explanation", "hard cases")
389 assert len(lines) == 2, f"{path}:\n{rendered}"
390 for line in lines:
391 assert "https://news.ycombinator.com/item?id=42" in line, f"{path}: {line}"
392 assert ARTICLE_URL not in line, f"{path}: {line}"
393
394
395 def test_pre_fix_hn_item_falls_back_to_hn_url_metadata_not_article():
396 """An item normalized before comments carried URLs still links the discussion."""
397 raw = _hn_item()
398 raw["hn_url"] = "https://news.ycombinator.com/item?id=4200"
399 hn = normalize._normalize_hackernews("hackernews", raw, 0, FROM_DATE, TO_DATE)
400 assert all("url" not in c for c in hn.metadata["top_comments"])
401 assert hn.url == ARTICLE_URL
402 for path, rendered in _render_comment_paths(hn).items():
403 lines = _comment_lines(rendered, "clearest explanation", "hard cases")
404 assert len(lines) == 2, f"{path}:\n{rendered}"
405 for line in lines:
406 assert "https://news.ycombinator.com/item?id=4200" in line, f"{path}: {line}"
407 assert ARTICLE_URL not in line, f"{path}: {line}"
408
409
410 def test_hn_comment_retained_by_non_hn_candidate_links_hn_not_candidate_url():
411 reddit = normalize._normalize_reddit("reddit", _reddit_item(), 0, FROM_DATE, TO_DATE)
412 hn = _fetched_hn_item(
413 [
414 {"id": 4242, "author": "dave", "text": "A retained HN comment with its own link.", "points": None},
415 ]
416 )
417 fused = _candidate("reddit", reddit)
418 fused.source_items = [reddit, hn]
419 rendered = "\n".join(render._render_top_comments(_report(reddit, fused)))
420 (line,) = _comment_lines(rendered, "retained HN comment")
421 assert "https://news.ycombinator.com/item?id=4242" in line
422 assert fused.url not in line
423
423 lines PYTHON