Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove deprecated import swiss public transport import flow #119813

Merged
merged 1 commit into from
Jun 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 0 additions & 31 deletions homeassistant/components/swiss_public_transport/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import voluptuous as vol

from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_NAME
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv

Expand Down Expand Up @@ -69,33 +68,3 @@ async def async_step_user(
errors=errors,
description_placeholders=PLACEHOLDERS,
)

async def async_step_import(self, import_input: dict[str, Any]) -> ConfigFlowResult:
"""Async import step to set up the connection."""
await self.async_set_unique_id(
f"{import_input[CONF_START]} {import_input[CONF_DESTINATION]}"
)
self._abort_if_unique_id_configured()

session = async_get_clientsession(self.hass)
opendata = OpendataTransport(
import_input[CONF_START], import_input[CONF_DESTINATION], session
)
try:
await opendata.async_get_data()
except OpendataTransportConnectionError:
return self.async_abort(reason="cannot_connect")
except OpendataTransportError:
return self.async_abort(reason="bad_config")
except Exception: # noqa: BLE001
_LOGGER.error(
"Unknown error raised by python-opendata-transport for '%s %s', check at http://transport.opendata.ch/examples/stationboard.html if your station names and your parameters are valid",
import_input[CONF_START],
import_input[CONF_DESTINATION],
)
return self.async_abort(reason="unknown")

return self.async_create_entry(
title=import_input[CONF_NAME],
data=import_input,
)
74 changes: 4 additions & 70 deletions homeassistant/components/swiss_public_transport/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,48 +8,26 @@
import logging
from typing import TYPE_CHECKING

import voluptuous as vol

from homeassistant import config_entries, core
from homeassistant.components.sensor import (
PLATFORM_SCHEMA,
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
)
from homeassistant.config_entries import SOURCE_IMPORT
from homeassistant.const import CONF_NAME, UnitOfTime
from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant, callback
from homeassistant.data_entry_flow import FlowResultType
import homeassistant.helpers.config_validation as cv
from homeassistant.const import UnitOfTime
from homeassistant.core import callback
from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.issue_registry import IssueSeverity, async_create_issue
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType, StateType
from homeassistant.helpers.typing import StateType
from homeassistant.helpers.update_coordinator import CoordinatorEntity

from .const import (
CONF_DESTINATION,
CONF_START,
DEFAULT_NAME,
DOMAIN,
PLACEHOLDERS,
SENSOR_CONNECTIONS_COUNT,
)
from .const import DOMAIN, SENSOR_CONNECTIONS_COUNT
from .coordinator import DataConnection, SwissPublicTransportDataUpdateCoordinator

_LOGGER = logging.getLogger(__name__)

SCAN_INTERVAL = timedelta(seconds=90)

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_DESTINATION): cv.string,
vol.Required(CONF_START): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
}
)


@dataclass(kw_only=True, frozen=True)
class SwissPublicTransportSensorEntityDescription(SensorEntityDescription):
Expand Down Expand Up @@ -118,50 +96,6 @@ async def async_setup_entry(
)


async def async_setup_platform(
hass: HomeAssistant,
config: ConfigType,
async_add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the sensor platform."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
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": "Swiss public transport",
},
)
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=PLACEHOLDERS,
)


class SwissPublicTransportSensor(
CoordinatorEntity[SwissPublicTransportDataUpdateCoordinator], SensorEntity
):
Expand Down
14 changes: 0 additions & 14 deletions homeassistant/components/swiss_public_transport/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,19 +46,5 @@
"name": "Delay"
}
}
},
"issues": {
"deprecated_yaml_import_issue_cannot_connect": {
"title": "The swiss public transport YAML configuration import cannot connect to server",
"description": "Configuring swiss public transport using YAML is being removed but there was a connection error importing your YAML configuration.\n\nMake sure your Home Assistant can reach the [opendata server]({opendata_url}). In case the server is down, try again later."
},
"deprecated_yaml_import_issue_bad_config": {
"title": "The swiss public transport YAML configuration import request failed due to bad config",
"description": "Configuring swiss public transport using YAML is being removed but there was bad config imported in your YAML configuration.\n\nCheck the [stationboard]({stationboard_url}) for valid stations."
},
"deprecated_yaml_import_issue_unknown": {
"title": "The swiss public transport YAML configuration import failed with unknown error raised by python-opendata-transport",
"description": "Configuring swiss public transport using YAML is being removed but there was an unknown error importing your YAML configuration.\n\nCheck your configuration or have a look at the documentation of the integration."
}
}
}
79 changes: 1 addition & 78 deletions tests/components/swiss_public_transport/test_config_flow.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,18 @@
"""Test the swiss_public_transport config flow."""

from unittest.mock import AsyncMock, patch
from unittest.mock import patch

from opendata_transport.exceptions import (
OpendataTransportConnectionError,
OpendataTransportError,
)
import pytest

from homeassistant import config_entries
from homeassistant.components.swiss_public_transport import config_flow
from homeassistant.components.swiss_public_transport.const import (
CONF_DESTINATION,
CONF_START,
)
from homeassistant.const import CONF_NAME
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType

Expand Down Expand Up @@ -126,78 +124,3 @@ async def test_flow_user_init_data_already_configured(hass: HomeAssistant) -> No

assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"


MOCK_DATA_IMPORT = {
CONF_START: "test_start",
CONF_DESTINATION: "test_destination",
CONF_NAME: "test_name",
}


async def test_import(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
) -> None:
"""Test import flow."""
with patch(
"homeassistant.components.swiss_public_transport.config_flow.OpendataTransport.async_get_data",
autospec=True,
return_value=True,
):
result = await hass.config_entries.flow.async_init(
config_flow.DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data=MOCK_DATA_IMPORT,
)
await hass.async_block_till_done()

assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == MOCK_DATA_IMPORT
assert len(mock_setup_entry.mock_calls) == 1


@pytest.mark.parametrize(
("raise_error", "text_error"),
[
(OpendataTransportConnectionError(), "cannot_connect"),
(OpendataTransportError(), "bad_config"),
(IndexError(), "unknown"),
],
)
async def test_import_error(hass: HomeAssistant, raise_error, text_error) -> None:
"""Test import flow cannot_connect error."""
with patch(
"homeassistant.components.swiss_public_transport.config_flow.OpendataTransport.async_get_data",
autospec=True,
side_effect=raise_error,
):
result = await hass.config_entries.flow.async_init(
config_flow.DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data=MOCK_DATA_IMPORT,
)
await hass.async_block_till_done()

assert result["type"] is FlowResultType.ABORT
assert result["reason"] == text_error


async def test_import_already_configured(hass: HomeAssistant) -> None:
"""Test we abort import when entry is already configured."""

entry = MockConfigEntry(
domain=config_flow.DOMAIN,
data=MOCK_DATA_IMPORT,
unique_id=f"{MOCK_DATA_IMPORT[CONF_START]} {MOCK_DATA_IMPORT[CONF_DESTINATION]}",
)
entry.add_to_hass(hass)

result = await hass.config_entries.flow.async_init(
config_flow.DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data=MOCK_DATA_IMPORT,
)

assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"