fix(health): ignore future article timestamps; flag unset vessel/FIRMS keys
/api/health articles.age_s used max(timestamp) with no future-date filter, so rows ahead of now() reported a negative age. Use the same closed window as the news list (timestamp <= now(); NULL timestamps are not fresh). If every non-null timestamp is in the future, age_s is null and ok is false. GET /api/stats keeps existing counters and adds feeds.vessels.configured and feeds.fires.configured from non-empty api_keys values only. The stored value is never returned.
This commit is contained in:
parent
d04ddc9afa
commit
02a9a5626b
3 changed files with 192 additions and 4 deletions
|
|
@ -8,7 +8,7 @@ from datetime import timezone
|
|||
|
||||
import httpx
|
||||
|
||||
from main import app, _stats_counts
|
||||
from main import app, _stats_counts, _stats_cache
|
||||
|
||||
BASE = "http://test"
|
||||
|
||||
|
|
@ -84,4 +84,80 @@ def test_stats_db_failure_degrades_to_zero(monkeypatch):
|
|||
assert body["cameras"] == 0
|
||||
assert body["fires"] == 0
|
||||
assert body["quakes"] == 0
|
||||
assert isinstance(body["timestamp"], str)
|
||||
assert isinstance(body["timestamp"], str)
|
||||
|
||||
|
||||
def _clear_stats_cache() -> None:
|
||||
_stats_cache.clear()
|
||||
|
||||
|
||||
def test_stats_feeds_unconfigured_without_keys(monkeypatch):
|
||||
"""No stored AIS/FIRMS key → both flags false; existing counters stay.
|
||||
|
||||
Env vars do not count. The HUD flag is the api_keys store only.
|
||||
"""
|
||||
monkeypatch.setenv("FIRMS_MAP_KEY", "env-firms-should-not-count")
|
||||
monkeypatch.setenv("AISSTREAM_API_KEY", "env-ais-should-not-count")
|
||||
monkeypatch.setenv("VESSELAPI_API_KEY", "env-vessel-should-not-count")
|
||||
|
||||
async def _unset(name: str):
|
||||
if name == "FIRMS_MAP_KEY":
|
||||
return " "
|
||||
return None
|
||||
|
||||
monkeypatch.setattr("keystore.get_api_key", _unset)
|
||||
_clear_stats_cache()
|
||||
resp = asyncio.run(_get("/api/stats"))
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
for key in EXPECTED_KEYS:
|
||||
assert key in body, f"missing key {key}"
|
||||
assert body["feeds"] == {
|
||||
"vessels": {"configured": False},
|
||||
"fires": {"configured": False},
|
||||
}
|
||||
assert "trains" not in body["feeds"]
|
||||
assert "env-firms-should-not-count" not in resp.text
|
||||
assert "env-ais-should-not-count" not in resp.text
|
||||
|
||||
|
||||
def test_stats_feeds_fires_configured_does_not_leak_key(monkeypatch):
|
||||
secret = "firms-map-key-do-not-leak-9f3a2c1b"
|
||||
|
||||
async def _keys(name: str):
|
||||
if name == "FIRMS_MAP_KEY":
|
||||
return secret
|
||||
return None
|
||||
|
||||
monkeypatch.setattr("keystore.get_api_key", _keys)
|
||||
_clear_stats_cache()
|
||||
resp = asyncio.run(_get("/api/stats"))
|
||||
body = resp.json()
|
||||
assert body["feeds"]["fires"]["configured"] is True
|
||||
assert body["feeds"]["vessels"]["configured"] is False
|
||||
assert secret not in resp.text
|
||||
assert secret[-4:] not in resp.text
|
||||
|
||||
|
||||
def test_stats_feeds_vessels_configured_from_either_key(monkeypatch):
|
||||
async def _ais_only(name: str):
|
||||
if name == "AISSTREAM_API_KEY":
|
||||
return "aisstream-stored-value"
|
||||
return None
|
||||
|
||||
monkeypatch.setattr("keystore.get_api_key", _ais_only)
|
||||
_clear_stats_cache()
|
||||
body = asyncio.run(_get("/api/stats")).json()
|
||||
assert body["feeds"]["vessels"]["configured"] is True
|
||||
assert body["feeds"]["fires"]["configured"] is False
|
||||
|
||||
async def _vesselapi_only(name: str):
|
||||
if name == "VESSELAPI_API_KEY":
|
||||
return "vesselapi-stored-value"
|
||||
return ""
|
||||
|
||||
monkeypatch.setattr("keystore.get_api_key", _vesselapi_only)
|
||||
_clear_stats_cache()
|
||||
body = asyncio.run(_get("/api/stats")).json()
|
||||
assert body["feeds"]["vessels"]["configured"] is True
|
||||
assert body["feeds"]["fires"]["configured"] is False
|
||||
|
|
@ -3,12 +3,21 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import asyncpg
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from conftest import requires_db
|
||||
from main import app
|
||||
|
||||
BASE = "http://test"
|
||||
_FIXTURE_URLS = (
|
||||
"https://test.invalid/t_ceb74e64/future",
|
||||
"https://test.invalid/t_ceb74e64/fresh",
|
||||
)
|
||||
|
||||
|
||||
async def _get(path: str) -> httpx.Response:
|
||||
|
|
@ -31,3 +40,67 @@ def test_ready_endpoint_exists():
|
|||
body = resp.json()
|
||||
assert "checks" in body
|
||||
assert "status" in body
|
||||
|
||||
|
||||
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"],
|
||||
}
|
||||
|
||||
|
||||
async def _prepare_article_age_fixture() -> None:
|
||||
"""Insert one row at now+6d and one at now-120s. Deletes only those URLs."""
|
||||
conn = await asyncpg.connect(**_conn_kwargs())
|
||||
try:
|
||||
await conn.execute(
|
||||
"DELETE FROM articles WHERE url = ANY($1::text[])",
|
||||
list(_FIXTURE_URLS),
|
||||
)
|
||||
now = datetime.now(timezone.utc)
|
||||
await conn.executemany(
|
||||
"INSERT INTO articles (title, url, content, domain, timestamp) "
|
||||
"VALUES ($1, $2, $3, $4, $5)",
|
||||
[
|
||||
("future", _FIXTURE_URLS[0], "x", "test.invalid", now + timedelta(days=6)),
|
||||
("fresh", _FIXTURE_URLS[1], "x", "test.invalid", now - timedelta(seconds=120)),
|
||||
],
|
||||
)
|
||||
finally:
|
||||
await conn.close()
|
||||
|
||||
|
||||
async def _delete_article_age_fixture() -> None:
|
||||
conn = await asyncpg.connect(**_conn_kwargs())
|
||||
try:
|
||||
await conn.execute(
|
||||
"DELETE FROM articles WHERE url = ANY($1::text[])",
|
||||
list(_FIXTURE_URLS),
|
||||
)
|
||||
finally:
|
||||
await conn.close()
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def article_age_rows():
|
||||
asyncio.run(_prepare_article_age_fixture())
|
||||
yield
|
||||
asyncio.run(_delete_article_age_fixture())
|
||||
|
||||
|
||||
@requires_db
|
||||
def test_health_article_age_ignores_future_rows(article_age_rows):
|
||||
"""Future-dated rows must not pin articles.age_s negative.
|
||||
|
||||
Fixture: one row at now+6d, one at now-120s. age_s is the age of the
|
||||
newest timestamp that is not in the future (NULL timestamps do not count).
|
||||
"""
|
||||
body = asyncio.run(_get("/api/health")).json()
|
||||
articles = body["checks"]["articles"]
|
||||
age = articles["age_s"]
|
||||
assert age is not None
|
||||
assert 0 <= age <= 600, articles
|
||||
assert articles["ok"] is True
|
||||
|
|
|
|||
Loading…
Reference in a new issue