| 1 | import unittest |
| 2 | from unittest.mock import patch |
| 3 | |
| 4 | from lib import hackernews |
| 5 | |
| 6 | |
| 7 | class HackerNewsHitIntegrityTest(unittest.TestCase): |
| 8 | def setUp(self): |
| 9 | self.valid = {"objectID": "37", "title": "Python packaging", "points": 25, "num_comments": 4} |
| 10 | self.malformed = {"objectID": "38", "title": "Python notebooks", "points": "unknown", "created_at_i": 10**20} |
| 11 | |
| 12 | def test_mixed_hits_keep_valid_search_results(self): |
| 13 | with patch.object(hackernews.http, "request", return_value={"hits": [None, self.malformed, self.valid]}): |
| 14 | response = hackernews.search_hackernews("Python", "2026-10-01", "2026-10-11") |
| 15 | self.assertEqual([self.valid], response["hits"]) |
| 16 | |
| 17 | def test_discovery_normalizes_optional_fields_and_keeps_other_stories(self): |
| 18 | pages = [{"hits": [None, self.malformed]}, {"hits": [self.valid, {"objectID": "39", "title": None}]}] |
| 19 | with patch.object(hackernews.http, "request", side_effect=pages): |
| 20 | discovery = hackernews.fetch_discovery_listings("2026-10-01", "2026-10-11") |
| 21 | items = {item["id"]: item for item in discovery["items"]} |
| 22 | self.assertEqual({"38", "37"}, set(items)) |
| 23 | self.assertEqual({"points": 0, "comments": 0}, items["38"]["engagement"]) |
| 24 | self.assertIsNone(items["38"]["date"]) |
| 25 | self.assertEqual({"points": 25, "comments": 4}, items["37"]["engagement"]) |
| 26 | |
| 27 | def test_invalid_envelope_is_a_source_error(self): |
| 28 | with patch.object(hackernews.http, "request", return_value={"hits": None}): |
| 29 | response = hackernews.search_hackernews("Python", "2026-10-01", "2026-10-11") |
| 30 | self.assertEqual([], response["hits"]) |
| 31 | self.assertIn("response shape", response["error"]) |
| 32 |