Enable raise-within-try (TRY301) rule in ruff (#123351)

This commit is contained in:
epenet 2024-08-12 09:16:33 +02:00 committed by GitHub
parent b15ea58851
commit 0bb8c4832d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
32 changed files with 41 additions and 42 deletions

View file

@ -194,7 +194,7 @@ async def async_handle_message(
try: try:
if not enabled: if not enabled:
raise AlexaBridgeUnreachableError( raise AlexaBridgeUnreachableError( # noqa: TRY301
"Alexa API not enabled in Home Assistant configuration" "Alexa API not enabled in Home Assistant configuration"
) )

View file

@ -499,7 +499,7 @@ class AmcrestCam(Camera):
await getattr(self, f"_async_set_{func}")(value) await getattr(self, f"_async_set_{func}")(value)
new_value = await getattr(self, f"_async_get_{func}")() new_value = await getattr(self, f"_async_get_{func}")()
if new_value != value: if new_value != value:
raise AmcrestCommandFailed raise AmcrestCommandFailed # noqa: TRY301
except (AmcrestError, AmcrestCommandFailed) as error: except (AmcrestError, AmcrestCommandFailed) as error:
if tries == 1: if tries == 1:
log_update_error(_LOGGER, action, self.name, description, error) log_update_error(_LOGGER, action, self.name, description, error)

View file

@ -862,7 +862,7 @@ class CameraMjpegStream(CameraView):
# Compose camera stream from stills # Compose camera stream from stills
interval = float(interval_str) interval = float(interval_str)
if interval < MIN_STREAM_INTERVAL: if interval < MIN_STREAM_INTERVAL:
raise ValueError(f"Stream interval must be > {MIN_STREAM_INTERVAL}") raise ValueError(f"Stream interval must be > {MIN_STREAM_INTERVAL}") # noqa: TRY301
return await camera.handle_async_still_stream(request, interval) return await camera.handle_async_still_stream(request, interval)
except ValueError as err: except ValueError as err:
raise web.HTTPBadRequest from err raise web.HTTPBadRequest from err

View file

@ -105,9 +105,9 @@ class Control4ConfigFlow(ConfigFlow, domain=DOMAIN):
) )
try: try:
if not await hub.authenticate(): if not await hub.authenticate():
raise InvalidAuth raise InvalidAuth # noqa: TRY301
if not await hub.connect_to_director(): if not await hub.connect_to_director():
raise CannotConnect raise CannotConnect # noqa: TRY301
except InvalidAuth: except InvalidAuth:
errors["base"] = "invalid_auth" errors["base"] = "invalid_auth"
except CannotConnect: except CannotConnect:

View file

@ -108,7 +108,7 @@ class CurrencylayerData:
try: try:
result = requests.get(self._resource, params=self._parameters, timeout=10) result = requests.get(self._resource, params=self._parameters, timeout=10)
if "error" in result.json(): if "error" in result.json():
raise ValueError(result.json()["error"]["info"]) raise ValueError(result.json()["error"]["info"]) # noqa: TRY301
self.data = result.json()["quotes"] self.data = result.json()["quotes"]
_LOGGER.debug("Currencylayer data updated: %s", result.json()["timestamp"]) _LOGGER.debug("Currencylayer data updated: %s", result.json()["timestamp"])
except ValueError as err: except ValueError as err:

View file

@ -350,7 +350,7 @@ class DeviceTrackerPlatform:
discovery_info, discovery_info,
) )
else: else:
raise HomeAssistantError("Invalid legacy device_tracker platform.") raise HomeAssistantError("Invalid legacy device_tracker platform.") # noqa: TRY301
if scanner is not None: if scanner is not None:
async_setup_scanner_platform( async_setup_scanner_platform(

View file

@ -39,7 +39,7 @@ class DuneHDConfigFlow(ConfigFlow, domain=DOMAIN):
try: try:
if self.host_already_configured(host): if self.host_already_configured(host):
raise AlreadyConfigured raise AlreadyConfigured # noqa: TRY301
await self.init_device(host) await self.init_device(host)
except CannotConnect: except CannotConnect:
errors[CONF_HOST] = "cannot_connect" errors[CONF_HOST] = "cannot_connect"

View file

@ -113,7 +113,7 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool:
server = egardiaserver.EgardiaServer("", rs_port) server = egardiaserver.EgardiaServer("", rs_port)
bound = server.bind() bound = server.bind()
if not bound: if not bound:
raise OSError( raise OSError( # noqa: TRY301
"Binding error occurred while starting EgardiaServer." "Binding error occurred while starting EgardiaServer."
) )
hass.data[EGARDIA_SERVER] = server hass.data[EGARDIA_SERVER] = server

View file

@ -424,7 +424,7 @@ class ElmaxConfigFlow(ConfigFlow, domain=DOMAIN):
if p.hash == self._entry.data[CONF_ELMAX_PANEL_ID] if p.hash == self._entry.data[CONF_ELMAX_PANEL_ID]
] ]
if len(panels) < 1: if len(panels) < 1:
raise NoOnlinePanelsError raise NoOnlinePanelsError # noqa: TRY301
# Verify the pin is still valid. # Verify the pin is still valid.
await client.get_panel_status( await client.get_panel_status(

View file

@ -485,7 +485,7 @@ class GenericThermostat(ClimateEntity, RestoreEntity):
try: try:
cur_temp = float(state.state) cur_temp = float(state.state)
if not math.isfinite(cur_temp): if not math.isfinite(cur_temp):
raise ValueError(f"Sensor has illegal state {state.state}") raise ValueError(f"Sensor has illegal state {state.state}") # noqa: TRY301
self._cur_temp = cur_temp self._cur_temp = cur_temp
except ValueError as ex: except ValueError as ex:
_LOGGER.error("Unable to update from sensor: %s", ex) _LOGGER.error("Unable to update from sensor: %s", ex)

View file

@ -406,7 +406,7 @@ class SensorGroup(GroupEntity, SensorEntity):
and (uom := state.attributes["unit_of_measurement"]) and (uom := state.attributes["unit_of_measurement"])
not in self._valid_units not in self._valid_units
): ):
raise HomeAssistantError("Not a valid unit") raise HomeAssistantError("Not a valid unit") # noqa: TRY301
sensor_values.append((entity_id, numeric_state, state)) sensor_values.append((entity_id, numeric_state, state))
if entity_id in self._state_incorrect: if entity_id in self._state_incorrect:

View file

@ -117,7 +117,7 @@ class IcloudAccount:
if self.api.requires_2fa: if self.api.requires_2fa:
# Trigger a new log in to ensure the user enters the 2FA code again. # Trigger a new log in to ensure the user enters the 2FA code again.
raise PyiCloudFailedLoginException raise PyiCloudFailedLoginException # noqa: TRY301
except PyiCloudFailedLoginException: except PyiCloudFailedLoginException:
self.api = None self.api = None

View file

@ -141,7 +141,7 @@ class IcloudFlowHandler(ConfigFlow, domain=DOMAIN):
getattr, self.api, "devices" getattr, self.api, "devices"
) )
if not devices: if not devices:
raise PyiCloudNoDevicesException raise PyiCloudNoDevicesException # noqa: TRY301
except (PyiCloudServiceNotActivatedException, PyiCloudNoDevicesException): except (PyiCloudServiceNotActivatedException, PyiCloudNoDevicesException):
_LOGGER.error("No device found in the iCloud account: %s", self._username) _LOGGER.error("No device found in the iCloud account: %s", self._username)
self.api = None self.api = None
@ -264,13 +264,13 @@ class IcloudFlowHandler(ConfigFlow, domain=DOMAIN):
if not await self.hass.async_add_executor_job( if not await self.hass.async_add_executor_job(
self.api.validate_2fa_code, self._verification_code self.api.validate_2fa_code, self._verification_code
): ):
raise PyiCloudException("The code you entered is not valid.") raise PyiCloudException("The code you entered is not valid.") # noqa: TRY301
elif not await self.hass.async_add_executor_job( elif not await self.hass.async_add_executor_job(
self.api.validate_verification_code, self.api.validate_verification_code,
self._trusted_device, self._trusted_device,
self._verification_code, self._verification_code,
): ):
raise PyiCloudException("The code you entered is not valid.") raise PyiCloudException("The code you entered is not valid.") # noqa: TRY301
except PyiCloudException as error: except PyiCloudException as error:
# Reset to the initial 2FA state to allow the user to retry # Reset to the initial 2FA state to allow the user to retry
_LOGGER.error("Failed to verify verification code: %s", error) _LOGGER.error("Failed to verify verification code: %s", error)

View file

@ -54,7 +54,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
try: try:
if not await coordinator.async_connect(): if not await coordinator.async_connect():
raise ConfigEntryNotReady(f"Unable to connect to desk {address}") raise ConfigEntryNotReady(f"Unable to connect to desk {address}") # noqa: TRY301
except (AuthFailedError, TimeoutError, BleakError, Exception) as ex: except (AuthFailedError, TimeoutError, BleakError, Exception) as ex:
raise ConfigEntryNotReady(f"Unable to connect to desk {address}") from ex raise ConfigEntryNotReady(f"Unable to connect to desk {address}") from ex

View file

@ -37,7 +37,7 @@ class JvcProjectorConfigFlow(ConfigFlow, domain=DOMAIN):
try: try:
if not is_host_valid(host): if not is_host_valid(host):
raise InvalidHost raise InvalidHost # noqa: TRY301
mac = await get_mac_address(host, port, password) mac = await get_mac_address(host, port, password)
except InvalidHost: except InvalidHost:

View file

@ -38,7 +38,7 @@ class KaleidescapeConfigFlow(ConfigFlow, domain=DOMAIN):
try: try:
info = await validate_host(host) info = await validate_host(host)
if info.server_only: if info.server_only:
raise UnsupportedError raise UnsupportedError # noqa: TRY301
except ConnectionError: except ConnectionError:
errors["base"] = ERROR_CANNOT_CONNECT errors["base"] = ERROR_CANNOT_CONNECT
except UnsupportedError: except UnsupportedError:
@ -73,7 +73,7 @@ class KaleidescapeConfigFlow(ConfigFlow, domain=DOMAIN):
try: try:
self.discovered_device = await validate_host(host) self.discovered_device = await validate_host(host)
if self.discovered_device.server_only: if self.discovered_device.server_only:
raise UnsupportedError raise UnsupportedError # noqa: TRY301
except ConnectionError: except ConnectionError:
return self.async_abort(reason=ERROR_CANNOT_CONNECT) return self.async_abort(reason=ERROR_CANNOT_CONNECT)
except UnsupportedError: except UnsupportedError:

View file

@ -445,7 +445,7 @@ class KNXCommonFlow(ABC, ConfigEntryBaseFlow):
try: try:
key_bytes = bytes.fromhex(user_input[CONF_KNX_ROUTING_BACKBONE_KEY]) key_bytes = bytes.fromhex(user_input[CONF_KNX_ROUTING_BACKBONE_KEY])
if len(key_bytes) != 16: if len(key_bytes) != 16:
raise ValueError raise ValueError # noqa: TRY301
except ValueError: except ValueError:
errors[CONF_KNX_ROUTING_BACKBONE_KEY] = "invalid_backbone_key" errors[CONF_KNX_ROUTING_BACKBONE_KEY] = "invalid_backbone_key"
if not errors: if not errors:

View file

@ -92,7 +92,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
platform.get_handler, hass, p_config, discovery_info platform.get_handler, hass, p_config, discovery_info
) )
else: else:
raise HomeAssistantError("Invalid mailbox platform.") raise HomeAssistantError("Invalid mailbox platform.") # noqa: TRY301
if mailbox is None: if mailbox is None:
_LOGGER.error("Failed to initialize mailbox platform %s", p_type) _LOGGER.error("Failed to initialize mailbox platform %s", p_type)

View file

@ -260,7 +260,7 @@ class MqttSensor(MqttEntity, RestoreSensor):
return return
try: try:
if (payload_datetime := dt_util.parse_datetime(payload)) is None: if (payload_datetime := dt_util.parse_datetime(payload)) is None:
raise ValueError raise ValueError # noqa: TRY301
except ValueError: except ValueError:
_LOGGER.warning("Invalid state message '%s' from '%s'", payload, msg.topic) _LOGGER.warning("Invalid state message '%s' from '%s'", payload, msg.topic)
self._attr_native_value = None self._attr_native_value = None
@ -280,7 +280,7 @@ class MqttSensor(MqttEntity, RestoreSensor):
try: try:
last_reset = dt_util.parse_datetime(str(payload)) last_reset = dt_util.parse_datetime(str(payload))
if last_reset is None: if last_reset is None:
raise ValueError raise ValueError # noqa: TRY301
self._attr_last_reset = last_reset self._attr_last_reset = last_reset
except ValueError: except ValueError:
_LOGGER.warning( _LOGGER.warning(

View file

@ -105,7 +105,7 @@ def async_setup_legacy(
platform.get_service, hass, p_config, discovery_info platform.get_service, hass, p_config, discovery_info
) )
else: else:
raise HomeAssistantError("Invalid notify platform.") raise HomeAssistantError("Invalid notify platform.") # noqa: TRY301
if notify_service is None: if notify_service is None:
# Platforms can decide not to create a service based # Platforms can decide not to create a service based

View file

@ -277,7 +277,7 @@ def execute(hass, filename, source, data=None, return_response=False):
if not isinstance(restricted_globals["output"], dict): if not isinstance(restricted_globals["output"], dict):
output_type = type(restricted_globals["output"]) output_type = type(restricted_globals["output"])
restricted_globals["output"] = {} restricted_globals["output"] = {}
raise ScriptError( raise ScriptError( # noqa: TRY301
f"Expected `output` to be a dictionary, was {output_type}" f"Expected `output` to be a dictionary, was {output_type}"
) )
except ScriptError as err: except ScriptError as err:

View file

@ -102,7 +102,7 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool:
try: try:
raincloud = RainCloudy(username=username, password=password) raincloud = RainCloudy(username=username, password=password)
if not raincloud.is_connected: if not raincloud.is_connected:
raise HTTPError raise HTTPError # noqa: TRY301
hass.data[DATA_RAINCLOUD] = RainCloudHub(raincloud) hass.data[DATA_RAINCLOUD] = RainCloudHub(raincloud)
except (ConnectTimeout, HTTPError) as ex: except (ConnectTimeout, HTTPError) as ex:
_LOGGER.error("Unable to connect to Rain Cloud service: %s", str(ex)) _LOGGER.error("Unable to connect to Rain Cloud service: %s", str(ex))

View file

@ -174,7 +174,7 @@ async def setup_device_v1(
if networking is None: if networking is None:
# If the api does not return an error but does return None for # If the api does not return an error but does return None for
# get_networking - then we need to go through cache checking. # get_networking - then we need to go through cache checking.
raise RoborockException("Networking request returned None.") raise RoborockException("Networking request returned None.") # noqa: TRY301
except RoborockException as err: except RoborockException as err:
_LOGGER.warning( _LOGGER.warning(
"Not setting up %s because we could not get the network information of the device. " "Not setting up %s because we could not get the network information of the device. "

View file

@ -166,7 +166,7 @@ class SignalNotificationService(BaseNotificationService):
and int(str(resp.headers.get("Content-Length"))) and int(str(resp.headers.get("Content-Length")))
> attachment_size_limit > attachment_size_limit
): ):
raise ValueError( raise ValueError( # noqa: TRY301
"Attachment too large (Content-Length reports {}). Max size: {}" "Attachment too large (Content-Length reports {}). Max size: {}"
" bytes".format( " bytes".format(
int(str(resp.headers.get("Content-Length"))), int(str(resp.headers.get("Content-Length"))),
@ -179,7 +179,7 @@ class SignalNotificationService(BaseNotificationService):
for chunk in resp.iter_content(1024): for chunk in resp.iter_content(1024):
size += len(chunk) size += len(chunk)
if size > attachment_size_limit: if size > attachment_size_limit:
raise ValueError( raise ValueError( # noqa: TRY301
f"Attachment too large (Stream reports {size}). " f"Attachment too large (Stream reports {size}). "
f"Max size: {CONF_MAX_ALLOWED_DOWNLOAD_SIZE_BYTES} bytes" f"Max size: {CONF_MAX_ALLOWED_DOWNLOAD_SIZE_BYTES} bytes"
) )

View file

@ -214,7 +214,7 @@ class StarlineFlowHandler(ConfigFlow, domain=DOMAIN):
self._captcha_image = data["captchaImg"] self._captcha_image = data["captchaImg"]
return self._async_form_auth_captcha(error) return self._async_form_auth_captcha(error)
raise Exception(data) # noqa: TRY002 raise Exception(data) # noqa: TRY002, TRY301
except Exception as err: # noqa: BLE001 except Exception as err: # noqa: BLE001
_LOGGER.error("Error auth user: %s", err) _LOGGER.error("Error auth user: %s", err)
return self._async_form_auth_user(ERROR_AUTH_USER) return self._async_form_auth_user(ERROR_AUTH_USER)

View file

@ -42,7 +42,7 @@ class Tami4ConfigFlow(ConfigFlow, domain=DOMAIN):
if m := _PHONE_MATCHER.match(phone): if m := _PHONE_MATCHER.match(phone):
self.phone = f"+972{m.group('number')}" self.phone = f"+972{m.group('number')}"
else: else:
raise InvalidPhoneNumber raise InvalidPhoneNumber # noqa: TRY301
await self.hass.async_add_executor_job( await self.hass.async_add_executor_job(
Tami4EdgeAPI.request_otp, self.phone Tami4EdgeAPI.request_otp, self.phone
) )

View file

@ -318,7 +318,7 @@ class TemplateVacuum(TemplateEntity, StateVacuumEntity):
try: try:
battery_level_int = int(battery_level) battery_level_int = int(battery_level)
if not 0 <= battery_level_int <= 100: if not 0 <= battery_level_int <= 100:
raise ValueError raise ValueError # noqa: TRY301
except ValueError: except ValueError:
_LOGGER.error( _LOGGER.error(
"Received invalid battery level: %s for entity %s. Expected: 0-100", "Received invalid battery level: %s for entity %s. Expected: 0-100",

View file

@ -223,7 +223,7 @@ class ActiveConnection:
try: try:
if schema is False: if schema is False:
if len(msg) > 2: if len(msg) > 2:
raise vol.Invalid("extra keys not allowed") raise vol.Invalid("extra keys not allowed") # noqa: TRY301
handler(self.hass, self, msg) handler(self.hass, self, msg)
else: else:
handler(self.hass, self, schema(msg)) handler(self.hass, self, schema(msg))

View file

@ -339,11 +339,11 @@ class WebSocketHandler:
raise Disconnect from err raise Disconnect from err
if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSED, WSMsgType.CLOSING): if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSED, WSMsgType.CLOSING):
raise Disconnect raise Disconnect # noqa: TRY301
if msg.type != WSMsgType.TEXT: if msg.type != WSMsgType.TEXT:
disconnect_warn = "Received non-Text message." disconnect_warn = "Received non-Text message."
raise Disconnect raise Disconnect # noqa: TRY301
try: try:
auth_msg_data = json_loads(msg.data) auth_msg_data = json_loads(msg.data)

View file

@ -100,7 +100,7 @@ async def load_wyoming_info(
while True: while True:
event = await client.read_event() event = await client.read_event()
if event is None: if event is None:
raise WyomingError( raise WyomingError( # noqa: TRY301
"Connection closed unexpectedly", "Connection closed unexpectedly",
) )

View file

@ -821,8 +821,7 @@ ignore = [
"PLE0605", "PLE0605",
# temporarily disabled # temporarily disabled
"RET503", "RET503"
"TRY301"
] ]
[tool.ruff.lint.flake8-import-conventions.extend-aliases] [tool.ruff.lint.flake8-import-conventions.extend-aliases]

View file

@ -36,7 +36,7 @@ async def get_error_log(hass_ws_client):
def _generate_and_log_exception(exception, log): def _generate_and_log_exception(exception, log):
try: try:
raise Exception(exception) # noqa: TRY002 raise Exception(exception) # noqa: TRY002, TRY301
except Exception: except Exception:
_LOGGER.exception(log) _LOGGER.exception(log)
@ -461,7 +461,7 @@ async def test__figure_out_source(hass: HomeAssistant) -> None:
in a test because the test is not a component. in a test because the test is not a component.
""" """
try: try:
raise ValueError("test") raise ValueError("test") # noqa: TRY301
except ValueError as ex: except ValueError as ex:
exc_info = (type(ex), ex, ex.__traceback__) exc_info = (type(ex), ex, ex.__traceback__)
mock_record = MagicMock( mock_record = MagicMock(
@ -486,7 +486,7 @@ async def test__figure_out_source(hass: HomeAssistant) -> None:
async def test_formatting_exception(hass: HomeAssistant) -> None: async def test_formatting_exception(hass: HomeAssistant) -> None:
"""Test that exceptions are formatted correctly.""" """Test that exceptions are formatted correctly."""
try: try:
raise ValueError("test") raise ValueError("test") # noqa: TRY301
except ValueError as ex: except ValueError as ex:
exc_info = (type(ex), ex, ex.__traceback__) exc_info = (type(ex), ex, ex.__traceback__)
mock_record = MagicMock( mock_record = MagicMock(