From bcdefe8e3881ba7cee1f23e328326ad39aa0b719 Mon Sep 17 00:00:00 2001 From: Rudolf Offereins Date: Fri, 30 Oct 2026 19:48:31 +0000 Subject: [PATCH] Stop hiding EPG fetch failures get_epg treated every error as "segment not available" and only logged it at debug level, so network and server failures were invisible. Only a 404 is still skipped quietly. Other connection errors are logged as warnings while the remaining segments are still merged, and auth errors now propagate. The request is the only code inside the try. Co-Authored-By: Claude Sonnet 5.5 --- lghorizon/lghorizon_api.py | 35 ++++++++++--- tests/test_api.py | 102 +++++++++++++++++++++++++++++++++++-- 2 files changed, 125 insertions(+), 12 deletions(-) diff --git a/lghorizon/lghorizon_api.py b/lghorizon/lghorizon_api.py index 0896551..3f50704 100644 --- a/lghorizon/lghorizon_api.py +++ b/lghorizon/lghorizon_api.py @@ -5,7 +5,9 @@ from typing import Any, Dict, cast, Callable, Optional from datetime import date as date_type -from .exceptions import LGHorizonApiError +from aiohttp import ClientResponseError + +from .exceptions import LGHorizonApiConnectionError, LGHorizonApiError from .lghorizon_device import LGHorizonDevice from .lghorizon_models import LGHorizonChannel from .lghorizon_models import LGHorizonAuth @@ -35,6 +37,12 @@ _LOGGER = logging.getLogger(__name__) +def _is_not_found(error: LGHorizonApiConnectionError) -> bool: + """Return whether the connection error was caused by an HTTP 404.""" + cause = error.__cause__ + return isinstance(cause, ClientResponseError) and cause.status == 404 + + class LGHorizonApi: """LG Horizon API client.""" @@ -463,13 +471,24 @@ async def get_epg(self, epg_date: date_type | None = None, language: str | None path = f"/{base_country_code}/{language}/events/segments/{date_str}{segment}0000" try: result = await self.auth.request(epg_base, path) - for entry in result.get("entries", []): - ch_id = entry.get("channelId", "") - if ch_id not in all_entries: - all_entries[ch_id] = [] - all_entries[ch_id].extend(entry.get("events", [])) - except Exception: - _LOGGER.debug("EPG segment %s%s0000 not available", date_str, segment) + except LGHorizonApiConnectionError as ex: + if _is_not_found(ex): + _LOGGER.debug( + "EPG segment %s%s0000 not available", date_str, segment + ) + else: + _LOGGER.warning( + "Failed to fetch EPG segment %s%s0000: %s", + date_str, + segment, + ex, + ) + continue + for entry in result.get("entries", []): + ch_id = entry.get("channelId", "") + if ch_id not in all_entries: + all_entries[ch_id] = [] + all_entries[ch_id].extend(entry.get("events", [])) # Build merged EpgEntry objects entries = [ diff --git a/tests/test_api.py b/tests/test_api.py index 70c766f..320f472 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -1,7 +1,14 @@ """Unit tests for LGHorizonApi.""" import pytest +from aiohttp import ClientResponseError, RequestInfo from unittest.mock import AsyncMock, MagicMock, patch +from yarl import URL + +from lghorizon.exceptions import ( + LGHorizonApiConnectionError, + LGHorizonApiUnauthorizedError, +) from lghorizon.lghorizon_api import LGHorizonApi from lghorizon.lghorizon_device import LGHorizonDevice @@ -560,17 +567,104 @@ async def test_returns_lghorizonepg_with_merged_segments( # 4 segments × 1 event = 4 events merged assert len(events) == 4 - async def test_returns_empty_epg_when_all_segments_fail( - self, mock_auth, sample_customer_json, sample_channel_json + @staticmethod + def _connection_error(status: int) -> LGHorizonApiConnectionError: + request_info = RequestInfo( + url=URL("http://test"), + method="GET", + headers={}, # type: ignore[arg-type] + real_url=URL("http://test"), + ) + cause = ClientResponseError(request_info, (), status=status, message="error") + error = LGHorizonApiConnectionError(f"Unable to call: {status}") + error.__cause__ = cause + return error + + async def test_missing_segments_are_skipped_quietly( + self, + mock_auth, + sample_customer_json, + sample_channel_json, + caplog: pytest.LogCaptureFixture, ): api = self._make_api(mock_auth, sample_customer_json, sample_channel_json) - mock_auth.request = AsyncMock(side_effect=Exception("network error")) + segment = {"entries": [{"channelId": "NL_001", "events": [{"id": "e1"}]}]} + mock_auth.request = AsyncMock( + side_effect=[segment, segment, self._connection_error(404), self._connection_error(404)] + ) + + from datetime import date + result = await api.get_epg(epg_date=date(2026, 4, 24)) + + assert len(result.get_channel_events("NL_001")) == 2 + assert not [r for r in caplog.records if r.levelname == "WARNING"] + + async def test_all_segments_missing_returns_empty_epg( + self, + mock_auth, + sample_customer_json, + sample_channel_json, + caplog: pytest.LogCaptureFixture, + ): + api = self._make_api(mock_auth, sample_customer_json, sample_channel_json) + mock_auth.request = AsyncMock(side_effect=self._connection_error(404)) from datetime import date result = await api.get_epg(epg_date=date(2026, 4, 24)) - assert isinstance(result, LGHorizonEpg) assert result.entries == [] + assert not [r for r in caplog.records if r.levelname == "WARNING"] + + @pytest.mark.parametrize("status", [500, 502, 403]) + async def test_failed_segments_are_logged_as_warnings( + self, + mock_auth, + sample_customer_json, + sample_channel_json, + caplog: pytest.LogCaptureFixture, + status: int, + ): + api = self._make_api(mock_auth, sample_customer_json, sample_channel_json) + segment = {"entries": [{"channelId": "NL_001", "events": [{"id": "e1"}]}]} + mock_auth.request = AsyncMock( + side_effect=[segment, self._connection_error(status), segment, segment] + ) + + from datetime import date + result = await api.get_epg(epg_date=date(2026, 4, 24)) + + assert len(result.get_channel_events("NL_001")) == 3 + warnings = [r.getMessage() for r in caplog.records if r.levelname == "WARNING"] + assert len(warnings) == 1 + assert "20260424060000" in warnings[0] + + async def test_connection_error_without_http_cause_is_a_warning( + self, + mock_auth, + sample_customer_json, + sample_channel_json, + caplog: pytest.LogCaptureFixture, + ): + api = self._make_api(mock_auth, sample_customer_json, sample_channel_json) + mock_auth.request = AsyncMock(side_effect=LGHorizonApiConnectionError("down")) + + from datetime import date + result = await api.get_epg(epg_date=date(2026, 4, 24)) + + assert result.entries == [] + assert len([r for r in caplog.records if r.levelname == "WARNING"]) == 4 + + async def test_unauthorized_error_is_not_swallowed( + self, mock_auth, sample_customer_json, sample_channel_json + ): + api = self._make_api(mock_auth, sample_customer_json, sample_channel_json) + mock_auth.request = AsyncMock( + side_effect=LGHorizonApiUnauthorizedError("Invalid token") + ) + + from datetime import date + with pytest.raises(LGHorizonApiUnauthorizedError): + await api.get_epg(epg_date=date(2026, 4, 24)) async def test_defaults_to_today_when_no_date_given( self, mock_auth, sample_customer_json, sample_channel_json