mirror of
https://github.com/Dasemu/skipredictor.git
synced 2026-11-26 07:16:15 +00:00
- Refactor backend into a single process (FastAPI + APScheduler + Telegram Bot) - Implement 'current_forecasts' and 'past_forecasts' architecture in storage - Optimize historical webcam collector with date range discovery for Pajares, San Isidro, and Fuentes - Clean up legacy scripts and tables (prediction_runs, prediction_stations) - Update tests and operations documentation
233 lines
6.3 KiB
Python
233 lines
6.3 KiB
Python
"""Unit tests for bot-side prediction selection rules."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import sys
|
|
import types
|
|
from datetime import datetime
|
|
from pathlib import Path
|
|
from zoneinfo import ZoneInfo
|
|
|
|
import yaml
|
|
|
|
telegram_module = types.ModuleType("telegram")
|
|
|
|
|
|
class _Update:
|
|
ALL_TYPES = object()
|
|
|
|
|
|
telegram_module.Update = _Update
|
|
|
|
constants_module = types.ModuleType("telegram.constants")
|
|
|
|
|
|
class _ParseMode:
|
|
HTML = "HTML"
|
|
|
|
|
|
constants_module.ParseMode = _ParseMode
|
|
|
|
ext_module = types.ModuleType("telegram.ext")
|
|
|
|
|
|
class _ApplicationBuilder:
|
|
def token(self, token: str):
|
|
return self
|
|
|
|
def build(self):
|
|
return types.SimpleNamespace(
|
|
add_handler=lambda *args, **kwargs: None,
|
|
run_polling=lambda *args, **kwargs: None,
|
|
)
|
|
|
|
|
|
class _Application:
|
|
@staticmethod
|
|
def builder():
|
|
return _ApplicationBuilder()
|
|
|
|
|
|
class _CommandHandler:
|
|
def __init__(self, *args, **kwargs) -> None:
|
|
self.args = args
|
|
self.kwargs = kwargs
|
|
|
|
|
|
class _ContextTypes:
|
|
DEFAULT_TYPE = object
|
|
|
|
|
|
ext_module.Application = _Application
|
|
ext_module.CommandHandler = _CommandHandler
|
|
ext_module.ContextTypes = _ContextTypes
|
|
|
|
sys.modules.setdefault("telegram", telegram_module)
|
|
sys.modules.setdefault("telegram.constants", constants_module)
|
|
sys.modules.setdefault("telegram.ext", ext_module)
|
|
|
|
from bot import telegram_bot
|
|
|
|
|
|
class FakeStore:
|
|
"""In-memory stand-in for SQLiteStore used in selection tests.
|
|
|
|
Exposes ``load_current_forecasts()`` which returns flat forecast rows
|
|
matching the ``current_forecasts`` table schema.
|
|
"""
|
|
|
|
def __init__(
|
|
self,
|
|
rows: list[dict] | None = None,
|
|
) -> None:
|
|
self.rows = rows or []
|
|
self.db_path = "/tmp/fake.db"
|
|
|
|
def load_current_forecasts(self, station_id=None):
|
|
if station_id is not None:
|
|
return [r for r in self.rows if r["station_id"] == station_id]
|
|
return list(self.rows)
|
|
|
|
|
|
def _make_forecast_row(
|
|
station_id: str,
|
|
prediction_date: str,
|
|
open_probability: float = 0.5,
|
|
) -> dict:
|
|
"""Build a minimal forecast row matching the current_forecasts schema."""
|
|
return {
|
|
"id": 1,
|
|
"generated_at": "2026-03-13T10:00:00+00:00",
|
|
"run_hour": 10,
|
|
"station_id": station_id,
|
|
"prediction_date": prediction_date,
|
|
"open_probability": open_probability,
|
|
"km_open": 10.0,
|
|
"crowd_level": "medium",
|
|
"weather_summary": None,
|
|
"rule_notes_json": "[]",
|
|
"prediction_source": "hybrid",
|
|
}
|
|
|
|
|
|
def test_load_predictions_prefers_today_before_ten():
|
|
"""Before 10:00 local time the bot should prefer today's run."""
|
|
store = FakeStore(
|
|
rows=[
|
|
_make_forecast_row("pajares", "2026-03-13"),
|
|
_make_forecast_row("pajares", "2026-03-14"),
|
|
]
|
|
)
|
|
|
|
loaded = telegram_bot.load_predictions(
|
|
now=datetime(2026, 3, 13, 9, 30, tzinfo=ZoneInfo("Europe/Madrid")),
|
|
store=store,
|
|
)
|
|
|
|
assert loaded is not None
|
|
assert loaded["prediction_date"] == "2026-03-13"
|
|
|
|
|
|
def test_load_predictions_prefers_tomorrow_after_ten():
|
|
"""From 10:00 onwards the bot should prefer tomorrow's run."""
|
|
store = FakeStore(
|
|
rows=[
|
|
_make_forecast_row("pajares", "2026-03-13"),
|
|
_make_forecast_row("pajares", "2026-03-14"),
|
|
]
|
|
)
|
|
|
|
loaded = telegram_bot.load_predictions(
|
|
now=datetime(2026, 3, 13, 10, 0, tzinfo=ZoneInfo("Europe/Madrid")),
|
|
store=store,
|
|
)
|
|
|
|
assert loaded is not None
|
|
assert loaded["prediction_date"] == "2026-03-14"
|
|
|
|
|
|
def test_load_predictions_falls_back_when_preferred_dates_are_missing():
|
|
"""If the preferred dates are absent, fall back to whatever is available."""
|
|
store = FakeStore(
|
|
rows=[
|
|
_make_forecast_row("pajares", "2026-03-16"),
|
|
]
|
|
)
|
|
|
|
loaded = telegram_bot.load_predictions(
|
|
now=datetime(2026, 3, 13, 8, 0, tzinfo=ZoneInfo("Europe/Madrid")),
|
|
store=store,
|
|
)
|
|
|
|
assert loaded is not None
|
|
assert loaded["prediction_date"] == "2026-03-16"
|
|
|
|
|
|
def test_prediction_dates_window_returns_consecutive_dates():
|
|
"""Window helpers must return consecutive dates from the requested offset."""
|
|
dates = telegram_bot.prediction_dates_window(
|
|
start_offset=1,
|
|
length=3,
|
|
now=datetime(2026, 3, 13, 8, 0, tzinfo=ZoneInfo("Europe/Madrid")),
|
|
)
|
|
|
|
assert dates == ["2026-03-14", "2026-03-15", "2026-03-16"]
|
|
|
|
|
|
def test_format_daily_predictions_includes_all_three_stations():
|
|
"""Daily overview messages must include the three configured stations."""
|
|
payload = {
|
|
"prediction_date": "2026-03-14",
|
|
"stations": {
|
|
"pajares": {
|
|
"open_probability": 0.85,
|
|
"km_open": 15.2,
|
|
"crowd_level": "medium",
|
|
"weather_summary": "Nevadas débiles",
|
|
"rule_overrides": [],
|
|
"prediction_source": "hybrid",
|
|
},
|
|
"sanisidro": {
|
|
"open_probability": 0.55,
|
|
"km_open": 12.8,
|
|
"crowd_level": "high",
|
|
"weather_summary": "Viento moderado",
|
|
"rule_overrides": [],
|
|
"prediction_source": "ml",
|
|
},
|
|
"fuentes": {
|
|
"open_probability": 0.35,
|
|
"km_open": 2.0,
|
|
"crowd_level": "low",
|
|
"weather_summary": "Lluvia a media mañana",
|
|
"rule_overrides": ["Cota de nieve alta."],
|
|
"prediction_source": "rules",
|
|
},
|
|
},
|
|
}
|
|
|
|
text = telegram_bot.format_daily_predictions(payload)
|
|
|
|
assert "Valgrande-Pajares" in text
|
|
assert "San Isidro" in text
|
|
assert "Fuentes de Invierno" in text
|
|
assert "2026-03-14" in text
|
|
|
|
|
|
def test_station_metadata_is_loaded_from_shared_config():
|
|
"""Bot station labels and max km must come from config/stations.yaml."""
|
|
config_path = Path(__file__).resolve().parents[1] / "config" / "stations.yaml"
|
|
with config_path.open("r", encoding="utf-8") as fh:
|
|
stations = yaml.safe_load(fh)["stations"]
|
|
|
|
expected = {
|
|
station_id: {
|
|
"name": station_cfg["name"],
|
|
"max_km": float(station_cfg["max_km_skiable"]),
|
|
}
|
|
for station_id, station_cfg in stations.items()
|
|
}
|
|
|
|
assert telegram_bot.STATIONS == expected
|
|
assert telegram_bot.STATION_ORDER == tuple(stations.keys())
|