Skip to content

Commit

Permalink
Remove config for Speedtest.net (home-assistant#55642)
Browse files Browse the repository at this point in the history
  • Loading branch information
engrbm87 authored Sep 23, 2021
1 parent 7fc0717 commit 4c40d17
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 162 deletions.
97 changes: 13 additions & 84 deletions homeassistant/components/speedtestdotnet/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,11 @@
import logging

import speedtest
import voluptuous as vol

from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import (
CONF_MONITORED_CONDITIONS,
CONF_SCAN_INTERVAL,
EVENT_HOMEASSISTANT_STARTED,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_SCAN_INTERVAL, EVENT_HOMEASSISTANT_STARTED
from homeassistant.core import CoreState, HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.typing import ConfigType
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed

from .const import (
Expand All @@ -26,59 +19,11 @@
DEFAULT_SERVER,
DOMAIN,
PLATFORMS,
SENSOR_TYPES,
SPEED_TEST_SERVICE,
)

_LOGGER = logging.getLogger(__name__)

SENSOR_KEYS = [desc.key for desc in SENSOR_TYPES]

CONFIG_SCHEMA = vol.Schema(
vol.All(
# Deprecated in Home Assistant 2021.6
cv.deprecated(DOMAIN),
{
DOMAIN: vol.Schema(
{
vol.Optional(CONF_SERVER_ID): cv.positive_int,
vol.Optional(
CONF_SCAN_INTERVAL,
default=timedelta(minutes=DEFAULT_SCAN_INTERVAL),
): cv.positive_time_period,
vol.Optional(CONF_MANUAL, default=False): cv.boolean,
vol.Optional(
CONF_MONITORED_CONDITIONS, default=list(SENSOR_KEYS)
): vol.All(cv.ensure_list, [vol.In(list(SENSOR_KEYS))]),
}
)
},
),
extra=vol.ALLOW_EXTRA,
)


def server_id_valid(server_id: str) -> bool:
"""Check if server_id is valid."""
try:
api = speedtest.Speedtest()
api.get_servers([int(server_id)])
except (speedtest.ConfigRetrievalError, speedtest.NoMatchedServers):
return False

return True


async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Import integration from config."""
if DOMAIN in config:
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_IMPORT}, data=config[DOMAIN]
)
)
return True


async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
"""Set up the Speedtest.net component."""
Expand Down Expand Up @@ -145,18 +90,17 @@ def update_servers(self):
for servers in test_servers.values():
for server in servers:
test_servers_list.append(server)
if test_servers_list:
for server in sorted(
test_servers_list,
key=lambda server: (
server["country"],
server["name"],
server["sponsor"],
),
):
self.servers[
f"{server['country']} - {server['sponsor']} - {server['name']}"
] = server
for server in sorted(
test_servers_list,
key=lambda server: (
server["country"],
server["name"],
server["sponsor"],
),
):
self.servers[
f"{server['country']} - {server['sponsor']} - {server['name']}"
] = server

def update_data(self):
"""Get the latest data from speedtest.net."""
Expand Down Expand Up @@ -184,19 +128,6 @@ async def async_update(self) -> dict[str, str]:
except speedtest.SpeedtestException as err:
raise UpdateFailed(err) from err

async def async_set_options(self):
"""Set options for entry."""
if not self.config_entry.options:
data = {**self.config_entry.data}
options = {
CONF_SCAN_INTERVAL: data.pop(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL),
CONF_MANUAL: data.pop(CONF_MANUAL, False),
CONF_SERVER_ID: str(data.pop(CONF_SERVER_ID, "")),
}
self.hass.config_entries.async_update_entry(
self.config_entry, data=data, options=options
)

async def async_setup(self) -> None:
"""Set up SpeedTest."""
try:
Expand All @@ -209,8 +140,6 @@ async def request_update(call):
"""Request update."""
await self.async_request_refresh()

await self.async_set_options()

self.hass.services.async_register(DOMAIN, SPEED_TEST_SERVICE, request_update)

self.config_entry.async_on_unload(
Expand Down
33 changes: 2 additions & 31 deletions homeassistant/components/speedtestdotnet/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,10 @@
import voluptuous as vol

from homeassistant import config_entries
from homeassistant.const import CONF_MONITORED_CONDITIONS, CONF_SCAN_INTERVAL
from homeassistant.const import CONF_SCAN_INTERVAL
from homeassistant.core import callback
from homeassistant.data_entry_flow import FlowResult

from . import server_id_valid
from .const import (
CONF_MANUAL,
CONF_SERVER_ID,
Expand Down Expand Up @@ -47,23 +46,6 @@ async def async_step_user(

return self.async_create_entry(title=DEFAULT_NAME, data=user_input)

async def async_step_import(self, import_config):
"""Import from config."""
if (
CONF_SERVER_ID in import_config
and not await self.hass.async_add_executor_job(
server_id_valid, import_config[CONF_SERVER_ID]
)
):
return self.async_abort(reason="wrong_server_id")

import_config[CONF_SCAN_INTERVAL] = int(
import_config[CONF_SCAN_INTERVAL].total_seconds() / 60
)
import_config.pop(CONF_MONITORED_CONDITIONS)

return await self.async_step_user(user_input=import_config)


class SpeedTestOptionsFlowHandler(config_entries.OptionsFlow):
"""Handle SpeedTest options."""
Expand Down Expand Up @@ -91,21 +73,10 @@ async def async_step_init(

self._servers = self.hass.data[DOMAIN].servers

server = []
if self.config_entry.options.get(
CONF_SERVER_ID
) and not self.config_entry.options.get(CONF_SERVER_NAME):
server = [
key
for (key, value) in self._servers.items()
if value.get("id") == self.config_entry.options[CONF_SERVER_ID]
]
server_name = server[0] if server else DEFAULT_SERVER

options = {
vol.Optional(
CONF_SERVER_NAME,
default=self.config_entry.options.get(CONF_SERVER_NAME, server_name),
default=self.config_entry.options.get(CONF_SERVER_NAME, DEFAULT_SERVER),
): vol.In(self._servers.keys()),
vol.Optional(
CONF_SCAN_INTERVAL,
Expand Down
6 changes: 2 additions & 4 deletions homeassistant/components/speedtestdotnet/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ class SpeedtestSensor(CoordinatorEntity, RestoreEntity, SensorEntity):
"""Implementation of a speedtest.net sensor."""

coordinator: SpeedTestDataCoordinator

_attr_icon = ICON

def __init__(
Expand All @@ -54,7 +53,6 @@ def __init__(
"""Initialize the sensor."""
super().__init__(coordinator)
self.entity_description = description

self._attr_name = f"{DEFAULT_NAME} {description.name}"
self._attr_unique_id = description.key
self._attrs = {ATTR_ATTRIBUTION: ATTRIBUTION}
Expand All @@ -73,10 +71,10 @@ def extra_state_attributes(self) -> dict[str, Any]:

if self.entity_description.key == "download":
self._attrs[ATTR_BYTES_RECEIVED] = self.coordinator.data[
"bytes_received"
ATTR_BYTES_RECEIVED
]
elif self.entity_description.key == "upload":
self._attrs[ATTR_BYTES_SENT] = self.coordinator.data["bytes_sent"]
self._attrs[ATTR_BYTES_SENT] = self.coordinator.data[ATTR_BYTES_SENT]

return self._attrs

Expand Down
44 changes: 1 addition & 43 deletions tests/components/speedtestdotnet/test_config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,15 @@
from datetime import timedelta
from unittest.mock import MagicMock

from speedtest import NoMatchedServers

from homeassistant import config_entries, data_entry_flow
from homeassistant.components import speedtestdotnet
from homeassistant.components.speedtestdotnet.const import (
CONF_MANUAL,
CONF_SERVER_ID,
CONF_SERVER_NAME,
DOMAIN,
SENSOR_TYPES,
)
from homeassistant.const import CONF_MONITORED_CONDITIONS, CONF_SCAN_INTERVAL
from homeassistant.const import CONF_SCAN_INTERVAL
from homeassistant.core import HomeAssistant

from tests.common import MockConfigEntry
Expand All @@ -33,45 +30,6 @@ async def test_flow_works(hass: HomeAssistant) -> None:
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY


async def test_import_fails(hass: HomeAssistant, mock_api: MagicMock) -> None:
"""Test import step fails if server_id is not valid."""

mock_api.return_value.get_servers.side_effect = NoMatchedServers
result = await hass.config_entries.flow.async_init(
speedtestdotnet.DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data={
CONF_SERVER_ID: "223",
CONF_MANUAL: True,
CONF_SCAN_INTERVAL: timedelta(minutes=1),
CONF_MONITORED_CONDITIONS: list(SENSOR_TYPES),
},
)
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
assert result["reason"] == "wrong_server_id"


async def test_import_success(hass):
"""Test import step is successful if server_id is valid."""

result = await hass.config_entries.flow.async_init(
speedtestdotnet.DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data={
CONF_SERVER_ID: "1",
CONF_MANUAL: True,
CONF_SCAN_INTERVAL: timedelta(minutes=1),
CONF_MONITORED_CONDITIONS: list(SENSOR_TYPES),
},
)

assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["title"] == "SpeedTest"
assert result["data"][CONF_SERVER_ID] == "1"
assert result["data"][CONF_MANUAL] is True
assert result["data"][CONF_SCAN_INTERVAL] == 1


async def test_options(hass: HomeAssistant, mock_api: MagicMock) -> None:
"""Test updating options."""
entry = MockConfigEntry(
Expand Down

0 comments on commit 4c40d17

Please sign in to comment.