diff --git a/homeassistant/components/sma/config_flow.py b/homeassistant/components/sma/config_flow.py index 68b9539ff96c..c648ec903cd4 100644 --- a/homeassistant/components/sma/config_flow.py +++ b/homeassistant/components/sma/config_flow.py @@ -93,8 +93,10 @@ async def validate_input( # new_session raises SmaAuthenticationException on failure await sma.new_session() - device_info = await sma.device_info() - await sma.close_session() + try: + device_info = await sma.device_info() + finally: + await sma.close_session() return dataclasses.asdict(device_info) diff --git a/tests/components/sma/test_config_flow.py b/tests/components/sma/test_config_flow.py index 0e4f8e5c6895..9ccb90abb610 100644 --- a/tests/components/sma/test_config_flow.py +++ b/tests/components/sma/test_config_flow.py @@ -105,6 +105,35 @@ async def test_form_exceptions( assert result["errors"] == {"base": error} +@pytest.mark.usefixtures("mock_setup_entry") +async def test_form_device_info_error_closes_session( + hass: HomeAssistant, mock_sma_client: MagicMock +) -> None: + """Test the session is closed when reading the device info fails.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + + mock_sma_client.device_info.side_effect = SmaReadException + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + MOCK_USER_INPUT, + ) + + assert result["type"] is FlowResultType.FORM + assert result["errors"] == {"base": "cannot_retrieve_device_info"} + mock_sma_client.close_session.assert_called_once() + + mock_sma_client.device_info.side_effect = None + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + MOCK_USER_INPUT, + ) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert mock_sma_client.close_session.call_count == 2 + + @pytest.mark.usefixtures("mock_setup_entry") async def test_form_already_configured( hass: HomeAssistant, mock_sma_client: AsyncMock