337 lines
12 KiB
Python
337 lines
12 KiB
Python
|
|
"""Integration tests for GET /api/news/blips (per-article proximate geo).
|
||
|
|
|
||
|
|
DB-backed: marked `requires_db` and auto-skip when the test database is
|
||
|
|
unreachable (see tests/conftest.py). Seeding writes directly to `articles`
|
||
|
|
and `article_scores`, exactly as the summarizer's persist step would.
|
||
|
|
|
||
|
|
Frozen wire contract (card t_bc15eb53):
|
||
|
|
200 -> JSON array, EXACT keys: id, headline, url, domain, location_name,
|
||
|
|
lat, lon, location_confidence, category, score, created_at.
|
||
|
|
Only finite lat/lon; created_at DESC; dedup by article id (latest wins).
|
||
|
|
"""
|
||
|
|
|
||
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import asyncio
|
||
|
|
import math
|
||
|
|
import os
|
||
|
|
from datetime import datetime, timedelta, timezone
|
||
|
|
from urllib.parse import quote
|
||
|
|
|
||
|
|
import asyncpg
|
||
|
|
import httpx
|
||
|
|
import pytest
|
||
|
|
|
||
|
|
from conftest import requires_db
|
||
|
|
|
||
|
|
from main import app
|
||
|
|
|
||
|
|
BASE = "http://test"
|
||
|
|
|
||
|
|
CONTRACT_KEYS = {
|
||
|
|
"id", "headline", "url", "domain", "location_name",
|
||
|
|
"lat", "lon", "location_confidence", "category", "score", "created_at",
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
def _conn_kwargs() -> dict:
|
||
|
|
return {
|
||
|
|
"host": os.environ["DB_HOST"],
|
||
|
|
"port": int(os.environ["DB_PORT"]),
|
||
|
|
"user": os.environ["DB_USER"],
|
||
|
|
"password": os.environ["DB_PASSWORD"],
|
||
|
|
"database": os.environ["DB_NAME"],
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
def _run(coro):
|
||
|
|
return asyncio.run(coro)
|
||
|
|
|
||
|
|
|
||
|
|
def _truncate() -> None:
|
||
|
|
async def run():
|
||
|
|
conn = await asyncpg.connect(**_conn_kwargs())
|
||
|
|
try:
|
||
|
|
await conn.execute("TRUNCATE articles, article_scores CASCADE")
|
||
|
|
finally:
|
||
|
|
await conn.close()
|
||
|
|
|
||
|
|
_run(run())
|
||
|
|
|
||
|
|
|
||
|
|
@pytest.fixture()
|
||
|
|
def clean_blips():
|
||
|
|
_truncate()
|
||
|
|
yield
|
||
|
|
_truncate()
|
||
|
|
|
||
|
|
|
||
|
|
def _seed_article(title: str, url: str | None, domain: str | None) -> int:
|
||
|
|
async def run() -> int:
|
||
|
|
conn = await asyncpg.connect(**_conn_kwargs())
|
||
|
|
try:
|
||
|
|
row = await conn.fetchrow(
|
||
|
|
"INSERT INTO articles (title, url, content, domain, timestamp) "
|
||
|
|
"VALUES ($1, $2, $3, $4, $5) RETURNING id",
|
||
|
|
title, url, "body text " * 20, domain,
|
||
|
|
datetime.now(timezone.utc),
|
||
|
|
)
|
||
|
|
return int(row["id"])
|
||
|
|
finally:
|
||
|
|
await conn.close()
|
||
|
|
|
||
|
|
return _run(run())
|
||
|
|
|
||
|
|
|
||
|
|
def _seed_score(
|
||
|
|
article_id: int,
|
||
|
|
*,
|
||
|
|
score: int = 50,
|
||
|
|
category: str | None = "politics",
|
||
|
|
location_name: str | None = "Kyiv, Ukraine",
|
||
|
|
lat: float | None = 50.45,
|
||
|
|
lon: float | None = 30.52,
|
||
|
|
location_confidence: str | None = "city",
|
||
|
|
created_at: datetime | None = None,
|
||
|
|
) -> None:
|
||
|
|
async def run():
|
||
|
|
conn = await asyncpg.connect(**_conn_kwargs())
|
||
|
|
try:
|
||
|
|
await conn.execute(
|
||
|
|
"INSERT INTO article_scores "
|
||
|
|
"(article_id, summary_id, score, category, selected, model, "
|
||
|
|
" duplicate_of, location_name, lat, lon, location_confidence, created_at) "
|
||
|
|
"VALUES ($1, NULL, $2, $3, false, 'test-model', NULL, $4, $5, $6, $7, $8)",
|
||
|
|
article_id, score, category, location_name, lat, lon,
|
||
|
|
location_confidence,
|
||
|
|
created_at or datetime.now(timezone.utc),
|
||
|
|
)
|
||
|
|
finally:
|
||
|
|
await conn.close()
|
||
|
|
|
||
|
|
_run(run())
|
||
|
|
|
||
|
|
|
||
|
|
async def _get(path: str) -> httpx.Response:
|
||
|
|
transport = httpx.ASGITransport(app=app)
|
||
|
|
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
|
||
|
|
return await client.get(path)
|
||
|
|
|
||
|
|
|
||
|
|
def _get_sync(path: str) -> httpx.Response:
|
||
|
|
return _run(_get(path))
|
||
|
|
|
||
|
|
|
||
|
|
@requires_db
|
||
|
|
def test_blips_exact_contract_keys(clean_blips):
|
||
|
|
aid = _seed_article("Strike in Kyiv", "https://ex.com/1", "ex.com")
|
||
|
|
_seed_score(aid, score=82)
|
||
|
|
resp = _get_sync("/api/news/blips")
|
||
|
|
assert resp.status_code == 200
|
||
|
|
rows = resp.json()
|
||
|
|
assert len(rows) == 1
|
||
|
|
row = rows[0]
|
||
|
|
assert set(row.keys()) == CONTRACT_KEYS
|
||
|
|
assert row["id"] == aid
|
||
|
|
assert row["headline"] == "Strike in Kyiv"
|
||
|
|
assert row["url"] == "https://ex.com/1"
|
||
|
|
assert row["domain"] == "ex.com"
|
||
|
|
assert row["location_name"] == "Kyiv, Ukraine"
|
||
|
|
assert row["lat"] == pytest.approx(50.45)
|
||
|
|
assert row["lon"] == pytest.approx(30.52)
|
||
|
|
assert row["location_confidence"] == "city"
|
||
|
|
assert row["category"] == "politics"
|
||
|
|
assert row["score"] == 82
|
||
|
|
assert isinstance(row["created_at"], str)
|
||
|
|
datetime.fromisoformat(row["created_at"]) # ISO8601 parseable
|
||
|
|
|
||
|
|
|
||
|
|
@requires_db
|
||
|
|
def test_blips_nullable_fields(clean_blips):
|
||
|
|
aid = _seed_article("Untitled", None, None)
|
||
|
|
_seed_score(
|
||
|
|
aid, category=None, location_name=None, location_confidence=None,
|
||
|
|
lat=10.0, lon=20.0,
|
||
|
|
)
|
||
|
|
row = _get_sync("/api/news/blips").json()[0]
|
||
|
|
assert row["url"] is None
|
||
|
|
assert row["domain"] is None
|
||
|
|
assert row["location_name"] is None
|
||
|
|
assert row["location_confidence"] is None
|
||
|
|
assert row["category"] is None
|
||
|
|
assert row["headline"] == "Untitled"
|
||
|
|
|
||
|
|
|
||
|
|
@requires_db
|
||
|
|
def test_blips_dedup_by_article_id_latest_geo_wins(clean_blips):
|
||
|
|
aid = _seed_article("Regraded story", "https://ex.com/r", "ex.com")
|
||
|
|
now = datetime.now(timezone.utc)
|
||
|
|
_seed_score(
|
||
|
|
aid, lat=1.0, lon=2.0, location_name="Old place",
|
||
|
|
location_confidence="approx", created_at=now - timedelta(hours=3),
|
||
|
|
)
|
||
|
|
_seed_score(
|
||
|
|
aid, lat=50.45, lon=30.52, location_name="Kyiv",
|
||
|
|
location_confidence="city", created_at=now - timedelta(hours=1),
|
||
|
|
)
|
||
|
|
rows = _get_sync("/api/news/blips").json()
|
||
|
|
assert len(rows) == 1
|
||
|
|
assert rows[0]["id"] == aid
|
||
|
|
assert rows[0]["location_name"] == "Kyiv"
|
||
|
|
assert rows[0]["lat"] == pytest.approx(50.45)
|
||
|
|
assert rows[0]["location_confidence"] == "city"
|
||
|
|
|
||
|
|
|
||
|
|
@requires_db
|
||
|
|
def test_blips_dedup_latest_geo_wins_even_if_newer_row_has_none(clean_blips):
|
||
|
|
"""Latest grading without geo: the newest FINITE-geo row still blips.
|
||
|
|
|
||
|
|
The contract filters to finite lat/lon rows first, then dedups by id
|
||
|
|
(latest geo wins) — a coord-less re-grade does not erase an article's
|
||
|
|
last known location.
|
||
|
|
"""
|
||
|
|
aid = _seed_article("Keeps its place", "https://ex.com/x", "ex.com")
|
||
|
|
now = datetime.now(timezone.utc)
|
||
|
|
_seed_score(aid, lat=50.45, lon=30.52, created_at=now - timedelta(hours=3))
|
||
|
|
_seed_score(
|
||
|
|
aid, lat=None, lon=None, location_name=None,
|
||
|
|
location_confidence=None, created_at=now - timedelta(hours=1),
|
||
|
|
)
|
||
|
|
rows = _get_sync("/api/news/blips").json()
|
||
|
|
assert len(rows) == 1
|
||
|
|
assert rows[0]["id"] == aid
|
||
|
|
assert rows[0]["lat"] == pytest.approx(50.45)
|
||
|
|
|
||
|
|
|
||
|
|
@requires_db
|
||
|
|
def test_blips_only_finite_coords(clean_blips):
|
||
|
|
now = datetime.now(timezone.utc)
|
||
|
|
good = _seed_article("Good", "https://ex.com/g", "ex.com")
|
||
|
|
_seed_score(good, created_at=now)
|
||
|
|
bad_cases = [
|
||
|
|
{"lat": None, "lon": None},
|
||
|
|
{"lat": float("nan"), "lon": 30.52},
|
||
|
|
{"lat": 50.45, "lon": float("nan")},
|
||
|
|
{"lat": float("inf"), "lon": 30.52},
|
||
|
|
{"lat": 50.45, "lon": float("-inf")},
|
||
|
|
{"lat": 91.0, "lon": 30.52},
|
||
|
|
{"lat": 50.45, "lon": 181.0},
|
||
|
|
]
|
||
|
|
for i, geo in enumerate(bad_cases):
|
||
|
|
aid = _seed_article(f"Bad {i}", f"https://ex.com/b{i}", "ex.com")
|
||
|
|
_seed_score(aid, created_at=now - timedelta(minutes=i + 1), **geo)
|
||
|
|
rows = _get_sync("/api/news/blips").json()
|
||
|
|
assert [r["id"] for r in rows] == [good]
|
||
|
|
assert all(math.isfinite(r["lat"]) and math.isfinite(r["lon"]) for r in rows)
|
||
|
|
|
||
|
|
|
||
|
|
@requires_db
|
||
|
|
def test_blips_includes_non_critical_articles(clean_blips):
|
||
|
|
"""No importance/score filter: low-scored graded articles are blips too."""
|
||
|
|
now = datetime.now(timezone.utc)
|
||
|
|
ids = []
|
||
|
|
for i, score in enumerate((95, 78, 50, 30, 12)):
|
||
|
|
aid = _seed_article(f"Story {score}", f"https://ex.com/{i}", "ex.com")
|
||
|
|
_seed_score(aid, score=score, created_at=now - timedelta(minutes=i))
|
||
|
|
ids.append(aid)
|
||
|
|
rows = _get_sync("/api/news/blips").json()
|
||
|
|
assert {r["id"] for r in rows} == set(ids)
|
||
|
|
assert {r["score"] for r in rows} == {95, 78, 50, 30, 12}
|
||
|
|
|
||
|
|
|
||
|
|
@requires_db
|
||
|
|
def test_blips_order_created_at_desc(clean_blips):
|
||
|
|
now = datetime.now(timezone.utc)
|
||
|
|
ids = []
|
||
|
|
for i in range(4):
|
||
|
|
aid = _seed_article(f"Story {i}", f"https://ex.com/{i}", "ex.com")
|
||
|
|
_seed_score(aid, created_at=now - timedelta(hours=i + 1))
|
||
|
|
ids.append(aid)
|
||
|
|
rows = _get_sync("/api/news/blips").json()
|
||
|
|
assert [r["id"] for r in rows] == ids # newest first
|
||
|
|
stamps = [datetime.fromisoformat(r["created_at"]) for r in rows]
|
||
|
|
assert stamps == sorted(stamps, reverse=True)
|
||
|
|
|
||
|
|
|
||
|
|
@requires_db
|
||
|
|
def test_blips_bbox_filter(clean_blips):
|
||
|
|
now = datetime.now(timezone.utc)
|
||
|
|
kyiv = _seed_article("Kyiv story", "https://ex.com/k", "ex.com")
|
||
|
|
_seed_score(kyiv, lat=50.45, lon=30.52, created_at=now)
|
||
|
|
sydney = _seed_article("Sydney story", "https://ex.com/s", "ex.com")
|
||
|
|
_seed_score(sydney, lat=-33.87, lon=151.21, created_at=now)
|
||
|
|
rows = _get_sync("/api/news/blips?bbox=20,40,40,60").json()
|
||
|
|
assert [r["id"] for r in rows] == [kyiv]
|
||
|
|
rows = _get_sync("/api/news/blips?bbox=-180,-90,180,90").json()
|
||
|
|
assert {r["id"] for r in rows} == {kyiv, sydney}
|
||
|
|
assert _get_sync("/api/news/blips?bbox=0,0,1,1").json() == []
|
||
|
|
|
||
|
|
|
||
|
|
@requires_db
|
||
|
|
@pytest.mark.parametrize(
|
||
|
|
"bbox",
|
||
|
|
["1,2,3", "1,2,3,4,5", "a,b,c,d", "1,2,,4", "1,2,3,"],
|
||
|
|
)
|
||
|
|
def test_blips_bbox_malformed_422(clean_blips, bbox):
|
||
|
|
resp = _get_sync(f"/api/news/blips?bbox={bbox}")
|
||
|
|
assert resp.status_code == 422
|
||
|
|
|
||
|
|
|
||
|
|
@requires_db
|
||
|
|
def test_blips_bbox_empty_is_omitted(clean_blips):
|
||
|
|
"""Same semantics as /api/news/map: an empty bbox means 'no filter'."""
|
||
|
|
aid = _seed_article("Any place", "https://ex.com/a", "ex.com")
|
||
|
|
_seed_score(aid)
|
||
|
|
assert _get_sync("/api/news/blips?bbox=").status_code == 200
|
||
|
|
assert len(_get_sync("/api/news/blips?bbox=").json()) == 1
|
||
|
|
|
||
|
|
|
||
|
|
@requires_db
|
||
|
|
def test_blips_since_honored(clean_blips):
|
||
|
|
now = datetime.now(timezone.utc)
|
||
|
|
fresh = _seed_article("Fresh", "https://ex.com/f", "ex.com")
|
||
|
|
_seed_score(fresh, created_at=now - timedelta(hours=1))
|
||
|
|
stale = _seed_article("Stale", "https://ex.com/s", "ex.com")
|
||
|
|
_seed_score(stale, created_at=now - timedelta(hours=30))
|
||
|
|
# Default window is 24h: the 30h-old row is out.
|
||
|
|
rows = _get_sync("/api/news/blips").json()
|
||
|
|
assert [r["id"] for r in rows] == [fresh]
|
||
|
|
# Explicit since widens the window.
|
||
|
|
since = quote((now - timedelta(hours=48)).isoformat())
|
||
|
|
rows = _get_sync(f"/api/news/blips?since={since}").json()
|
||
|
|
assert {r["id"] for r in rows} == {fresh, stale}
|
||
|
|
# Explicit since narrows it.
|
||
|
|
since = quote((now - timedelta(minutes=30)).isoformat())
|
||
|
|
assert _get_sync(f"/api/news/blips?since={since}").json() == []
|
||
|
|
|
||
|
|
|
||
|
|
@requires_db
|
||
|
|
def test_blips_limit_honored_and_validated(clean_blips):
|
||
|
|
now = datetime.now(timezone.utc)
|
||
|
|
for i in range(5):
|
||
|
|
aid = _seed_article(f"Story {i}", f"https://ex.com/{i}", "ex.com")
|
||
|
|
_seed_score(aid, created_at=now - timedelta(minutes=i))
|
||
|
|
rows = _get_sync("/api/news/blips?limit=2").json()
|
||
|
|
assert len(rows) == 2
|
||
|
|
assert _get_sync("/api/news/blips?limit=0").status_code == 422
|
||
|
|
assert _get_sync("/api/news/blips?limit=5001").status_code == 422
|
||
|
|
assert _get_sync("/api/news/blips?limit=abc").status_code == 422
|
||
|
|
# Max boundary is accepted.
|
||
|
|
assert _get_sync("/api/news/blips?limit=5000").status_code == 200
|
||
|
|
|
||
|
|
|
||
|
|
@requires_db
|
||
|
|
def test_blips_empty_db_returns_empty_array(clean_blips):
|
||
|
|
resp = _get_sync("/api/news/blips")
|
||
|
|
assert resp.status_code == 200
|
||
|
|
assert resp.json() == []
|
||
|
|
|
||
|
|
|
||
|
|
@requires_db
|
||
|
|
def test_news_map_unchanged_by_blips(clean_blips):
|
||
|
|
"""Critical-pin layer keeps its own contract while blips exist."""
|
||
|
|
aid = _seed_article("Critical story", "https://ex.com/c", "ex.com")
|
||
|
|
_seed_score(aid, score=95)
|
||
|
|
resp = _get_sync("/api/news/map")
|
||
|
|
assert resp.status_code == 200
|
||
|
|
assert resp.json() == [] # no news_items seeded; blips do not leak in
|