"""Weekly import cron trigger and import-staleness helper.""" from __future__ import annotations from datetime import UTC, datetime, timedelta import pytest from app.config import Settings from app.db.models import SourceImportRun from app.db.queries import latest_successful_import_at from app.scheduler import start_scheduler, stop_scheduler @pytest.mark.asyncio async def test_import_job_registered_as_weekly_cron(): settings = Settings( APP_NAME="RastroTest", RUN_SCHEDULER=True, IMPORT_DAY_OF_WEEK="sun", IMPORT_HOUR_UTC=4, ) scheduler = start_scheduler(settings) try: job = scheduler.get_job("import_sources") assert job is not None trigger = str(job.trigger) assert "day_of_week='sun'" in trigger assert "hour='4'" in trigger finally: stop_scheduler() @pytest.mark.asyncio async def test_latest_successful_import_at(session): now = datetime.now(UTC) session.add_all( [ SourceImportRun( source_name="a", started_at=now - timedelta(days=10), finished_at=now - timedelta(days=10), status="ok", ), SourceImportRun( source_name="b", started_at=now - timedelta(days=2), finished_at=now - timedelta(days=2), status="not_modified", ), SourceImportRun( source_name="c", started_at=now, finished_at=now, status="failed", ), ] ) await session.commit() latest = await latest_successful_import_at(session) assert latest is not None if latest.tzinfo is None: latest = latest.replace(tzinfo=UTC) # The 2-day-old not_modified run wins; the failed "now" run does not count. assert (now - latest) < timedelta(days=3) @pytest.mark.asyncio async def test_latest_successful_import_at_none_when_only_failures(session): now = datetime.now(UTC) session.add( SourceImportRun( source_name="a", started_at=now, finished_at=now, status="failed", ) ) await session.commit() assert await latest_successful_import_at(session) is None