diff --git a/backend/app/services/weather_cache.py b/backend/app/services/weather_cache.py index 179f2245..00fd366a 100644 --- a/backend/app/services/weather_cache.py +++ b/backend/app/services/weather_cache.py @@ -161,8 +161,15 @@ def _fetch_weather_remote(lat: float, lon: float) -> dict[str, Any] | None: "avg_max_c": round(sum(t_max) / len(t_max), 1) if t_max else None, "avg_min_c": round(sum(t_min) / len(t_min), 1) if t_min else None, }, - "precipitation_total_mm": round(sum(precip), 1) if precip else 0, - "precipitation_days": sum(1 for p in precip if p and p > 0.5), + # #2464: было `if precip else 0`. Ноль здесь означал бы «осадков не + # ожидается» — утверждение о погоде. Но пустой `precip` значит, что + # open-meteo не отдал ряд осадков вовсе, то есть мы НЕ ЗНАЕМ. Все шесть + # соседних агрегатов в этом же словаре при пустых данных дают None + # (min_c/max_c/avg_*/uv_index_max/max_speed_m_s) — осадки были + # единственным исключением, и именно они рисуются на фронте как + # измеренная величина (ptica-adapt заворачивает их в `real(...)`). + "precipitation_total_mm": round(sum(precip), 1) if precip else None, + "precipitation_days": (sum(1 for p in precip if p and p > 0.5) if precip else None), "uv_index_max": round(max(uv), 1) if uv else None, "wind": { "dominant_direction_deg": ( @@ -251,7 +258,10 @@ def _fetch_seasonal_remote(lat: float, lon: float) -> dict[str, Any] | None: "avg_precip_per_day_mm": ( round(sum(precip) / len(precip), 1) if precip else None ), - "total_precip_mm": round(sum(precip), 0) if precip else 0, + # #2464: та же правка, что у прогноза выше. Особенно наглядно + # здесь: соседняя строка avg_precip_per_day_mm считается из ЭТОГО ЖЕ + # списка и при пустом даёт None, а сумма давала 0. + "total_precip_mm": round(sum(precip), 0) if precip else None, "days_observed": len(vals["t_max"]), } return { diff --git a/backend/tests/services/test_weather_cache.py b/backend/tests/services/test_weather_cache.py index c5cab6f1..ed5b5f71 100644 --- a/backend/tests/services/test_weather_cache.py +++ b/backend/tests/services/test_weather_cache.py @@ -594,3 +594,87 @@ class TestWindDirectionAllNone: # Один сэмпл 90° → circular mean ровно 90° → rose[2] = "Восток" assert wind["dominant_direction_deg"] == 90 assert wind["dominant_direction_label"] == "Восток" + + +# ────────────────────────────────────────────────────────────────────────────── +# 8. осадков нет в ответе → precipitation_* = None, а не 0 (#2464) +# +# Тот же класс, что раздел 7 выше (wind_d all-None → None, не 0.0°): «ноль» здесь +# был бы утверждением о погоде («сухо»), тогда как пустой ряд значит, что мы просто +# не знаем. Все шесть соседних агрегатов того же словаря при пустых данных дают None +# — осадки были единственным исключением, и именно они рисуются на фронте как +# измеренная величина (ptica-adapt заворачивал их в `real(...)` безусловно). +# ────────────────────────────────────────────────────────────────────────────── + + +def _make_forecast_response_precip_all_none() -> dict[str, Any]: + """Forecast, где все precipitation_sum = null (Open-Meteo так делает штатно).""" + return { + "daily": { + "time": ["2026-06-12", "2026-06-13", "2026-06-14"], + "temperature_2m_max": [20.0, 21.0, 22.0], + "temperature_2m_min": [10.0, 11.0, 12.0], + "precipitation_sum": [None, None, None], + "uv_index_max": [5.0, 5.0, 5.0], + "winddirection_10m_dominant": [180, 180, 180], + "windspeed_10m_max": [3.0, 4.0, 3.0], + } + } + + +def _make_forecast_response_precip_missing() -> dict[str, Any]: + """Forecast без ключа precipitation_sum вовсе.""" + return { + "daily": { + "time": ["2026-06-12", "2026-06-13", "2026-06-14"], + "temperature_2m_max": [20.0, 21.0, 22.0], + "temperature_2m_min": [10.0, 11.0, 12.0], + "uv_index_max": [5.0, 5.0, 5.0], + "winddirection_10m_dominant": [180, 180, 180], + "windspeed_10m_max": [3.0, 4.0, 3.0], + } + } + + +class TestPrecipitationUnknownIsNotZero: + """Регрессия: без ряда осадков не должно возвращаться 0 (= «сухо»).""" + + def _call_with_payload(self, payload: dict[str, Any]) -> dict[str, Any] | None: + get = MagicMock(return_value=_make_httpx_response(payload)) + client_ctx = MagicMock() + client_ctx.__enter__ = MagicMock(return_value=MagicMock(get=get)) + client_ctx.__exit__ = MagicMock(return_value=None) + with patch("app.services.weather_cache.httpx.Client", return_value=client_ctx): + return weather_cache.get_weather_cached(56.84, 60.59) + + def test_all_none_precip_gives_none_not_zero(self) -> None: + result = self._call_with_payload(_make_forecast_response_precip_all_none()) + + assert result is not None, "ответ должен строиться и без ряда осадков" + assert result["precipitation_total_mm"] is None, ( + f"ожидался None, получено {result['precipitation_total_mm']!r} — " + "ноль здесь читается как «осадков не будет»" + ) + assert result["precipitation_days"] is None + + def test_missing_precip_key_gives_none(self) -> None: + result = self._call_with_payload(_make_forecast_response_precip_missing()) + + assert result is not None + assert result["precipitation_total_mm"] is None + assert result["precipitation_days"] is None + + def test_real_dry_week_is_still_a_measured_zero(self) -> None: + """КОНТРОЛЬ: настоящая сухая неделя — это измеренный 0.0, а не None. + + Без этой проверки правку можно было бы «сделать» так, что осадки всегда + None, и оба теста выше стали бы зелёными по неверной причине. + """ + payload = _make_forecast_response_precip_all_none() + payload["daily"]["precipitation_sum"] = [0.0, 0.0, 0.0] + + result = self._call_with_payload(payload) + + assert result is not None + assert result["precipitation_total_mm"] == 0.0 + assert result["precipitation_days"] == 0 diff --git a/frontend/src/components/site-finder/EnvironmentTab.tsx b/frontend/src/components/site-finder/EnvironmentTab.tsx index 4d4a90fa..7b6228d5 100644 --- a/frontend/src/components/site-finder/EnvironmentTab.tsx +++ b/frontend/src/components/site-finder/EnvironmentTab.tsx @@ -361,16 +361,23 @@ function WeatherBlock({