From c75b57fe8ee6c722d2a8ff21c2be6edcf0f61cd5 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Sun, 17 May 2026 18:17:32 +0000 Subject: [PATCH] Fix Growatt mix device IndexError when chart data is empty --- .../components/growatt_server/coordinator.py | 17 +++++++------- .../components/growatt_server/test_sensor.py | 23 +++++++++++++++++++ 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/homeassistant/components/growatt_server/coordinator.py b/homeassistant/components/growatt_server/coordinator.py index f5da2779580b34..c9885f16dad56d 100644 --- a/homeassistant/components/growatt_server/coordinator.py +++ b/homeassistant/components/growatt_server/coordinator.py @@ -215,14 +215,15 @@ def _sync_update_data(self) -> dict[str, Any]: mix_chart_entries = mix_detail["chartData"] sorted_keys = sorted(mix_chart_entries) - # Create datetime from the latest entry - date_now = dt_util.now().date() - last_updated_time = dt_util.parse_time(str(sorted_keys[-1])) - mix_detail["lastdataupdate"] = datetime.datetime.combine( - date_now, - last_updated_time, # type: ignore[arg-type] - dt_util.get_default_time_zone(), - ) + if sorted_keys: + # Create datetime from the latest entry + date_now = dt_util.now().date() + last_updated_time = dt_util.parse_time(str(sorted_keys[-1])) + mix_detail["lastdataupdate"] = datetime.datetime.combine( + date_now, + last_updated_time, # type: ignore[arg-type] + dt_util.get_default_time_zone(), + ) # Dashboard data for mix system dashboard_data = self.api.dashboard_data(self.plant_id) diff --git a/tests/components/growatt_server/test_sensor.py b/tests/components/growatt_server/test_sensor.py index e64a2a864e2c8c..81e31ba5ba9892 100644 --- a/tests/components/growatt_server/test_sensor.py +++ b/tests/components/growatt_server/test_sensor.py @@ -127,6 +127,29 @@ async def test_sensors_classic_api( ) +@pytest.mark.freeze_time("2023-10-21") +async def test_mix_empty_chart_data( + hass: HomeAssistant, + mock_growatt_classic_api, + mock_config_entry_classic: MockConfigEntry, +) -> None: + """Test mix device handles empty chart data without crashing.""" + mock_growatt_classic_api.device_list.return_value = [ + {"deviceSn": "MIX123456", "deviceType": "mix"} + ] + mock_growatt_classic_api.mix_detail.return_value = { + "deviceSn": "MIX123456", + "chartData": {}, + } + + with patch("homeassistant.components.growatt_server.PLATFORMS", [Platform.SENSOR]): + await setup_integration(hass, mock_config_entry_classic) + + # Should not crash - entities should still be created + states = hass.states.async_entity_ids("sensor") + assert len(states) > 0 + + async def test_sensor_coordinator_updates( hass: HomeAssistant, mock_growatt_v1_api,