Reduce code duplication in Suez config flow (#105558)

This commit is contained in:
Joost Lekkerkerker 2023-12-13 10:41:35 +01:00 committed by GitHub
parent a91dfc7954
commit 06f81251fb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 45 additions and 93 deletions

View File

@ -10,16 +10,13 @@ import voluptuous as vol
from homeassistant.config_entries import ConfigFlow from homeassistant.config_entries import ConfigFlow
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN from homeassistant.data_entry_flow import FlowResult
from homeassistant.data_entry_flow import AbortFlow, FlowResult
from homeassistant.exceptions import HomeAssistantError from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.issue_registry import IssueSeverity, async_create_issue
from .const import CONF_COUNTER_ID, DOMAIN from .const import CONF_COUNTER_ID, DOMAIN
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
ISSUE_PLACEHOLDER = {"url": "/config/integrations/dashboard/add?domain=suez_water"}
STEP_USER_DATA_SCHEMA = vol.Schema( STEP_USER_DATA_SCHEMA = vol.Schema(
{ {
vol.Required(CONF_USERNAME): str, vol.Required(CONF_USERNAME): str,
@ -81,80 +78,16 @@ class SuezWaterConfigFlow(ConfigFlow, domain=DOMAIN):
async def async_step_import(self, user_input: dict[str, Any]) -> FlowResult: async def async_step_import(self, user_input: dict[str, Any]) -> FlowResult:
"""Import the yaml config.""" """Import the yaml config."""
await self.async_set_unique_id(user_input[CONF_USERNAME]) await self.async_set_unique_id(user_input[CONF_USERNAME])
try:
self._abort_if_unique_id_configured() self._abort_if_unique_id_configured()
except AbortFlow as err:
async_create_issue(
self.hass,
HOMEASSISTANT_DOMAIN,
f"deprecated_yaml_{DOMAIN}",
breaks_in_ha_version="2024.7.0",
is_fixable=False,
issue_domain=DOMAIN,
severity=IssueSeverity.WARNING,
translation_key="deprecated_yaml",
translation_placeholders={
"domain": DOMAIN,
"integration_title": "Suez Water",
},
)
raise err
try: try:
await self.hass.async_add_executor_job(validate_input, user_input) await self.hass.async_add_executor_job(validate_input, user_input)
except CannotConnect: except CannotConnect:
async_create_issue(
self.hass,
DOMAIN,
"deprecated_yaml_import_issue_cannot_connect",
breaks_in_ha_version="2024.7.0",
is_fixable=False,
issue_domain=DOMAIN,
severity=IssueSeverity.WARNING,
translation_key="deprecated_yaml_import_issue_cannot_connect",
translation_placeholders=ISSUE_PLACEHOLDER,
)
return self.async_abort(reason="cannot_connect") return self.async_abort(reason="cannot_connect")
except InvalidAuth: except InvalidAuth:
async_create_issue(
self.hass,
DOMAIN,
"deprecated_yaml_import_issue_invalid_auth",
breaks_in_ha_version="2024.7.0",
is_fixable=False,
issue_domain=DOMAIN,
severity=IssueSeverity.WARNING,
translation_key="deprecated_yaml_import_issue_invalid_auth",
translation_placeholders=ISSUE_PLACEHOLDER,
)
return self.async_abort(reason="invalid_auth") return self.async_abort(reason="invalid_auth")
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception") _LOGGER.exception("Unexpected exception")
async_create_issue(
self.hass,
DOMAIN,
"deprecated_yaml_import_issue_unknown",
breaks_in_ha_version="2024.7.0",
is_fixable=False,
issue_domain=DOMAIN,
severity=IssueSeverity.WARNING,
translation_key="deprecated_yaml_import_issue_unknown",
translation_placeholders=ISSUE_PLACEHOLDER,
)
return self.async_abort(reason="unknown") return self.async_abort(reason="unknown")
async_create_issue(
self.hass,
HOMEASSISTANT_DOMAIN,
f"deprecated_yaml_{DOMAIN}",
breaks_in_ha_version="2024.7.0",
is_fixable=False,
issue_domain=DOMAIN,
severity=IssueSeverity.WARNING,
translation_key="deprecated_yaml",
translation_placeholders={
"domain": DOMAIN,
"integration_title": "Suez Water",
},
)
return self.async_create_entry(title=user_input[CONF_USERNAME], data=user_input) return self.async_create_entry(title=user_input[CONF_USERNAME], data=user_input)

View File

@ -15,14 +15,17 @@ from homeassistant.components.sensor import (
) )
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, UnitOfVolume from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, UnitOfVolume
from homeassistant.core import HomeAssistant from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.issue_registry import IssueSeverity, async_create_issue
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from .const import CONF_COUNTER_ID, DOMAIN from .const import CONF_COUNTER_ID, DOMAIN
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
ISSUE_PLACEHOLDER = {"url": "/config/integrations/dashboard/add?domain=suez_water"}
SCAN_INTERVAL = timedelta(hours=12) SCAN_INTERVAL = timedelta(hours=12)
@ -35,19 +38,47 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
) )
def setup_platform( async def async_setup_platform(
hass: HomeAssistant, hass: HomeAssistant,
config: ConfigType, config: ConfigType,
add_entities: AddEntitiesCallback, async_add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None, discovery_info: DiscoveryInfoType | None = None,
) -> None: ) -> None:
"""Set up the sensor platform.""" """Set up the sensor platform."""
hass.async_create_task( result = await hass.config_entries.flow.async_init(
hass.config_entries.flow.async_init(
DOMAIN, DOMAIN,
context={"source": SOURCE_IMPORT}, context={"source": SOURCE_IMPORT},
data=config, data=config,
) )
if (
result["type"] == FlowResultType.CREATE_ENTRY
or result["reason"] == "already_configured"
):
async_create_issue(
hass,
HOMEASSISTANT_DOMAIN,
f"deprecated_yaml_{DOMAIN}",
breaks_in_ha_version="2024.7.0",
is_fixable=False,
issue_domain=DOMAIN,
severity=IssueSeverity.WARNING,
translation_key="deprecated_yaml",
translation_placeholders={
"domain": DOMAIN,
"integration_title": "Suez Water",
},
)
else:
async_create_issue(
hass,
DOMAIN,
f"deprecated_yaml_import_issue_${result['reason']}",
breaks_in_ha_version="2024.7.0",
is_fixable=False,
issue_domain=DOMAIN,
severity=IssueSeverity.WARNING,
translation_key=f"deprecated_yaml_import_issue_${result['reason']}",
translation_placeholders=ISSUE_PLACEHOLDER,
) )

View File

@ -8,7 +8,6 @@ from homeassistant import config_entries
from homeassistant.components.suez_water.const import DOMAIN from homeassistant.components.suez_water.const import DOMAIN
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers import issue_registry as ir
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
@ -138,9 +137,7 @@ async def test_form_error(
assert len(mock_setup_entry.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1
async def test_import( async def test_import(hass: HomeAssistant, mock_setup_entry: AsyncMock) -> None:
hass: HomeAssistant, mock_setup_entry: AsyncMock, issue_registry: ir.IssueRegistry
) -> None:
"""Test import flow.""" """Test import flow."""
with patch("homeassistant.components.suez_water.config_flow.SuezClient"): with patch("homeassistant.components.suez_water.config_flow.SuezClient"):
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
@ -153,7 +150,6 @@ async def test_import(
assert result["result"].unique_id == "test-username" assert result["result"].unique_id == "test-username"
assert result["data"] == MOCK_DATA assert result["data"] == MOCK_DATA
assert len(mock_setup_entry.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1
assert len(issue_registry.issues) == 1
@pytest.mark.parametrize( @pytest.mark.parametrize(
@ -164,7 +160,6 @@ async def test_import_error(
mock_setup_entry: AsyncMock, mock_setup_entry: AsyncMock,
exception: Exception, exception: Exception,
reason: str, reason: str,
issue_registry: ir.IssueRegistry,
) -> None: ) -> None:
"""Test we handle errors while importing.""" """Test we handle errors while importing."""
@ -178,12 +173,9 @@ async def test_import_error(
assert result["type"] == FlowResultType.ABORT assert result["type"] == FlowResultType.ABORT
assert result["reason"] == reason assert result["reason"] == reason
assert len(issue_registry.issues) == 1
async def test_importing_invalid_auth( async def test_importing_invalid_auth(hass: HomeAssistant) -> None:
hass: HomeAssistant, issue_registry: ir.IssueRegistry
) -> None:
"""Test we handle invalid auth when importing.""" """Test we handle invalid auth when importing."""
with patch( with patch(
@ -199,12 +191,9 @@ async def test_importing_invalid_auth(
assert result["type"] == FlowResultType.ABORT assert result["type"] == FlowResultType.ABORT
assert result["reason"] == "invalid_auth" assert result["reason"] == "invalid_auth"
assert len(issue_registry.issues) == 1
async def test_import_already_configured( async def test_import_already_configured(hass: HomeAssistant) -> None:
hass: HomeAssistant, issue_registry: ir.IssueRegistry
) -> None:
"""Test we abort import when entry is already configured.""" """Test we abort import when entry is already configured."""
entry = MockConfigEntry( entry = MockConfigEntry(
@ -220,4 +209,3 @@ async def test_import_already_configured(
assert result["type"] == FlowResultType.ABORT assert result["type"] == FlowResultType.ABORT
assert result["reason"] == "already_configured" assert result["reason"] == "already_configured"
assert len(issue_registry.issues) == 1