Enable Ruff TRY004 (#86811)

This commit is contained in:
Franck Nijhof 2023-01-30 14:06:52 +01:00 committed by GitHub
parent 7368c86ecb
commit 3b5fd4bd06
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
19 changed files with 24 additions and 22 deletions

View file

@ -438,7 +438,7 @@ def _create_auth_code_store() -> tuple[StoreResultType, RetrieveResultType]:
def store_result(client_id: str, result: Credentials) -> str: def store_result(client_id: str, result: Credentials) -> str:
"""Store flow result and return a code to retrieve it.""" """Store flow result and return a code to retrieve it."""
if not isinstance(result, Credentials): if not isinstance(result, Credentials):
raise ValueError("result has to be a Credentials instance") raise TypeError("result has to be a Credentials instance")
code = uuid.uuid4().hex code = uuid.uuid4().hex
temp_results[(client_id, code)] = ( temp_results[(client_id, code)] = (

View file

@ -285,7 +285,7 @@ class PassiveBluetoothDataProcessor(Generic[_T]):
if not isinstance(new_data, PassiveBluetoothDataUpdate): if not isinstance(new_data, PassiveBluetoothDataUpdate):
self.last_update_success = False # type: ignore[unreachable] self.last_update_success = False # type: ignore[unreachable]
raise ValueError( raise TypeError(
f"The update_method for {self.coordinator.name} returned" f"The update_method for {self.coordinator.name} returned"
f" {new_data} instead of a PassiveBluetoothDataUpdate" f" {new_data} instead of a PassiveBluetoothDataUpdate"
) )

View file

@ -69,7 +69,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
) )
) )
if not isinstance(implementation, LyricLocalOAuth2Implementation): if not isinstance(implementation, LyricLocalOAuth2Implementation):
raise ValueError("Unexpected auth implementation; can't find oauth client id") raise TypeError("Unexpected auth implementation; can't find oauth client id")
session = aiohttp_client.async_get_clientsession(hass) session = aiohttp_client.async_get_clientsession(hass)
oauth_session = OAuth2SessionLyric(hass, entry, implementation) oauth_session = OAuth2SessionLyric(hass, entry, implementation)

View file

@ -111,7 +111,7 @@ async def new_subscriber(
if not isinstance( if not isinstance(
implementation, config_entry_oauth2_flow.LocalOAuth2Implementation implementation, config_entry_oauth2_flow.LocalOAuth2Implementation
): ):
raise ValueError(f"Unexpected auth implementation {implementation}") raise TypeError(f"Unexpected auth implementation {implementation}")
if not (subscriber_id := entry.data.get(CONF_SUBSCRIBER_ID)): if not (subscriber_id := entry.data.get(CONF_SUBSCRIBER_ID)):
raise ValueError("Configuration option 'subscriber_id' missing") raise ValueError("Configuration option 'subscriber_id' missing")
auth = AsyncConfigEntryAuth( auth = AsyncConfigEntryAuth(

View file

@ -378,7 +378,7 @@ class NestFlowHandler(
if not isinstance( if not isinstance(
self.flow_impl, config_entry_oauth2_flow.LocalOAuth2Implementation self.flow_impl, config_entry_oauth2_flow.LocalOAuth2Implementation
): ):
raise ValueError(f"Unexpected OAuth implementation: {self.flow_impl}") raise TypeError(f"Unexpected OAuth implementation: {self.flow_impl}")
client_id = self.flow_impl.client_id client_id = self.flow_impl.client_id
return self.async_show_form( return self.async_show_form(
step_id="device_project_upgrade", step_id="device_project_upgrade",

View file

@ -88,21 +88,21 @@ async def async_setup_platform(
async def handle_async_join(entity, service_call): async def handle_async_join(entity, service_call):
"""Handle the entity service join.""" """Handle the entity service join."""
if not isinstance(entity, SnapcastClientDevice): if not isinstance(entity, SnapcastClientDevice):
raise ValueError("Entity is not a client. Can only join clients.") raise TypeError("Entity is not a client. Can only join clients.")
await entity.async_join(service_call.data[ATTR_MASTER]) await entity.async_join(service_call.data[ATTR_MASTER])
async def handle_async_unjoin(entity, service_call): async def handle_async_unjoin(entity, service_call):
"""Handle the entity service unjoin.""" """Handle the entity service unjoin."""
if not isinstance(entity, SnapcastClientDevice): if not isinstance(entity, SnapcastClientDevice):
raise ValueError("Entity is not a client. Can only unjoin clients.") raise TypeError("Entity is not a client. Can only unjoin clients.")
await entity.async_unjoin() await entity.async_unjoin()
async def handle_set_latency(entity, service_call): async def handle_set_latency(entity, service_call):
"""Handle the entity service set_latency.""" """Handle the entity service set_latency."""
if not isinstance(entity, SnapcastClientDevice): if not isinstance(entity, SnapcastClientDevice):
raise ValueError("Latency can only be set for a Snapcast client.") raise TypeError("Latency can only be set for a Snapcast client.")
await entity.async_set_latency(service_call.data[ATTR_LATENCY]) await entity.async_set_latency(service_call.data[ATTR_LATENCY])
@ -309,7 +309,7 @@ class SnapcastClientDevice(MediaPlayerEntity):
entity for entity in self.hass.data[DATA_KEY] if entity.entity_id == master entity for entity in self.hass.data[DATA_KEY] if entity.entity_id == master
) )
if not isinstance(master_entity, SnapcastClientDevice): if not isinstance(master_entity, SnapcastClientDevice):
raise ValueError("Master is not a client device. Can only join clients.") raise TypeError("Master is not a client device. Can only join clients.")
master_group = next( master_group = next(
group group

View file

@ -547,7 +547,7 @@ class TelegramNotificationService:
InlineKeyboardButton(text_btn, callback_data=data_btn) InlineKeyboardButton(text_btn, callback_data=data_btn)
) )
else: else:
raise ValueError(str(row_keyboard)) raise TypeError(str(row_keyboard))
return buttons return buttons
# Defaults # Defaults

View file

@ -142,7 +142,7 @@ class ValloxState:
"""Return cached UUID value.""" """Return cached UUID value."""
uuid = _api_get_uuid(self.metric_cache) uuid = _api_get_uuid(self.metric_cache)
if not isinstance(uuid, UUID): if not isinstance(uuid, UUID):
raise ValueError raise TypeError
return uuid return uuid
def get_next_filter_change_date(self) -> date | None: def get_next_filter_change_date(self) -> date | None:

View file

@ -90,20 +90,20 @@ async def async_setup_entry(
# Handle services for a discovered WiLight device. # Handle services for a discovered WiLight device.
async def set_watering_time(entity, service: Any) -> None: async def set_watering_time(entity, service: Any) -> None:
if not isinstance(entity, WiLightValveSwitch): if not isinstance(entity, WiLightValveSwitch):
raise ValueError("Entity is not a WiLight valve switch") raise TypeError("Entity is not a WiLight valve switch")
watering_time = service.data[ATTR_WATERING_TIME] watering_time = service.data[ATTR_WATERING_TIME]
await entity.async_set_watering_time(watering_time=watering_time) await entity.async_set_watering_time(watering_time=watering_time)
async def set_trigger(entity, service: Any) -> None: async def set_trigger(entity, service: Any) -> None:
if not isinstance(entity, WiLightValveSwitch): if not isinstance(entity, WiLightValveSwitch):
raise ValueError("Entity is not a WiLight valve switch") raise TypeError("Entity is not a WiLight valve switch")
trigger_index = service.data[ATTR_TRIGGER_INDEX] trigger_index = service.data[ATTR_TRIGGER_INDEX]
trigger = service.data[ATTR_TRIGGER] trigger = service.data[ATTR_TRIGGER]
await entity.async_set_trigger(trigger_index=trigger_index, trigger=trigger) await entity.async_set_trigger(trigger_index=trigger_index, trigger=trigger)
async def set_pause_time(entity, service: Any) -> None: async def set_pause_time(entity, service: Any) -> None:
if not isinstance(entity, WiLightValvePauseSwitch): if not isinstance(entity, WiLightValvePauseSwitch):
raise ValueError("Entity is not a WiLight valve pause switch") raise TypeError("Entity is not a WiLight valve pause switch")
pause_time = service.data[ATTR_PAUSE_TIME] pause_time = service.data[ATTR_PAUSE_TIME]
await entity.async_set_pause_time(pause_time=pause_time) await entity.async_set_pause_time(pause_time=pause_time)

View file

@ -89,7 +89,7 @@ def serialize_response(response: web.Response) -> dict[str, Any]:
elif isinstance(body, bytes): elif isinstance(body, bytes):
body_decoded = body.decode(response.charset or "utf-8") body_decoded = body.decode(response.charset or "utf-8")
else: else:
raise ValueError("Unknown payload encoding") raise TypeError("Unknown payload encoding")
return { return {
"status": response.status, "status": response.status,

View file

@ -256,6 +256,7 @@ select = [
"SIM300", # Yoda conditions. Use 'age == 42' instead of '42 == age'. "SIM300", # Yoda conditions. Use 'age == 42' instead of '42 == age'.
"SIM401", # Use get from dict with default instead of an if block "SIM401", # Use get from dict with default instead of an if block
"T20", # flake8-print "T20", # flake8-print
"TRY004", # Prefer TypeError exception for invalid type
"UP", # pyupgrade "UP", # pyupgrade
"W", # pycodestyle "W", # pycodestyle
] ]

View file

@ -29,5 +29,6 @@ noqa-require-code = True
# and probably need to clean up a couple of noqa comments. # and probably need to clean up a couple of noqa comments.
per-file-ignores = per-file-ignores =
homeassistant/config.py:NQA102 homeassistant/config.py:NQA102
tests/components/august/mocks.py:NQA102
tests/components/tts/conftest.py:NQA102 tests/components/tts/conftest.py:NQA102
tests/helpers/test_icon.py:NQA102 tests/helpers/test_icon.py:NQA102

View file

@ -1363,7 +1363,7 @@ ANY = _HA_ANY()
def raise_contains_mocks(val: Any) -> None: def raise_contains_mocks(val: Any) -> None:
"""Raise for mocks.""" """Raise for mocks."""
if isinstance(val, Mock): if isinstance(val, Mock):
raise ValueError raise TypeError
if isinstance(val, dict): if isinstance(val, dict):
for dict_value in val.values(): for dict_value in val.values():

View file

@ -113,7 +113,7 @@ async def _create_august_api_with_devices( # noqa: C901
{"base": _mock_august_doorbell(device.device_id), "detail": device} {"base": _mock_august_doorbell(device.device_id), "detail": device}
) )
else: else:
raise ValueError raise ValueError # noqa: TRY004
def _get_device_detail(device_type, device_id): def _get_device_detail(device_type, device_id):
for device in device_data[device_type]: for device in device_data[device_type]:

View file

@ -188,7 +188,7 @@ def test_auth_code_store_requires_credentials(mock_credential):
"""Test we require credentials.""" """Test we require credentials."""
store, _retrieve = auth._create_auth_code_store() store, _retrieve = auth._create_auth_code_store()
with pytest.raises(ValueError): with pytest.raises(TypeError):
store(None, MockUser()) store(None, MockUser())
store(None, mock_credential) store(None, mock_credential)

View file

@ -479,7 +479,7 @@ async def test_bad_data_from_update_method(
assert processor.available is True assert processor.available is True
# We should go unavailable once we get bad data # We should go unavailable once we get bad data
with pytest.raises(ValueError): with pytest.raises(TypeError):
saved_callback(GENERIC_BLUETOOTH_SERVICE_INFO_2, BluetoothChange.ADVERTISEMENT) saved_callback(GENERIC_BLUETOOTH_SERVICE_INFO_2, BluetoothChange.ADVERTISEMENT)
assert processor.available is False assert processor.available is False

View file

@ -252,7 +252,7 @@ async def test_switch_services(
assert state.attributes.get(ATTR_TRIGGER_4) == "00008300" assert state.attributes.get(ATTR_TRIGGER_4) == "00008300"
# Set watering time using WiLight Pause Switch to raise # Set watering time using WiLight Pause Switch to raise
with pytest.raises(ValueError) as exc_info: with pytest.raises(TypeError) as exc_info:
await hass.services.async_call( await hass.services.async_call(
WILIGHT_DOMAIN, WILIGHT_DOMAIN,
SERVICE_SET_WATERING_TIME, SERVICE_SET_WATERING_TIME,

View file

@ -367,7 +367,7 @@ def aiohttp_client(
elif isinstance(__param, BaseTestServer): elif isinstance(__param, BaseTestServer):
client = TestClient(__param, loop=loop, **kwargs) client = TestClient(__param, loop=loop, **kwargs)
else: else:
raise ValueError("Unknown argument type: %r" % type(__param)) raise TypeError("Unknown argument type: %r" % type(__param))
await client.start_server() await client.start_server()
clients.append(client) clients.append(client)

View file

@ -75,7 +75,7 @@ async def test_custom_encoder(hass):
return "9" return "9"
store = storage.Store(hass, MOCK_VERSION, MOCK_KEY, encoder=JSONEncoder) store = storage.Store(hass, MOCK_VERSION, MOCK_KEY, encoder=JSONEncoder)
with pytest.raises(ValueError): with pytest.raises(TypeError):
await store.async_save(Mock()) await store.async_save(Mock())
await store.async_save(object()) await store.async_save(object())
data = await store.async_load() data = await store.async_load()