Use pysma exceptions (#52252)

This commit is contained in:
René Klomp 2021-06-28 16:59:17 +02:00 committed by GitHub
parent 3a5ee00081
commit 540d6e9fa5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 34 additions and 33 deletions

View File

@ -142,10 +142,16 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
session = async_get_clientsession(hass, verify_ssl=verify_ssl) session = async_get_clientsession(hass, verify_ssl=verify_ssl)
sma = pysma.SMA(session, url, password, group) sma = pysma.SMA(session, url, password, group)
try:
# Get updated device info # Get updated device info
device_info = await sma.device_info() device_info = await sma.device_info()
# Get all device sensors # Get all device sensors
sensor_def = await sma.get_sensors() sensor_def = await sma.get_sensors()
except (
pysma.exceptions.SmaReadException,
pysma.exceptions.SmaConnectionException,
) as exc:
raise ConfigEntryNotReady from exc
# Parse legacy options if initial setup was done from yaml # Parse legacy options if initial setup was done from yaml
if entry.source == SOURCE_IMPORT: if entry.source == SOURCE_IMPORT:
@ -155,9 +161,13 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
# Define the coordinator # Define the coordinator
async def async_update_data(): async def async_update_data():
"""Update the used SMA sensors.""" """Update the used SMA sensors."""
values = await sma.read(sensor_def) try:
if not values: await sma.read(sensor_def)
raise UpdateFailed except (
pysma.exceptions.SmaReadException,
pysma.exceptions.SmaConnectionException,
) as exc:
raise UpdateFailed from exc
interval = timedelta( interval = timedelta(
seconds=entry.options.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) seconds=entry.options.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL)

View File

@ -4,11 +4,10 @@ from __future__ import annotations
import logging import logging
from typing import Any from typing import Any
import aiohttp
import pysma import pysma
import voluptuous as vol import voluptuous as vol
from homeassistant import config_entries, core, exceptions from homeassistant import config_entries, core
from homeassistant.const import ( from homeassistant.const import (
CONF_HOST, CONF_HOST,
CONF_PASSWORD, CONF_PASSWORD,
@ -36,15 +35,11 @@ async def validate_input(
sma = pysma.SMA(session, url, data[CONF_PASSWORD], group=data[CONF_GROUP]) sma = pysma.SMA(session, url, data[CONF_PASSWORD], group=data[CONF_GROUP])
if await sma.new_session() is False: # new_session raises SmaAuthenticationException on failure
raise InvalidAuth await sma.new_session()
device_info = await sma.device_info() device_info = await sma.device_info()
await sma.close_session() await sma.close_session()
if not device_info:
raise CannotRetrieveDeviceInfo
return device_info return device_info
@ -79,11 +74,11 @@ class SmaConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
try: try:
device_info = await validate_input(self.hass, user_input) device_info = await validate_input(self.hass, user_input)
except aiohttp.ClientError: except pysma.exceptions.SmaConnectionException:
errors["base"] = "cannot_connect" errors["base"] = "cannot_connect"
except InvalidAuth: except pysma.exceptions.SmaAuthenticationException:
errors["base"] = "invalid_auth" errors["base"] = "invalid_auth"
except CannotRetrieveDeviceInfo: except pysma.exceptions.SmaReadException:
errors["base"] = "cannot_retrieve_device_info" errors["base"] = "cannot_retrieve_device_info"
except Exception: # pylint: disable=broad-except except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception") _LOGGER.exception("Unexpected exception")
@ -128,11 +123,3 @@ class SmaConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
return self.async_create_entry( return self.async_create_entry(
title=import_config[CONF_HOST], data=import_config title=import_config[CONF_HOST], data=import_config
) )
class InvalidAuth(exceptions.HomeAssistantError):
"""Error to indicate there is invalid auth."""
class CannotRetrieveDeviceInfo(exceptions.HomeAssistantError):
"""Error to indicate we cannot retrieve the device information."""

View File

@ -3,7 +3,7 @@
"name": "SMA Solar", "name": "SMA Solar",
"config_flow": true, "config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/sma", "documentation": "https://www.home-assistant.io/integrations/sma",
"requirements": ["pysma==0.5.0"], "requirements": ["pysma==0.6.0"],
"codeowners": ["@kellerza", "@rklomp"], "codeowners": ["@kellerza", "@rklomp"],
"iot_class": "local_polling" "iot_class": "local_polling"
} }

View File

@ -1747,7 +1747,7 @@ pysignalclirestapi==0.3.4
pyskyqhub==0.1.3 pyskyqhub==0.1.3
# homeassistant.components.sma # homeassistant.components.sma
pysma==0.5.0 pysma==0.6.0
# homeassistant.components.smappee # homeassistant.components.smappee
pysmappee==0.2.25 pysmappee==0.2.25

View File

@ -989,7 +989,7 @@ pysiaalarm==3.0.0
pysignalclirestapi==0.3.4 pysignalclirestapi==0.3.4
# homeassistant.components.sma # homeassistant.components.sma
pysma==0.5.0 pysma==0.6.0
# homeassistant.components.smappee # homeassistant.components.smappee
pysmappee==0.2.25 pysmappee==0.2.25

View File

@ -1,7 +1,11 @@
"""Test the sma config flow.""" """Test the sma config flow."""
from unittest.mock import patch from unittest.mock import patch
import aiohttp from pysma.exceptions import (
SmaAuthenticationException,
SmaConnectionException,
SmaReadException,
)
from homeassistant import setup from homeassistant import setup
from homeassistant.components.sma.const import DOMAIN from homeassistant.components.sma.const import DOMAIN
@ -54,7 +58,7 @@ async def test_form_cannot_connect(hass):
) )
with patch( with patch(
"pysma.SMA.new_session", side_effect=aiohttp.ClientError "pysma.SMA.new_session", side_effect=SmaConnectionException
), _patch_async_setup_entry() as mock_setup_entry: ), _patch_async_setup_entry() as mock_setup_entry:
result = await hass.config_entries.flow.async_configure( result = await hass.config_entries.flow.async_configure(
result["flow_id"], result["flow_id"],
@ -73,7 +77,7 @@ async def test_form_invalid_auth(hass):
) )
with patch( with patch(
"pysma.SMA.new_session", return_value=False "pysma.SMA.new_session", side_effect=SmaAuthenticationException
), _patch_async_setup_entry() as mock_setup_entry: ), _patch_async_setup_entry() as mock_setup_entry:
result = await hass.config_entries.flow.async_configure( result = await hass.config_entries.flow.async_configure(
result["flow_id"], result["flow_id"],
@ -92,7 +96,7 @@ async def test_form_cannot_retrieve_device_info(hass):
) )
with patch("pysma.SMA.new_session", return_value=True), patch( with patch("pysma.SMA.new_session", return_value=True), patch(
"pysma.SMA.read", return_value=False "pysma.SMA.read", side_effect=SmaReadException
), _patch_async_setup_entry() as mock_setup_entry: ), _patch_async_setup_entry() as mock_setup_entry:
result = await hass.config_entries.flow.async_configure( result = await hass.config_entries.flow.async_configure(
result["flow_id"], result["flow_id"],