| 1 | """Tests for hackernews.py - HN search via Algolia API.""" |
| 2 | |
| 3 | import json |
| 4 | from datetime import datetime, timezone |
| 5 | from unittest.mock import MagicMock, Mock, patch |
| 6 | from urllib.parse import parse_qs, urlsplit |
| 7 | |
| 8 | import pytest |
| 9 | |
| 10 | from lib import hackernews |
| 11 | |
| 12 | # === Helper Functions === |
| 13 | |
| 14 | |
| 15 | def create_mock_hit( |
| 16 | object_id="12345", |
| 17 | title="Test HN Story", |
| 18 | points=100, |
| 19 | num_comments=50, |
| 20 | created_at_i=None, |
| 21 | author="testuser", |
| 22 | url="https://example.com", |
| 23 | ): |
| 24 | """Create a mock Algolia hit object.""" |
| 25 | if created_at_i is None: |
| 26 | # Default to 30 days ago |
| 27 | dt = datetime.now(timezone.utc) |
| 28 | created_at_i = int(dt.timestamp()) - (30 * 86400) |
| 29 | |
| 30 | return { |
| 31 | "objectID": object_id, |
| 32 | "title": title, |
| 33 | "points": points, |
| 34 | "num_comments": num_comments, |
| 35 | "created_at_i": created_at_i, |
| 36 | "author": author, |
| 37 | "url": url, |
| 38 | } |
| 39 | |
| 40 | # === Tests for _date_to_unix() === |
| 41 | |
| 42 | |
| 43 | def test_date_to_unix_basic(): |
| 44 | """Test converting YYYY-MM-DD to Unix timestamp.""" |
| 45 | result = hackernews._date_to_unix("2026-01-01") |
| 46 | |
| 47 | # Should be midnight UTC on Jan 1, 2026 |
| 48 | expected = datetime(2026, 1, 1, tzinfo=timezone.utc).timestamp() |
| 49 | assert result == int(expected) |
| 50 | |
| 51 | |
| 52 | def test_date_to_unix_leap_day(): |
| 53 | """Test date conversion with leap day.""" |
| 54 | result = hackernews._date_to_unix("2024-02-29") |
| 55 | |
| 56 | expected = datetime(2024, 2, 29, tzinfo=timezone.utc).timestamp() |
| 57 | assert result == int(expected) |
| 58 | |
| 59 | # === Tests for _unix_to_date() === |
| 60 | |
| 61 | |
| 62 | def test_unix_to_date_basic(): |
| 63 | """Test converting Unix timestamp to YYYY-MM-DD.""" |
| 64 | ts = int(datetime(2026, 1, 15, tzinfo=timezone.utc).timestamp()) |
| 65 | result = hackernews._unix_to_date(ts) |
| 66 | |
| 67 | assert result == "2026-01-15" |
| 68 | |
| 69 | |
| 70 | def test_unix_to_date_with_time(): |
| 71 | """Test that time component is stripped.""" |
| 72 | ts = int(datetime(2026, 1, 15, 14, 30, 45, tzinfo=timezone.utc).timestamp()) |
| 73 | result = hackernews._unix_to_date(ts) |
| 74 | |
| 75 | assert result == "2026-01-15" |
| 76 | |
| 77 | # === Tests for _strip_html() === |
| 78 | |
| 79 | |
| 80 | def test_strip_html_basic(): |
| 81 | """Test HTML stripping and entity decoding.""" |
| 82 | html_text = "<p>Hello & goodbye</p>" |
| 83 | result = hackernews._strip_html(html_text) |
| 84 | |
| 85 | assert result == "Hello & goodbye" |
| 86 | |
| 87 | |
| 88 | def test_strip_html_paragraph_tags(): |
| 89 | """Test that <p> tags are converted to newlines.""" |
| 90 | html_text = "First<p>Second<p>Third" |
| 91 | result = hackernews._strip_html(html_text) |
| 92 | |
| 93 | assert "First\n" in result |
| 94 | assert "Second\n" in result |
| 95 | |
| 96 | |
| 97 | def test_strip_html_nested_tags(): |
| 98 | """Test stripping nested HTML tags.""" |
| 99 | html_text = "<div><a href='test'>Link</a> text <b>bold</b></div>" |
| 100 | result = hackernews._strip_html(html_text) |
| 101 | |
| 102 | assert result == "Link text bold" |
| 103 | |
| 104 | |
| 105 | def test_strip_html_entities(): |
| 106 | """Test HTML entity decoding and tag stripping.""" |
| 107 | html_text = "Text & "test"" |
| 108 | result = hackernews._strip_html(html_text) |
| 109 | |
| 110 | # Entities are decoded |
| 111 | assert "&" in result or "test" in result |
| 112 | |
| 113 | |
| 114 | def test_strip_html_preserves_escaped_markup_in_comment_text(): |
| 115 | text = ( |
| 116 | "Use <code>vector<int></code>.<p>" |
| 117 | "Print <p> when x < y && y > 0." |
| 118 | ) |
| 119 | assert hackernews._strip_html(text) == "Use vector<int>.\nPrint <p> when x < y && y > 0." |
| 120 | |
| 121 | |
| 122 | # === Tests for _title_matches_query() === |
| 123 | |
| 124 | |
| 125 | def test_title_matches_query_basic(): |
| 126 | """Test basic query matching.""" |
| 127 | title = "New AI framework for developers" |
| 128 | query = "AI framework" |
| 129 | |
| 130 | assert hackernews._title_matches_query(title, query) is True |
| 131 | |
| 132 | |
| 133 | def test_title_matches_query_case_insensitive(): |
| 134 | """Test that matching is case-insensitive.""" |
| 135 | title = "NEW AI FRAMEWORK" |
| 136 | query = "ai framework" |
| 137 | |
| 138 | assert hackernews._title_matches_query(title, query) is True |
| 139 | |
| 140 | |
| 141 | def test_title_matches_query_with_prefix(): |
| 142 | """Test matching with HN prefix stripped.""" |
| 143 | title = "Show HN: My new AI framework" |
| 144 | query = "AI framework" |
| 145 | |
| 146 | # Should match "AI framework" in the content, not the "Show HN:" prefix |
| 147 | assert hackernews._title_matches_query(title, query) is True |
| 148 | |
| 149 | |
| 150 | def test_title_matches_query_prefix_only(): |
| 151 | """Test that matching prefix-only returns False.""" |
| 152 | title = "Show HN: Something else entirely" |
| 153 | query = "Show HN" |
| 154 | |
| 155 | # "Show HN" is a prefix, not real content |
| 156 | # After stripping, "Show HN" won't be in the stripped title |
| 157 | assert hackernews._title_matches_query(title, query) is False |
| 158 | |
| 159 | |
| 160 | def test_title_matches_query_empty_query(): |
| 161 | """Test that empty query always matches.""" |
| 162 | title = "Any title" |
| 163 | query = "" |
| 164 | |
| 165 | assert hackernews._title_matches_query(title, query) is True |
| 166 | |
| 167 | |
| 168 | def test_title_matches_query_partial_match(): |
| 169 | """Any-word matching: at least one query token in title is enough. |
| 170 | |
| 171 | Previously required *all* tokens, which killed every hit on multi-keyword |
| 172 | theme queries like 'claude, personal agents, agentic infra' since no real |
| 173 | HN title contains all 5 tokens verbatim. Token-overlap relevance at parse |
| 174 | time still demotes weak matches, so the loosened gate is safe. |
| 175 | """ |
| 176 | title = "New AI framework" |
| 177 | query = "AI blockchain" |
| 178 | |
| 179 | # "AI" matches as a whole word, even though "blockchain" doesn't appear |
| 180 | assert hackernews._title_matches_query(title, query) is True |
| 181 | |
| 182 | |
| 183 | def test_title_matches_query_no_token_in_title(): |
| 184 | """If no query token appears in the title at all, reject.""" |
| 185 | assert hackernews._title_matches_query("New rust compiler", "AI blockchain") is False |
| 186 | |
| 187 | |
| 188 | def test_title_matches_query_word_boundary_not_substring(): |
| 189 | """Short tokens must match on word boundaries, not as substrings. |
| 190 | |
| 191 | Without word-boundary matching, 'ai' would falsely match 'email', |
| 192 | 'rail', 'artists', etc. |
| 193 | """ |
| 194 | # 'ai' as a substring of 'email' must not match |
| 195 | assert hackernews._title_matches_query("New email service", "ai blockchain") is False |
| 196 | # 'ai' as a whole word does match |
| 197 | assert hackernews._title_matches_query("Cool AI tool launched", "ai blockchain") is True |
| 198 | |
| 199 | |
| 200 | def test_title_matches_query_flattens_hyphens_and_commas(): |
| 201 | """Query tokens split on hyphens/commas the same way search_hackernews |
| 202 | flattens them, so the post-filter stays aligned with what Algolia saw.""" |
| 203 | # query 'ts-bun-node' flattens to ['ts', 'bun', 'node']; title contains 'bun' |
| 204 | assert hackernews._title_matches_query("Bun 1.2 released", "ts-bun-node") is True |
| 205 | # query 'rust, go, zig' flattens; title contains 'go' |
| 206 | assert hackernews._title_matches_query("Go 1.24 generics update", "rust, go, zig") is True |
| 207 | |
| 208 | # === Tests for search_hackernews() === |
| 209 | |
| 210 | @patch('lib.hackernews.http.request') |
| 211 | |
| 212 | |
| 213 | def test_search_hackernews_basic(mock_request): |
| 214 | """Test basic HN search.""" |
| 215 | mock_request.return_value = { |
| 216 | "hits": [create_mock_hit()], |
| 217 | "nbHits": 1, |
| 218 | } |
| 219 | |
| 220 | result = hackernews.search_hackernews( |
| 221 | "AI framework", |
| 222 | "2026-01-01", |
| 223 | "2026-01-31", |
| 224 | depth="quick" |
| 225 | ) |
| 226 | |
| 227 | assert "hits" in result |
| 228 | assert len(result["hits"]) == 1 |
| 229 | assert mock_request.called |
| 230 | |
| 231 | @patch('lib.hackernews.http.request') |
| 232 | |
| 233 | |
| 234 | def test_search_hackernews_depth_config(mock_request): |
| 235 | """Test that depth parameter controls hit count.""" |
| 236 | mock_request.return_value = {"hits": [], "nbHits": 0} |
| 237 | |
| 238 | # Quick mode returns up to 15 hits, but overfetches before client-side |
| 239 | # engagement filtering so low-point stories do not shrink result depth. |
| 240 | hackernews.search_hackernews("test", "2026-01-01", "2026-01-31", depth="quick") |
| 241 | |
| 242 | call_args = mock_request.call_args[0] |
| 243 | url = call_args[1] |
| 244 | |
| 245 | expected_hits_per_page = ( |
| 246 | hackernews.DEPTH_CONFIG["quick"] * hackernews.HN_OVERFETCH_MULTIPLIER |
| 247 | ) |
| 248 | assert f"hitsPerPage={expected_hits_per_page}" in url |
| 249 | |
| 250 | @patch('lib.hackernews.http.request') |
| 251 | |
| 252 | |
| 253 | def test_search_hackernews_date_filtering(mock_request): |
| 254 | """Test that date range is applied correctly.""" |
| 255 | mock_request.return_value = {"hits": [], "nbHits": 0} |
| 256 | |
| 257 | hackernews.search_hackernews("test", "2026-01-01", "2026-01-31", depth="quick") |
| 258 | |
| 259 | mock_request.assert_called_once() |
| 260 | url = mock_request.call_args.args[1] |
| 261 | filters = parse_qs(urlsplit(url).query)["numericFilters"] |
| 262 | assert filters == ["created_at_i>1767225600,created_at_i<1769904000"] |
| 263 | |
| 264 | @patch('lib.hackernews.http.request') |
| 265 | |
| 266 | |
| 267 | def test_search_hackernews_http_error_handling(mock_request): |
| 268 | """Test graceful handling of HTTP errors.""" |
| 269 | from lib.http import HTTPError |
| 270 | mock_request.side_effect = HTTPError("HTTP 429: Too Many Requests") |
| 271 | |
| 272 | result = hackernews.search_hackernews("test", "2026-01-01", "2026-01-31") |
| 273 | |
| 274 | # Should return empty hits with error |
| 275 | assert result["hits"] == [] |
| 276 | assert "error" in result |
| 277 | |
| 278 | @patch('lib.hackernews.http.request') |
| 279 | |
| 280 | |
| 281 | def test_search_hackernews_engagement_filter(mock_request): |
| 282 | """Test that low-engagement stories are filtered client-side.""" |
| 283 | mock_request.return_value = { |
| 284 | "hits": [ |
| 285 | create_mock_hit(object_id="low", points=2), |
| 286 | create_mock_hit(object_id="high", points=3), |
| 287 | ], |
| 288 | "nbHits": 2, |
| 289 | } |
| 290 | |
| 291 | result = hackernews.search_hackernews("test", "2026-01-01", "2026-01-31") |
| 292 | |
| 293 | call_args = mock_request.call_args[0] |
| 294 | url = call_args[1] |
| 295 | |
| 296 | # Algolia rejects points in numericFilters; keep only supported date filters. |
| 297 | assert "points" not in url |
| 298 | assert [hit["objectID"] for hit in result["hits"]] == ["high"] |
| 299 | |
| 300 | |
| 301 | @patch('lib.hackernews.http.request') |
| 302 | def test_search_hackernews_no_points_numericfilter(mock_request): |
| 303 | """numericFilters must NOT include a `points` clause. |
| 304 | |
| 305 | `points` is not in the HN Algolia index's `numericAttributesForFiltering`, |
| 306 | so a `points>2` clause returns HTTP 400 ("invalid numeric attribute(points)") |
| 307 | and zero stories. Engagement is filtered client-side after overfetching |
| 308 | instead. This guards against the invalid filter being reintroduced. |
| 309 | """ |
| 310 | mock_request.return_value = {"hits": [], "nbHits": 0} |
| 311 | |
| 312 | hackernews.search_hackernews("test", "2026-01-01", "2026-01-31") |
| 313 | |
| 314 | url = mock_request.call_args[0][1] |
| 315 | |
| 316 | # Date filter stays; the invalid points filter must be gone. |
| 317 | assert "created_at_i" in url |
| 318 | assert "points" not in url |
| 319 | |
| 320 | |
| 321 | @patch('lib.hackernews.http.request') |
| 322 | def test_search_hackernews_truncates_after_overfetch(mock_request): |
| 323 | """Test that overfetching does not return more than the requested depth.""" |
| 324 | mock_request.return_value = { |
| 325 | "hits": [ |
| 326 | create_mock_hit(object_id=str(i), points=10) |
| 327 | for i in range(20) |
| 328 | ], |
| 329 | "nbHits": 20, |
| 330 | } |
| 331 | |
| 332 | result = hackernews.search_hackernews("test", "2026-01-01", "2026-01-31", depth="quick") |
| 333 | |
| 334 | assert len(result["hits"]) == 15 |
| 335 | assert [hit["objectID"] for hit in result["hits"]] == [str(i) for i in range(15)] |
| 336 | |
| 337 | # === Tests for parse_hackernews_response() === |
| 338 | |
| 339 | |
| 340 | def test_parse_hackernews_response_basic(): |
| 341 | """Test parsing basic Algolia response.""" |
| 342 | response = { |
| 343 | "hits": [create_mock_hit( |
| 344 | object_id="123", |
| 345 | title="Test Story", |
| 346 | points=100, |
| 347 | num_comments=50 |
| 348 | )] |
| 349 | } |
| 350 | |
| 351 | items = hackernews.parse_hackernews_response(response) |
| 352 | |
| 353 | assert len(items) == 1 |
| 354 | assert items[0]["id"] == "123" |
| 355 | assert items[0]["title"] == "Test Story" |
| 356 | assert items[0]["engagement"]["points"] == 100 |
| 357 | assert items[0]["engagement"]["comments"] == 50 |
| 358 | |
| 359 | |
| 360 | def test_parse_hackernews_response_hn_url(): |
| 361 | """Test that HN discussion URL is generated correctly.""" |
| 362 | response = { |
| 363 | "hits": [create_mock_hit(object_id="12345")] |
| 364 | } |
| 365 | |
| 366 | items = hackernews.parse_hackernews_response(response) |
| 367 | |
| 368 | assert items[0]["hn_url"] == "https://news.ycombinator.com/item?id=12345" |
| 369 | |
| 370 | |
| 371 | def test_parse_hackernews_response_date_conversion(): |
| 372 | """Test that Unix timestamp is converted to YYYY-MM-DD.""" |
| 373 | ts = int(datetime(2026, 1, 15, tzinfo=timezone.utc).timestamp()) |
| 374 | response = { |
| 375 | "hits": [create_mock_hit(created_at_i=ts)] |
| 376 | } |
| 377 | |
| 378 | items = hackernews.parse_hackernews_response(response) |
| 379 | |
| 380 | assert items[0]["date"] == "2026-01-15" |
| 381 | |
| 382 | |
| 383 | def test_parse_hackernews_response_missing_fields(): |
| 384 | """Test handling of hits with missing optional fields.""" |
| 385 | response = { |
| 386 | "hits": [{ |
| 387 | "objectID": "123", |
| 388 | "title": "Test", |
| 389 | # Missing points, num_comments, created_at_i |
| 390 | }] |
| 391 | } |
| 392 | |
| 393 | items = hackernews.parse_hackernews_response(response) |
| 394 | |
| 395 | assert len(items) == 1 |
| 396 | assert items[0]["engagement"]["points"] == 0 |
| 397 | assert items[0]["engagement"]["comments"] == 0 |
| 398 | assert items[0]["date"] is None |
| 399 | |
| 400 | |
| 401 | def test_parse_hackernews_response_relevance_scoring(): |
| 402 | """Test that relevance scores are calculated.""" |
| 403 | response = { |
| 404 | "hits": [ |
| 405 | create_mock_hit(object_id="1", points=100), |
| 406 | create_mock_hit(object_id="2", points=50), |
| 407 | create_mock_hit(object_id="3", points=10), |
| 408 | ] |
| 409 | } |
| 410 | |
| 411 | items = hackernews.parse_hackernews_response(response, query="test") |
| 412 | |
| 413 | # Should have relevance scores |
| 414 | for item in items: |
| 415 | assert "relevance" in item |
| 416 | assert 0 <= item["relevance"] <= 1.0 |
| 417 | |
| 418 | # First item should generally have higher relevance (better rank) |
| 419 | assert items[0]["relevance"] >= items[2]["relevance"] |
| 420 | |
| 421 | |
| 422 | def test_parse_hackernews_response_engagement_boost(): |
| 423 | """Test that high-engagement items get relevance boost.""" |
| 424 | high = hackernews.parse_hackernews_response( |
| 425 | {"hits": [create_mock_hit(object_id="story", points=500, num_comments=5)]}, |
| 426 | query="", |
| 427 | )[0] |
| 428 | low = hackernews.parse_hackernews_response( |
| 429 | {"hits": [create_mock_hit(object_id="story", points=10, num_comments=5)]}, |
| 430 | query="", |
| 431 | )[0] |
| 432 | |
| 433 | assert high["engagement"]["points"] == 500 |
| 434 | assert low["engagement"]["points"] == 10 |
| 435 | assert high["relevance"] > low["relevance"] |
| 436 | |
| 437 | |
| 438 | def test_parse_hackernews_response_prefix_filtering(): |
| 439 | """Test that items matching only HN prefixes are filtered.""" |
| 440 | response = { |
| 441 | "hits": [ |
| 442 | create_mock_hit(title="Show HN: My AI Project", object_id="1"), |
| 443 | create_mock_hit(title="Show HN: Unrelated Project", object_id="2"), |
| 444 | ] |
| 445 | } |
| 446 | |
| 447 | # Query for "AI" should keep first, filter second |
| 448 | items = hackernews.parse_hackernews_response(response, query="AI") |
| 449 | |
| 450 | assert len(items) == 1 |
| 451 | assert items[0]["id"] == "1" |
| 452 | |
| 453 | |
| 454 | def test_parse_hackernews_response_empty_response(): |
| 455 | """Test handling of empty response.""" |
| 456 | response = {"hits": []} |
| 457 | |
| 458 | items = hackernews.parse_hackernews_response(response) |
| 459 | |
| 460 | assert items == [] |
| 461 | |
| 462 | # === Tests for engagement scoring === |
| 463 | |
| 464 | |
| 465 | def test_engagement_score_calculation(): |
| 466 | """Test that engagement dict contains points and comments.""" |
| 467 | response = { |
| 468 | "hits": [create_mock_hit(points=150, num_comments=75)] |
| 469 | } |
| 470 | |
| 471 | items = hackernews.parse_hackernews_response(response) |
| 472 | |
| 473 | engagement = items[0]["engagement"] |
| 474 | assert engagement["points"] == 150 |
| 475 | assert engagement["comments"] == 75 |
| 476 | |
| 477 | |
| 478 | def test_engagement_score_zero_values(): |
| 479 | """Test handling of zero engagement values.""" |
| 480 | response = { |
| 481 | "hits": [{ |
| 482 | "objectID": "123", |
| 483 | "title": "Test", |
| 484 | "points": None, |
| 485 | "num_comments": None, |
| 486 | }] |
| 487 | } |
| 488 | |
| 489 | items = hackernews.parse_hackernews_response(response) |
| 490 | |
| 491 | engagement = items[0]["engagement"] |
| 492 | assert engagement["points"] == 0 |
| 493 | assert engagement["comments"] == 0 |
| 494 | |
| 495 | |
| 496 | @pytest.mark.parametrize("points", [None, 0]) |
| 497 | @patch("lib.hackernews.http.request") |
| 498 | def test_fetch_item_comments_preserves_absent_and_zero_points(mock_request, points): |
| 499 | """The adapter must distinguish an unmeasured score from a measured zero.""" |
| 500 | mock_request.return_value = { |
| 501 | "children": [ |
| 502 | { |
| 503 | "author": "alice", |
| 504 | "text": "A useful comment.", |
| 505 | "points": points, |
| 506 | } |
| 507 | ] |
| 508 | } |
| 509 | |
| 510 | result = hackernews._fetch_item_comments("123") |
| 511 | |
| 512 | assert result["comments"][0]["points"] is points |
| 513 | |
| 514 | |
| 515 | # === Pipeline wiring === |
| 516 | |
| 517 | |
| 518 | @patch("lib.hackernews.http.request") |
| 519 | def test_pipeline_hackernews_stream_attaches_top_comments(mock_request): |
| 520 | """The HN stream must enrich top stories with comments (#1168).""" |
| 521 | from lib import pipeline, schema |
| 522 | |
| 523 | def fake_request(method, url, **kwargs): |
| 524 | if url.startswith(hackernews.ALGOLIA_ITEM_URL): |
| 525 | return { |
| 526 | "children": [ |
| 527 | {"author": "alice", "text": "<p>Great launch.</p>", "points": 7}, |
| 528 | ] |
| 529 | } |
| 530 | return { |
| 531 | "hits": [ |
| 532 | create_mock_hit(object_id="1", title="Widget launch", points=300), |
| 533 | create_mock_hit(object_id="2", title="Widget review", points=50), |
| 534 | ] |
| 535 | } |
| 536 | |
| 537 | mock_request.side_effect = fake_request |
| 538 | subquery = schema.SubQuery( |
| 539 | label="primary", |
| 540 | search_query="widget", |
| 541 | ranking_query="widget", |
| 542 | sources=["hackernews"], |
| 543 | ) |
| 544 | |
| 545 | items, _ = pipeline._retrieve_stream_impl( |
| 546 | topic="widget", |
| 547 | subquery=subquery, |
| 548 | source="hackernews", |
| 549 | config={}, |
| 550 | depth="quick", |
| 551 | date_range=("2026-08-24", "2026-09-23"), |
| 552 | runtime=schema.ProviderRuntime( |
| 553 | reasoning_provider="none", |
| 554 | planner_model="none", |
| 555 | rerank_model="none", |
| 556 | ), |
| 557 | mock=False, |
| 558 | ) |
| 559 | |
| 560 | by_id = {item["id"]: item for item in items} |
| 561 | assert by_id["1"]["top_comments"] == [ |
| 562 | { |
| 563 | "author": "alice", |
| 564 | "text": "Great launch.", |
| 565 | "points": 7, |
| 566 | # No Algolia child id, so the link is the story's discussion page. |
| 567 | "url": "https://news.ycombinator.com/item?id=1", |
| 568 | } |
| 569 | ] |
| 570 | assert by_id["1"]["comment_insights"] == ["Great launch."] |
| 571 | item_urls = [ |
| 572 | call.args[1] for call in mock_request.call_args_list |
| 573 | if call.args[1].startswith(hackernews.ALGOLIA_ITEM_URL) |
| 574 | ] |
| 575 | assert sorted(item_urls) == [ |
| 576 | f"{hackernews.ALGOLIA_ITEM_URL}/1", |
| 577 | f"{hackernews.ALGOLIA_ITEM_URL}/2", |
| 578 | ] |
| 579 | |
| 580 | |
| 581 | @patch("lib.http.time.sleep") |
| 582 | @patch("lib.http.urllib.request.urlopen") |
| 583 | @patch("lib.hackernews.search_hackernews") |
| 584 | def test_pipeline_hackernews_reports_failed_comment_enrichment( |
| 585 | mock_search, mock_urlopen, _mock_sleep |
| 586 | ): |
| 587 | """Rate-limited item fetches keep the stories but surface in the outcome.""" |
| 588 | import urllib.error |
| 589 | |
| 590 | from lib import pipeline, schema |
| 591 | |
| 592 | mock_search.return_value = { |
| 593 | "hits": [ |
| 594 | create_mock_hit(object_id="1", title="Widget launch", points=300), |
| 595 | create_mock_hit(object_id="2", title="Widget review", points=50), |
| 596 | ] |
| 597 | } |
| 598 | mock_urlopen.side_effect = urllib.error.HTTPError( |
| 599 | hackernews.ALGOLIA_ITEM_URL, 429, "Too Many Requests", {}, None |
| 600 | ) |
| 601 | subquery = schema.SubQuery( |
| 602 | label="primary", |
| 603 | search_query="widget", |
| 604 | ranking_query="widget", |
| 605 | sources=["hackernews"], |
| 606 | ) |
| 607 | |
| 608 | items, artifact = pipeline._retrieve_stream( |
| 609 | topic="widget", |
| 610 | subquery=subquery, |
| 611 | source="hackernews", |
| 612 | config={}, |
| 613 | depth="quick", |
| 614 | date_range=("2026-08-24", "2026-09-23"), |
| 615 | runtime=schema.ProviderRuntime( |
| 616 | reasoning_provider="none", |
| 617 | planner_model="none", |
| 618 | rerank_model="none", |
| 619 | ), |
| 620 | mock=False, |
| 621 | ) |
| 622 | |
| 623 | assert sorted(item["id"] for item in items) == ["1", "2"] |
| 624 | assert all(item["top_comments"] == [] for item in items) |
| 625 | assert "_source_outcome" not in artifact |
| 626 | assert "2 sub-requests rate-limited (HTTP 429)" in artifact["_source_outcome_detail"] |
| 627 | assert artifact["_source_outcome_detail_state"] == schema.RATE_LIMITED |
| 628 | |
| 629 | |
| 630 | # === HN kids ordering (#1285) === |
| 631 | |
| 632 | |
| 633 | @patch("lib.hackernews.http.request") |
| 634 | def test_fetch_item_comments_orders_by_firebase_kids(mock_request): |
| 635 | """Quoted comments follow HN thread order, not Algolia child / id order.""" |
| 636 | |
| 637 | def fake_request(method, url, **kwargs): |
| 638 | if url.startswith(hackernews.FIREBASE_ITEM_URL): |
| 639 | # HN ranks B then A then C; Algolia listed them A, B, C (id order). |
| 640 | return {"kids": [2, 1, 3]} |
| 641 | if url.startswith(hackernews.ALGOLIA_ITEM_URL): |
| 642 | return { |
| 643 | "children": [ |
| 644 | {"id": 1, "author": "alice", "text": "<p>First posted.</p>", "points": None}, |
| 645 | {"id": 2, "author": "bob", "text": "<p>Top-ranked reply.</p>", "points": None}, |
| 646 | {"id": 3, "author": "carol", "text": "<p>Third.</p>", "points": None}, |
| 647 | ] |
| 648 | } |
| 649 | raise AssertionError(f"unexpected url: {url}") |
| 650 | |
| 651 | mock_request.side_effect = fake_request |
| 652 | result = hackernews._fetch_item_comments("50019911", max_comments=2) |
| 653 | |
| 654 | assert [c["author"] for c in result["comments"]] == ["bob", "alice"] |
| 655 | assert result["comments"][0]["url"] == "https://news.ycombinator.com/item?id=2" |
| 656 | |
| 657 | |
| 658 | @patch("lib.hackernews.http.request") |
| 659 | def test_fetch_item_comments_falls_back_to_points_when_kids_unavailable(mock_request): |
| 660 | """If the Firebase kids fetch fails, keep the previous points ordering.""" |
| 661 | |
| 662 | def fake_request(method, url, **kwargs): |
| 663 | if url.startswith(hackernews.FIREBASE_ITEM_URL): |
| 664 | raise hackernews.http.HTTPError("firebase down", status_code=503) |
| 665 | return { |
| 666 | "children": [ |
| 667 | {"id": 1, "author": "alice", "text": "low", "points": 1}, |
| 668 | {"id": 2, "author": "bob", "text": "high", "points": 9}, |
| 669 | ] |
| 670 | } |
| 671 | |
| 672 | mock_request.side_effect = fake_request |
| 673 | result = hackernews._fetch_item_comments("123", max_comments=2) |
| 674 | assert [c["author"] for c in result["comments"]] == ["bob", "alice"] |
| 675 | |
| 676 | |
| 677 | def test_order_comments_by_kids_appends_unknowns(): |
| 678 | comments = [ |
| 679 | {"id": 1, "author": "a"}, |
| 680 | {"id": 2, "author": "b"}, |
| 681 | {"id": 99, "author": "extra"}, |
| 682 | ] |
| 683 | ordered = hackernews._order_comments_by_kids(comments, [2, 1]) |
| 684 | assert [c["id"] for c in ordered] == [2, 1, 99] |
| 685 | |
| 686 | |
| 687 | @patch("lib.http.time.sleep") |
| 688 | @patch("lib.http.urllib.request.urlopen") |
| 689 | def test_firebase_kids_failure_stays_out_of_failure_sink(mock_urlopen, _mock_sleep): |
| 690 | """A Firebase outage keeps the Algolia comments and records no run failure.""" |
| 691 | import urllib.error |
| 692 | |
| 693 | from lib import http as lib_http |
| 694 | |
| 695 | algolia_body = json.dumps({ |
| 696 | "children": [ |
| 697 | {"id": 1, "author": "alice", "text": "low", "points": 1}, |
| 698 | {"id": 2, "author": "bob", "text": "high", "points": 9}, |
| 699 | ] |
| 700 | }).encode("utf-8") |
| 701 | firebase_calls = [] |
| 702 | |
| 703 | def fake_urlopen(req, timeout=None): |
| 704 | url = req.full_url |
| 705 | if url.startswith(hackernews.FIREBASE_ITEM_URL): |
| 706 | firebase_calls.append(url) |
| 707 | raise urllib.error.HTTPError(url, 503, "Service Unavailable", {}, None) |
| 708 | response = MagicMock() |
| 709 | response.__enter__.return_value = response |
| 710 | response.__exit__.return_value = False |
| 711 | response.read.return_value = algolia_body |
| 712 | response.status = 200 |
| 713 | return response |
| 714 | |
| 715 | mock_urlopen.side_effect = fake_urlopen |
| 716 | with lib_http.capture_failures() as failures: |
| 717 | result = hackernews._fetch_item_comments("123", max_comments=2) |
| 718 | |
| 719 | assert firebase_calls |
| 720 | assert failures == [] |
| 721 | assert [c["author"] for c in result["comments"]] == ["bob", "alice"] |
| 722 | |
| 723 | |
| 724 | |
| 725 | @pytest.mark.parametrize("firebase_read", ["incomplete", "non_utf8"]) |
| 726 | @patch("lib.http.time.sleep") |
| 727 | @patch("lib.http.urllib.request.urlopen") |
| 728 | def test_firebase_kids_unwrapped_read_errors_fall_back(mock_urlopen, _mock_sleep, firebase_read): |
| 729 | """A truncated or undecodable Firebase body keeps the Algolia comments.""" |
| 730 | import http.client |
| 731 | |
| 732 | from lib import http as lib_http |
| 733 | |
| 734 | algolia_body = json.dumps({ |
| 735 | "children": [ |
| 736 | {"id": 1, "author": "alice", "text": "low", "points": 1}, |
| 737 | {"id": 2, "author": "bob", "text": "high", "points": 9}, |
| 738 | ] |
| 739 | }).encode("utf-8") |
| 740 | |
| 741 | def fake_urlopen(req, timeout=None): |
| 742 | response = MagicMock() |
| 743 | response.__enter__.return_value = response |
| 744 | response.__exit__.return_value = False |
| 745 | response.status = 200 |
| 746 | if req.full_url.startswith(hackernews.FIREBASE_ITEM_URL): |
| 747 | if firebase_read == "incomplete": |
| 748 | response.read.side_effect = http.client.IncompleteRead(b'{"kids": [1') |
| 749 | else: |
| 750 | response.read.return_value = b"\xff\xfe" |
| 751 | else: |
| 752 | response.read.return_value = algolia_body |
| 753 | return response |
| 754 | |
| 755 | mock_urlopen.side_effect = fake_urlopen |
| 756 | with lib_http.capture_failures() as failures: |
| 757 | result = hackernews._fetch_item_comments("123", max_comments=2) |
| 758 | |
| 759 | assert failures == [] |
| 760 | assert [c["author"] for c in result["comments"]] == ["bob", "alice"] |
| 761 | |
| 762 | |
| 763 | |
| 764 | @patch("lib.http.time.sleep") |
| 765 | @patch("lib.http.urllib.request.urlopen") |
| 766 | def test_firebase_kids_timeouts_are_bounded(mock_urlopen, _mock_sleep): |
| 767 | """A hanging Firebase gets a short retry budget, not the default five attempts.""" |
| 768 | from lib import http as lib_http |
| 769 | |
| 770 | algolia_body = json.dumps({ |
| 771 | "children": [ |
| 772 | {"id": 1, "author": "alice", "text": "low", "points": 1}, |
| 773 | {"id": 2, "author": "bob", "text": "high", "points": 9}, |
| 774 | ] |
| 775 | }).encode("utf-8") |
| 776 | firebase_timeouts = [] |
| 777 | |
| 778 | def fake_urlopen(req, timeout=None): |
| 779 | if req.full_url.startswith(hackernews.FIREBASE_ITEM_URL): |
| 780 | firebase_timeouts.append(timeout) |
| 781 | raise TimeoutError("timed out") |
| 782 | response = MagicMock() |
| 783 | response.__enter__.return_value = response |
| 784 | response.__exit__.return_value = False |
| 785 | response.status = 200 |
| 786 | response.read.return_value = algolia_body |
| 787 | return response |
| 788 | |
| 789 | mock_urlopen.side_effect = fake_urlopen |
| 790 | with lib_http.capture_failures() as failures: |
| 791 | result = hackernews._fetch_item_comments("123", max_comments=2) |
| 792 | |
| 793 | assert 1 <= len(firebase_timeouts) <= hackernews.FIREBASE_KIDS_RETRIES |
| 794 | assert all(t <= hackernews.FIREBASE_KIDS_TIMEOUT for t in firebase_timeouts) |
| 795 | assert failures == [] |
| 796 | assert [c["author"] for c in result["comments"]] == ["bob", "alice"] |
| 797 | |
| 798 | |
| 799 | if __name__ == "__main__": |
| 800 | pytest.main([__file__, "-v"]) |
| 801 |