Enable raise-within-try (TRY301) rule in ruff (#123351)
This commit is contained in:
parent
b15ea58851
commit
0bb8c4832d
32 changed files with 41 additions and 42 deletions
|
@ -194,7 +194,7 @@ async def async_handle_message(
|
|||
|
||||
try:
|
||||
if not enabled:
|
||||
raise AlexaBridgeUnreachableError(
|
||||
raise AlexaBridgeUnreachableError( # noqa: TRY301
|
||||
"Alexa API not enabled in Home Assistant configuration"
|
||||
)
|
||||
|
||||
|
|
|
@ -499,7 +499,7 @@ class AmcrestCam(Camera):
|
|||
await getattr(self, f"_async_set_{func}")(value)
|
||||
new_value = await getattr(self, f"_async_get_{func}")()
|
||||
if new_value != value:
|
||||
raise AmcrestCommandFailed
|
||||
raise AmcrestCommandFailed # noqa: TRY301
|
||||
except (AmcrestError, AmcrestCommandFailed) as error:
|
||||
if tries == 1:
|
||||
log_update_error(_LOGGER, action, self.name, description, error)
|
||||
|
|
|
@ -862,7 +862,7 @@ class CameraMjpegStream(CameraView):
|
|||
# Compose camera stream from stills
|
||||
interval = float(interval_str)
|
||||
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)
|
||||
except ValueError as err:
|
||||
raise web.HTTPBadRequest from err
|
||||
|
|
|
@ -105,9 +105,9 @@ class Control4ConfigFlow(ConfigFlow, domain=DOMAIN):
|
|||
)
|
||||
try:
|
||||
if not await hub.authenticate():
|
||||
raise InvalidAuth
|
||||
raise InvalidAuth # noqa: TRY301
|
||||
if not await hub.connect_to_director():
|
||||
raise CannotConnect
|
||||
raise CannotConnect # noqa: TRY301
|
||||
except InvalidAuth:
|
||||
errors["base"] = "invalid_auth"
|
||||
except CannotConnect:
|
||||
|
|
|
@ -108,7 +108,7 @@ class CurrencylayerData:
|
|||
try:
|
||||
result = requests.get(self._resource, params=self._parameters, timeout=10)
|
||||
if "error" in result.json():
|
||||
raise ValueError(result.json()["error"]["info"])
|
||||
raise ValueError(result.json()["error"]["info"]) # noqa: TRY301
|
||||
self.data = result.json()["quotes"]
|
||||
_LOGGER.debug("Currencylayer data updated: %s", result.json()["timestamp"])
|
||||
except ValueError as err:
|
||||
|
|
|
@ -350,7 +350,7 @@ class DeviceTrackerPlatform:
|
|||
discovery_info,
|
||||
)
|
||||
else:
|
||||
raise HomeAssistantError("Invalid legacy device_tracker platform.")
|
||||
raise HomeAssistantError("Invalid legacy device_tracker platform.") # noqa: TRY301
|
||||
|
||||
if scanner is not None:
|
||||
async_setup_scanner_platform(
|
||||
|
|
|
@ -39,7 +39,7 @@ class DuneHDConfigFlow(ConfigFlow, domain=DOMAIN):
|
|||
|
||||
try:
|
||||
if self.host_already_configured(host):
|
||||
raise AlreadyConfigured
|
||||
raise AlreadyConfigured # noqa: TRY301
|
||||
await self.init_device(host)
|
||||
except CannotConnect:
|
||||
errors[CONF_HOST] = "cannot_connect"
|
||||
|
|
|
@ -113,7 +113,7 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
|||
server = egardiaserver.EgardiaServer("", rs_port)
|
||||
bound = server.bind()
|
||||
if not bound:
|
||||
raise OSError(
|
||||
raise OSError( # noqa: TRY301
|
||||
"Binding error occurred while starting EgardiaServer."
|
||||
)
|
||||
hass.data[EGARDIA_SERVER] = server
|
||||
|
|
|
@ -424,7 +424,7 @@ class ElmaxConfigFlow(ConfigFlow, domain=DOMAIN):
|
|||
if p.hash == self._entry.data[CONF_ELMAX_PANEL_ID]
|
||||
]
|
||||
if len(panels) < 1:
|
||||
raise NoOnlinePanelsError
|
||||
raise NoOnlinePanelsError # noqa: TRY301
|
||||
|
||||
# Verify the pin is still valid.
|
||||
await client.get_panel_status(
|
||||
|
|
|
@ -485,7 +485,7 @@ class GenericThermostat(ClimateEntity, RestoreEntity):
|
|||
try:
|
||||
cur_temp = float(state.state)
|
||||
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
|
||||
except ValueError as ex:
|
||||
_LOGGER.error("Unable to update from sensor: %s", ex)
|
||||
|
|
|
@ -406,7 +406,7 @@ class SensorGroup(GroupEntity, SensorEntity):
|
|||
and (uom := state.attributes["unit_of_measurement"])
|
||||
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))
|
||||
if entity_id in self._state_incorrect:
|
||||
|
|
|
@ -117,7 +117,7 @@ class IcloudAccount:
|
|||
|
||||
if self.api.requires_2fa:
|
||||
# Trigger a new log in to ensure the user enters the 2FA code again.
|
||||
raise PyiCloudFailedLoginException
|
||||
raise PyiCloudFailedLoginException # noqa: TRY301
|
||||
|
||||
except PyiCloudFailedLoginException:
|
||||
self.api = None
|
||||
|
|
|
@ -141,7 +141,7 @@ class IcloudFlowHandler(ConfigFlow, domain=DOMAIN):
|
|||
getattr, self.api, "devices"
|
||||
)
|
||||
if not devices:
|
||||
raise PyiCloudNoDevicesException
|
||||
raise PyiCloudNoDevicesException # noqa: TRY301
|
||||
except (PyiCloudServiceNotActivatedException, PyiCloudNoDevicesException):
|
||||
_LOGGER.error("No device found in the iCloud account: %s", self._username)
|
||||
self.api = None
|
||||
|
@ -264,13 +264,13 @@ class IcloudFlowHandler(ConfigFlow, domain=DOMAIN):
|
|||
if not await self.hass.async_add_executor_job(
|
||||
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(
|
||||
self.api.validate_verification_code,
|
||||
self._trusted_device,
|
||||
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:
|
||||
# Reset to the initial 2FA state to allow the user to retry
|
||||
_LOGGER.error("Failed to verify verification code: %s", error)
|
||||
|
|
|
@ -54,7 +54,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
|||
|
||||
try:
|
||||
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:
|
||||
raise ConfigEntryNotReady(f"Unable to connect to desk {address}") from ex
|
||||
|
||||
|
|
|
@ -37,7 +37,7 @@ class JvcProjectorConfigFlow(ConfigFlow, domain=DOMAIN):
|
|||
|
||||
try:
|
||||
if not is_host_valid(host):
|
||||
raise InvalidHost
|
||||
raise InvalidHost # noqa: TRY301
|
||||
|
||||
mac = await get_mac_address(host, port, password)
|
||||
except InvalidHost:
|
||||
|
|
|
@ -38,7 +38,7 @@ class KaleidescapeConfigFlow(ConfigFlow, domain=DOMAIN):
|
|||
try:
|
||||
info = await validate_host(host)
|
||||
if info.server_only:
|
||||
raise UnsupportedError
|
||||
raise UnsupportedError # noqa: TRY301
|
||||
except ConnectionError:
|
||||
errors["base"] = ERROR_CANNOT_CONNECT
|
||||
except UnsupportedError:
|
||||
|
@ -73,7 +73,7 @@ class KaleidescapeConfigFlow(ConfigFlow, domain=DOMAIN):
|
|||
try:
|
||||
self.discovered_device = await validate_host(host)
|
||||
if self.discovered_device.server_only:
|
||||
raise UnsupportedError
|
||||
raise UnsupportedError # noqa: TRY301
|
||||
except ConnectionError:
|
||||
return self.async_abort(reason=ERROR_CANNOT_CONNECT)
|
||||
except UnsupportedError:
|
||||
|
|
|
@ -445,7 +445,7 @@ class KNXCommonFlow(ABC, ConfigEntryBaseFlow):
|
|||
try:
|
||||
key_bytes = bytes.fromhex(user_input[CONF_KNX_ROUTING_BACKBONE_KEY])
|
||||
if len(key_bytes) != 16:
|
||||
raise ValueError
|
||||
raise ValueError # noqa: TRY301
|
||||
except ValueError:
|
||||
errors[CONF_KNX_ROUTING_BACKBONE_KEY] = "invalid_backbone_key"
|
||||
if not errors:
|
||||
|
|
|
@ -92,7 +92,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
|||
platform.get_handler, hass, p_config, discovery_info
|
||||
)
|
||||
else:
|
||||
raise HomeAssistantError("Invalid mailbox platform.")
|
||||
raise HomeAssistantError("Invalid mailbox platform.") # noqa: TRY301
|
||||
|
||||
if mailbox is None:
|
||||
_LOGGER.error("Failed to initialize mailbox platform %s", p_type)
|
||||
|
|
|
@ -260,7 +260,7 @@ class MqttSensor(MqttEntity, RestoreSensor):
|
|||
return
|
||||
try:
|
||||
if (payload_datetime := dt_util.parse_datetime(payload)) is None:
|
||||
raise ValueError
|
||||
raise ValueError # noqa: TRY301
|
||||
except ValueError:
|
||||
_LOGGER.warning("Invalid state message '%s' from '%s'", payload, msg.topic)
|
||||
self._attr_native_value = None
|
||||
|
@ -280,7 +280,7 @@ class MqttSensor(MqttEntity, RestoreSensor):
|
|||
try:
|
||||
last_reset = dt_util.parse_datetime(str(payload))
|
||||
if last_reset is None:
|
||||
raise ValueError
|
||||
raise ValueError # noqa: TRY301
|
||||
self._attr_last_reset = last_reset
|
||||
except ValueError:
|
||||
_LOGGER.warning(
|
||||
|
|
|
@ -105,7 +105,7 @@ def async_setup_legacy(
|
|||
platform.get_service, hass, p_config, discovery_info
|
||||
)
|
||||
else:
|
||||
raise HomeAssistantError("Invalid notify platform.")
|
||||
raise HomeAssistantError("Invalid notify platform.") # noqa: TRY301
|
||||
|
||||
if notify_service is None:
|
||||
# Platforms can decide not to create a service based
|
||||
|
|
|
@ -277,7 +277,7 @@ def execute(hass, filename, source, data=None, return_response=False):
|
|||
if not isinstance(restricted_globals["output"], dict):
|
||||
output_type = type(restricted_globals["output"])
|
||||
restricted_globals["output"] = {}
|
||||
raise ScriptError(
|
||||
raise ScriptError( # noqa: TRY301
|
||||
f"Expected `output` to be a dictionary, was {output_type}"
|
||||
)
|
||||
except ScriptError as err:
|
||||
|
|
|
@ -102,7 +102,7 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
|||
try:
|
||||
raincloud = RainCloudy(username=username, password=password)
|
||||
if not raincloud.is_connected:
|
||||
raise HTTPError
|
||||
raise HTTPError # noqa: TRY301
|
||||
hass.data[DATA_RAINCLOUD] = RainCloudHub(raincloud)
|
||||
except (ConnectTimeout, HTTPError) as ex:
|
||||
_LOGGER.error("Unable to connect to Rain Cloud service: %s", str(ex))
|
||||
|
|
|
@ -174,7 +174,7 @@ async def setup_device_v1(
|
|||
if networking is None:
|
||||
# If the api does not return an error but does return None for
|
||||
# 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:
|
||||
_LOGGER.warning(
|
||||
"Not setting up %s because we could not get the network information of the device. "
|
||||
|
|
|
@ -166,7 +166,7 @@ class SignalNotificationService(BaseNotificationService):
|
|||
and int(str(resp.headers.get("Content-Length")))
|
||||
> attachment_size_limit
|
||||
):
|
||||
raise ValueError(
|
||||
raise ValueError( # noqa: TRY301
|
||||
"Attachment too large (Content-Length reports {}). Max size: {}"
|
||||
" bytes".format(
|
||||
int(str(resp.headers.get("Content-Length"))),
|
||||
|
@ -179,7 +179,7 @@ class SignalNotificationService(BaseNotificationService):
|
|||
for chunk in resp.iter_content(1024):
|
||||
size += len(chunk)
|
||||
if size > attachment_size_limit:
|
||||
raise ValueError(
|
||||
raise ValueError( # noqa: TRY301
|
||||
f"Attachment too large (Stream reports {size}). "
|
||||
f"Max size: {CONF_MAX_ALLOWED_DOWNLOAD_SIZE_BYTES} bytes"
|
||||
)
|
||||
|
|
|
@ -214,7 +214,7 @@ class StarlineFlowHandler(ConfigFlow, domain=DOMAIN):
|
|||
self._captcha_image = data["captchaImg"]
|
||||
return self._async_form_auth_captcha(error)
|
||||
|
||||
raise Exception(data) # noqa: TRY002
|
||||
raise Exception(data) # noqa: TRY002, TRY301
|
||||
except Exception as err: # noqa: BLE001
|
||||
_LOGGER.error("Error auth user: %s", err)
|
||||
return self._async_form_auth_user(ERROR_AUTH_USER)
|
||||
|
|
|
@ -42,7 +42,7 @@ class Tami4ConfigFlow(ConfigFlow, domain=DOMAIN):
|
|||
if m := _PHONE_MATCHER.match(phone):
|
||||
self.phone = f"+972{m.group('number')}"
|
||||
else:
|
||||
raise InvalidPhoneNumber
|
||||
raise InvalidPhoneNumber # noqa: TRY301
|
||||
await self.hass.async_add_executor_job(
|
||||
Tami4EdgeAPI.request_otp, self.phone
|
||||
)
|
||||
|
|
|
@ -318,7 +318,7 @@ class TemplateVacuum(TemplateEntity, StateVacuumEntity):
|
|||
try:
|
||||
battery_level_int = int(battery_level)
|
||||
if not 0 <= battery_level_int <= 100:
|
||||
raise ValueError
|
||||
raise ValueError # noqa: TRY301
|
||||
except ValueError:
|
||||
_LOGGER.error(
|
||||
"Received invalid battery level: %s for entity %s. Expected: 0-100",
|
||||
|
|
|
@ -223,7 +223,7 @@ class ActiveConnection:
|
|||
try:
|
||||
if schema is False:
|
||||
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)
|
||||
else:
|
||||
handler(self.hass, self, schema(msg))
|
||||
|
|
|
@ -339,11 +339,11 @@ class WebSocketHandler:
|
|||
raise Disconnect from err
|
||||
|
||||
if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSED, WSMsgType.CLOSING):
|
||||
raise Disconnect
|
||||
raise Disconnect # noqa: TRY301
|
||||
|
||||
if msg.type != WSMsgType.TEXT:
|
||||
disconnect_warn = "Received non-Text message."
|
||||
raise Disconnect
|
||||
raise Disconnect # noqa: TRY301
|
||||
|
||||
try:
|
||||
auth_msg_data = json_loads(msg.data)
|
||||
|
|
|
@ -100,7 +100,7 @@ async def load_wyoming_info(
|
|||
while True:
|
||||
event = await client.read_event()
|
||||
if event is None:
|
||||
raise WyomingError(
|
||||
raise WyomingError( # noqa: TRY301
|
||||
"Connection closed unexpectedly",
|
||||
)
|
||||
|
||||
|
|
|
@ -821,8 +821,7 @@ ignore = [
|
|||
"PLE0605",
|
||||
|
||||
# temporarily disabled
|
||||
"RET503",
|
||||
"TRY301"
|
||||
"RET503"
|
||||
]
|
||||
|
||||
[tool.ruff.lint.flake8-import-conventions.extend-aliases]
|
||||
|
|
|
@ -36,7 +36,7 @@ async def get_error_log(hass_ws_client):
|
|||
|
||||
def _generate_and_log_exception(exception, log):
|
||||
try:
|
||||
raise Exception(exception) # noqa: TRY002
|
||||
raise Exception(exception) # noqa: TRY002, TRY301
|
||||
except Exception:
|
||||
_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.
|
||||
"""
|
||||
try:
|
||||
raise ValueError("test")
|
||||
raise ValueError("test") # noqa: TRY301
|
||||
except ValueError as ex:
|
||||
exc_info = (type(ex), ex, ex.__traceback__)
|
||||
mock_record = MagicMock(
|
||||
|
@ -486,7 +486,7 @@ async def test__figure_out_source(hass: HomeAssistant) -> None:
|
|||
async def test_formatting_exception(hass: HomeAssistant) -> None:
|
||||
"""Test that exceptions are formatted correctly."""
|
||||
try:
|
||||
raise ValueError("test")
|
||||
raise ValueError("test") # noqa: TRY301
|
||||
except ValueError as ex:
|
||||
exc_info = (type(ex), ex, ex.__traceback__)
|
||||
mock_record = MagicMock(
|
||||
|
|
Loading…
Add table
Reference in a new issue