From acdf77ad47e80107d00dd25a42319a297c9ff327 Mon Sep 17 00:00:00 2001 From: Erwin Douna Date: Sun, 27 Sep 2026 13:13:57 +0200 Subject: [PATCH] Close the SMA session when unloading the config entry (#183286) --- homeassistant/components/sma/__init__.py | 1 + homeassistant/components/sma/coordinator.py | 6 ++++- tests/components/sma/test_init.py | 27 +++++++++++++++++++++ 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/sma/__init__.py b/homeassistant/components/sma/__init__.py index 02b4a3cbfad5..58b1bf711b12 100644 --- a/homeassistant/components/sma/__init__.py +++ b/homeassistant/components/sma/__init__.py @@ -43,6 +43,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: SMAConfigEntry) -> bool: ) coordinator = SMADataUpdateCoordinator(hass, entry, sma) + entry.async_on_unload(coordinator.async_close_sma_session) await coordinator.async_config_entry_first_refresh() entry.runtime_data = coordinator diff --git a/homeassistant/components/sma/coordinator.py b/homeassistant/components/sma/coordinator.py index 148a2b30931b..976cf5faee6a 100644 --- a/homeassistant/components/sma/coordinator.py +++ b/homeassistant/components/sma/coordinator.py @@ -107,5 +107,9 @@ class SMADataUpdateCoordinator(DataUpdateCoordinator[SMACoordinatorData]): async def async_close_sma_session(self) -> None: """Close the SMA session.""" - await self.sma.close_session() + try: + await self.sma.close_session() + except SmaConnectionException as err: + _LOGGER.debug("Could not close the SMA session: %s", err) + return _LOGGER.debug("SMA session closed") diff --git a/tests/components/sma/test_init.py b/tests/components/sma/test_init.py index 036a93996448..25d633ff3272 100644 --- a/tests/components/sma/test_init.py +++ b/tests/components/sma/test_init.py @@ -56,3 +56,30 @@ async def test_setup_exceptions( mock_sma_client.device_info.side_effect = exception await setup_integration(hass, mock_config_entry) assert mock_config_entry.state is expected_state + + +@pytest.mark.parametrize( + "close_session_error", + [ + pytest.param(None, id="closed"), + pytest.param(SmaConnectionException, id="unreachable"), + ], +) +async def test_unload_closes_session( + hass: HomeAssistant, + mock_sma_client: MagicMock, + mock_config_entry: MockConfigEntry, + close_session_error: type[Exception] | None, +) -> None: + """Test unloading the entry closes the SMA session, even if unreachable.""" + await setup_integration(hass, mock_config_entry) + assert mock_config_entry.state is ConfigEntryState.LOADED + mock_sma_client.close_session.assert_not_called() + + mock_sma_client.close_session.side_effect = close_session_error + + assert await hass.config_entries.async_unload(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.NOT_LOADED + mock_sma_client.close_session.assert_called_once()