"""News spider/pipeline: skip audio, use pubDate, don't log dupes as errors.""" from __future__ import annotations import datetime as _dt import sys from pathlib import Path import pytest ROOT = Path(__file__).resolve().parent.parent _SCRAPER = ROOT / "news/scraper" if str(_SCRAPER) not in sys.path: sys.path.insert(0, str(_SCRAPER)) def test_is_audio_enclosure(): from newsScraper.feed_util import is_audio_url assert is_audio_url("https://cdn.example/podcast.mp3") is True assert is_audio_url("https://cdn.example/show.m4a?x=1") is True assert is_audio_url("https://www.example.com/world/story") is False def test_article_timestamp_prefers_pubdate(): from newsScraper.feed_util import article_timestamp ts = article_timestamp("Tue, 01 Apr 2025 12:00:00 GMT") assert ts.tzinfo is not None assert ts.year == 2025 assert ts.month == 4 assert ts.day == 1 def test_pipeline_does_not_wrap_dropitem_as_error(): src = (ROOT / "news/scraper/newsScraper/pipelines.py").read_text() assert "except DropItem" in src assert "seen_urls.add" in src or "self.seen_urls.add" in src def test_spider_skips_audio_before_request(): src = (ROOT / "news/scraper/newsScraper/spiders/news_spider.py").read_text() assert "is_audio_url" in src assert "article_timestamp" in src assert "datetime.datetime.now()" not in src # ── future-dated guard (ingest) ─────────────────────────────────────────── class _FakeCursor: rowcount = 1 def __init__(self): self.executed = [] def execute(self, sql, params=None): self.executed.append((sql, params)) class _FakeConnection: def commit(self): pass def rollback(self): pass class _FakeStats: def __init__(self): self.values = {} def inc_value(self, key, count=1): self.values[key] = self.values.get(key, 0) + count class _FakeSpider: class _Logger: def info(self, *a, **kw): pass def error(self, *a, **kw): pass def __init__(self): self.logger = self._Logger() self.crawler = type("C", (), {"stats": _FakeStats()})() def _pipeline(): from newsScraper.pipelines import PostgresPipeline pipe = PostgresPipeline(db_config={}) pipe.cur = _FakeCursor() pipe.connection = _FakeConnection() return pipe def _item(ts: _dt.datetime) -> dict: return { "title": "t", "url": f"https://a.example/{ts.isoformat()}", "text": "body", "domain": "a.example", "timestamp": ts.isoformat(), } def test_pipeline_drops_future_dated_item(): from scrapy.exceptions import DropItem pipe = _pipeline() spider = _FakeSpider() future = _dt.datetime.now(_dt.timezone.utc) + _dt.timedelta(days=5) with pytest.raises(DropItem): pipe.process_item(_item(future), spider) assert pipe.future_dated_dropped == 1 assert spider.crawler.stats.values["future_dated_dropped"] == 1 assert pipe.cur.executed == [] # never reached the INSERT def test_pipeline_keeps_recent_item(): pipe = _pipeline() spider = _FakeSpider() recent = _dt.datetime.now(_dt.timezone.utc) - _dt.timedelta(days=1) assert pipe.process_item(_item(recent), spider)["domain"] == "a.example" assert pipe.future_dated_dropped == 0 assert len(pipe.cur.executed) == 1 def test_pipeline_keeps_unparseable_timestamp(): from newsScraper.pipelines import is_future_dated assert is_future_dated("not a date") is False assert is_future_dated(None) is False # ── CDATA title unwrap (ingest) ─────────────────────────────────────────── # Excelsior stores the wrapper as text, including the leading newline the # feed leaves around . A plain title, and real HTML that is # not that wrapper, must pass through unchanged. @pytest.mark.parametrize( "raw,expected", [ ("", "Hello"), ("\n ", "Hello"), ( "\n ", "Hello", ), ("Hello", "Hello"), (" Hello ", " Hello "), ("Hello", "Hello"), ("See ", "See "), (None, None), ], ) def test_unwrap_cdata_title(raw, expected): from newsScraper.feed_util import unwrap_cdata_title assert unwrap_cdata_title(raw) == expected @pytest.mark.parametrize( "raw,expected", [ ("", "Hello"), ("\n ", "Hello"), ("Hello", "Hello"), ("Hello", "Hello"), ], ) def test_pipeline_stores_cdata_title_unwrapped(raw, expected): pipe = _pipeline() spider = _FakeSpider() recent = _dt.datetime.now(_dt.timezone.utc) - _dt.timedelta(hours=1) item = _item(recent) item["title"] = raw returned = pipe.process_item(item, spider) assert returned["title"] == expected stored = pipe.cur.executed[0][1][0] assert stored == expected