from types import SimpleNamespace from uuid import UUID import importlib import pytest from fastapi import HTTPException from app.api.v1 import earth, news @pytest.mark.asyncio async def test_post_news_refresh_only_schedules_background_region_check(monkeypatch): scheduled = [] def request(region: str): scheduled.append(region) return {"refresh_id": "refresh-europe", "region": region, "status": "pending"} async def fail_network_refresh(*_args, **_kwargs): raise AssertionError("the POST handler must not perform RSS requests") monkeypatch.setattr("app.services.scheduler.request_earth_news_region_refresh", request) monkeypatch.setattr("app.services.scheduler.refresh_earth_news_region", fail_network_refresh) response = await news.request_earth_news_refresh( news.EarthNewsRefreshRequest(region="Europe", lat=48.8, lon=2.3) ) assert response == {"refresh_id": "refresh-europe", "region": "europe", "status": "pending"} assert scheduled == ["europe"] refresh_route = next(route for route in news.router.routes if route.path == "/refresh") assert refresh_route.status_code == 202 @pytest.mark.asyncio async def test_post_news_refresh_infers_region_and_rejects_unknown_region(monkeypatch): scheduled = [] monkeypatch.setattr( "app.services.scheduler.request_earth_news_region_refresh", lambda region: scheduled.append(region) or {"refresh_id": "refresh-americas", "region": region, "status": "pending"}, ) response = await news.request_earth_news_refresh( news.EarthNewsRefreshRequest(lat=40.7, lon=-74.0) ) assert response["region"] == "americas" assert response["status"] == "pending" assert scheduled == ["americas"] with pytest.raises(HTTPException) as error: await news.request_earth_news_refresh(news.EarthNewsRefreshRequest(region="unknown")) assert error.value.status_code == 422 @pytest.mark.asyncio async def test_get_news_refresh_returns_status_and_expired_shape(monkeypatch): current = {"refresh_id": "abc", "region": "global", "status": "running"} monkeypatch.setattr( "app.services.earth_news_refresh.get_earth_news_refresh_status", lambda _refresh_id: current, ) response = await news.get_earth_news_refresh(UUID("00000000-0000-0000-0000-000000000abc")) assert response is current assert response["status"] == "running" monkeypatch.setattr( "app.services.earth_news_refresh.get_earth_news_refresh_status", lambda _id: None ) expired = await news.get_earth_news_refresh(UUID("00000000-0000-0000-0000-000000000abc")) assert expired == { "refresh_id": UUID("00000000-0000-0000-0000-000000000abc").hex, "region": None, "status": "failed", "error": { "code": "expired", "message": "Refresh status expired. Submit a new refresh.", }, } @pytest.mark.asyncio async def test_database_failure_sets_terminal_failed_status_without_leaking_error(monkeypatch): scheduler = importlib.import_module("app.services.scheduler") statuses = [] async def fail_refresh(_region, *, force=False): raise RuntimeError("postgres://private-token@host/database: commit failed") monkeypatch.setattr(scheduler, "refresh_earth_news_region", fail_refresh) monkeypatch.setattr(scheduler, "touch_earth_news_refresh_status", lambda *_args: True) monkeypatch.setattr( scheduler, "set_earth_news_refresh_status", lambda refresh_id, region, state, *, error=None: statuses.append( {"refresh_id": refresh_id, "region": region, "status": state, "error": error} ), ) scheduler._pending_earth_news_refreshes["europe"] = { "force": True, "refresh_id": "refresh-db-failure", } await scheduler._run_earth_news_region_refresh("europe") assert [item["status"] for item in statuses] == ["running", "failed"] assert statuses[-1]["error"] == { "code": "refresh_failed", "message": "Could not refresh news. Please try again.", } assert "private-token" not in repr(statuses) @pytest.mark.asyncio async def test_news_source_save_and_reset_schedule_immediate_refresh(monkeypatch): scheduled = [] monkeypatch.setattr( earth, "save_earth_news_sources_payload", lambda _db, _payload: _async_result({"status": "updated"}), ) monkeypatch.setattr( earth, "reset_earth_news_sources_payload", lambda _db: _async_result({"status": "reset"}), ) monkeypatch.setattr( "app.services.scheduler.schedule_earth_news_refresh_for_all_regions", lambda *, force=False: scheduled.append(force), ) await earth.update_earth_news_sources( SimpleNamespace(model_dump=lambda: {}), _current_user=None, db=object() ) await earth.reset_earth_news_sources(_current_user=None, db=object()) assert scheduled == [True, True] async def _async_result(value): return value