Files
skipredictor/tests/test_collect_historical_webcams.py
T
2026-03-13 15:10:37 +01:00

265 lines
8.8 KiB
Python

"""Unit tests for scripts/collect_historical_webcams.py."""
from __future__ import annotations
from datetime import date
from pathlib import Path
import pandas as pd
from scripts.collect_historical_webcams import HistoricalWebcamCollector
class _StoreStub:
"""Minimal store stub for historical webcam collector tests."""
def __init__(self, station_df: pd.DataFrame, crowd_df: pd.DataFrame):
self._station_df = station_df
self._crowd_df = crowd_df
def read_dataframe(self, *_: object, **__: object) -> pd.DataFrame:
return self._station_df.copy()
def load_crowd_analyses(self, **_: object) -> pd.DataFrame:
return self._crowd_df.copy()
def _collector_with_store(store: _StoreStub) -> HistoricalWebcamCollector:
collector = object.__new__(HistoricalWebcamCollector)
collector.store = store
collector.get_available_date_range = lambda _station_id: None
return collector
class _ResponseStub:
def __init__(
self,
*,
status_code: int = 200,
text: str = "",
content: bytes = b"",
headers: dict[str, str] | None = None,
):
self.status_code = status_code
self.text = text
self.content = content
self.headers = headers or {}
def raise_for_status(self) -> None:
if self.status_code >= 400:
raise RuntimeError(f"HTTP {self.status_code}")
class _SessionStub:
def __init__(self, responses: dict[str, _ResponseStub]):
self._responses = responses
def get(self, url: str, timeout: int = 20) -> _ResponseStub:
for key, value in self._responses.items():
if key in url:
return value
raise AssertionError(f"Unexpected URL in test: {url}")
class _RaisingSessionStub:
def get(self, url: str, timeout: int = 20) -> _ResponseStub:
raise RuntimeError(f"network error for {url}")
class _AnalyzerStub:
def __init__(self):
self.saved: list[dict] = []
def analyze_image(self, image_path: str) -> dict:
assert Path(image_path).exists()
return {
"cars_detected": 1,
"people_detected": 2,
"buses_detected": 0,
"total_vehicles": 1,
"crowd_density": "low",
"confidence_scores": [0.9],
"timestamp": "2026-03-13T00:00:00",
}
def _save_result(self, result: dict) -> None:
self.saved.append(result)
def test_get_missing_dates_uses_analysis_date_column():
"""Missing-date detection must use analysis_date instead of timestamp."""
station_df = pd.DataFrame(
{
"date": pd.to_datetime(["2026-03-10", "2026-03-11", "2026-03-12"]),
"station_id": ["pajares", "pajares", "pajares"],
}
)
crowd_df = pd.DataFrame(
{
"analysis_date": ["2026-03-10", "2026-03-11"],
"station_id": ["pajares", "pajares"],
}
)
collector = _collector_with_store(_StoreStub(station_df, crowd_df))
missing = collector.get_missing_dates("pajares")
assert missing == [date(2026, 3, 12)]
def test_is_already_processed_uses_analysis_date_column():
"""Processed-day checks must match against analysis_date values."""
collector = _collector_with_store(
_StoreStub(
station_df=pd.DataFrame(),
crowd_df=pd.DataFrame(
{
"analysis_date": ["2026-03-10"],
"station_id": ["pajares"],
}
),
)
)
assert collector._is_already_processed("pajares", date(2026, 3, 10))
assert not collector._is_already_processed("pajares", date(2026, 3, 11))
def test_retry_unknown_treats_unknown_as_pending():
"""With retry_unknown enabled, unknown rows must be considered unprocessed."""
collector = _collector_with_store(
_StoreStub(
station_df=pd.DataFrame(
{
"date": pd.to_datetime(["2026-03-10"]),
"station_id": ["pajares"],
}
),
crowd_df=pd.DataFrame(
{
"analysis_date": ["2026-03-10"],
"station_id": ["pajares"],
"crowd_density": ["unknown"],
}
),
)
)
assert collector._is_already_processed("pajares", date(2026, 3, 10))
assert not collector._is_already_processed(
"pajares", date(2026, 3, 10), retry_unknown=True
)
assert collector.get_missing_dates("pajares", retry_unknown=True) == [
date(2026, 3, 10)
]
def test_extract_webcam_jpg_url_accepts_relative_urls():
"""Relative /webcams/*.jpg paths must be normalized to absolute URLs."""
html = '<div><img src="/webcams/pajares-test_2025-03-03-10.jpg"></div>'
url = HistoricalWebcamCollector._extract_webcam_jpg_url(html)
assert url == "https://www.infonieve.es/webcams/pajares-test_2025-03-03-10.jpg"
def test_extract_webcam_jpg_url_accepts_historico_files_urls():
"""Historico image URLs under files/historico must be accepted."""
html = '<img src="https://www.infonieve.es/files/historico/2025/2025-04-30/3197_2025-04-30-10-714.jpg">'
url = HistoricalWebcamCollector._extract_webcam_jpg_url(html)
assert (
url
== "https://www.infonieve.es/files/historico/2025/2025-04-30/3197_2025-04-30-10-714.jpg"
)
def test_extract_webcam_jpg_url_accepts_escaped_relative_historico_urls():
"""Escaped relative paths like ``\\/files\\/historico\\/...`` must normalize."""
html = '{"src":"\\/files\\/historico\\/2025\\/2025-04-30\\/3197_2025-04-30-10-714.jpg"}'
url = HistoricalWebcamCollector._extract_webcam_jpg_url(html)
assert (
url
== "https://www.infonieve.es/files/historico/2025/2025-04-30/3197_2025-04-30-10-714.jpg"
)
def test_download_image_bytes_rejects_html_responses():
"""Downloader must reject HTML payloads even if URL ends in .jpg."""
collector = object.__new__(HistoricalWebcamCollector)
collector.session = _SessionStub(
{
"webcams/fake.jpg": _ResponseStub(
text="<html>not an image</html>",
content=b"<!DOCTYPE html><html>not an image</html>",
headers={"Content-Type": "text/html; charset=utf-8"},
)
}
)
result = collector._download_image_bytes("https://www.infonieve.es/webcams/fake.jpg")
assert result is None
def test_process_day_resolves_showimg_and_persists_analysis(tmp_path):
"""process_day must resolve showimg URL, download bytes, and save analysis."""
collector = object.__new__(HistoricalWebcamCollector)
collector.store = _StoreStub(pd.DataFrame(), pd.DataFrame())
collector.analyzer = _AnalyzerStub()
collector.temp_dir = tmp_path
collector.session = _SessionStub(
{
"showimg=1": _ResponseStub(
text='<img src="https://www.infonieve.es/webcams/pajares-sample.jpg">'
),
"webcams/pajares-sample.jpg": _ResponseStub(
content=b"\xff\xd8\xff\xdbJPEGDATA",
headers={"Content-Type": "image/jpeg"},
),
}
)
collector.process_day("pajares", date(2025, 3, 3))
assert len(collector.analyzer.saved) == 1
saved = collector.analyzer.saved[0]
assert saved["station_id"] == "pajares"
assert saved["crowd_density"] == "low"
assert str(saved["image_path"]).endswith("pajares_2025-03-03_10h.jpg")
def test_process_day_with_historico_file_url(tmp_path):
"""process_day must support resolved URLs under /files/historico/."""
collector = object.__new__(HistoricalWebcamCollector)
collector.store = _StoreStub(pd.DataFrame(), pd.DataFrame())
collector.analyzer = _AnalyzerStub()
collector.temp_dir = tmp_path
collector.session = _SessionStub(
{
"showimg=1": _ResponseStub(
text='<img src="/files/historico/2025/2025-04-30/3197_2025-04-30-10-714.jpg">'
),
"files/historico/2025/2025-04-30/3197_2025-04-30-10-714.jpg": _ResponseStub(
content=b"\xff\xd8\xff\xdbJPEGDATA",
headers={"Content-Type": "image/jpeg"},
),
}
)
collector.process_day("pajares", date(2025, 4, 30))
assert len(collector.analyzer.saved) == 1
saved = collector.analyzer.saved[0]
assert saved["station_id"] == "pajares"
assert saved["crowd_density"] == "low"
def test_process_day_does_not_persist_unknown_on_network_errors(tmp_path):
"""Transient errors must not be persisted as unknown crowd rows."""
collector = object.__new__(HistoricalWebcamCollector)
collector.store = _StoreStub(pd.DataFrame(), pd.DataFrame())
collector.analyzer = _AnalyzerStub()
collector.temp_dir = tmp_path
collector.session = _RaisingSessionStub()
collector.process_day("pajares", date(2025, 3, 3))
assert collector.analyzer.saved == []