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:
"""Store flow result and return a code to retrieve it."""
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
temp_results[(client_id, code)] = (

View File

@ -285,7 +285,7 @@ class PassiveBluetoothDataProcessor(Generic[_T]):
if not isinstance(new_data, PassiveBluetoothDataUpdate):
self.last_update_success = False # type: ignore[unreachable]
raise ValueError(
raise TypeError(
f"The update_method for {self.coordinator.name} returned"
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):
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)
oauth_session = OAuth2SessionLyric(hass, entry, implementation)

View File

@ -111,7 +111,7 @@ async def new_subscriber(
if not isinstance(
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)):
raise ValueError("Configuration option 'subscriber_id' missing")
auth = AsyncConfigEntryAuth(

View File

@ -378,7 +378,7 @@ class NestFlowHandler(
if not isinstance(
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
return self.async_show_form(
step_id="device_project_upgrade",

View File

@ -88,21 +88,21 @@ async def async_setup_platform(
async def handle_async_join(entity, service_call):
"""Handle the entity service join."""
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])
async def handle_async_unjoin(entity, service_call):
"""Handle the entity service unjoin."""
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()
async def handle_set_latency(entity, service_call):
"""Handle the entity service set_latency."""
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])
@ -309,7 +309,7 @@ class SnapcastClientDevice(MediaPlayerEntity):
entity for entity in self.hass.data[DATA_KEY] if entity.entity_id == master
)
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(
group

View File

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

View File

@ -142,7 +142,7 @@ class ValloxState:
"""Return cached UUID value."""
uuid = _api_get_uuid(self.metric_cache)
if not isinstance(uuid, UUID):
raise ValueError
raise TypeError
return uuid
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.
async def set_watering_time(entity, service: Any) -> None:
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]
await entity.async_set_watering_time(watering_time=watering_time)
async def set_trigger(entity, service: Any) -> None:
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 = service.data[ATTR_TRIGGER]
await entity.async_set_trigger(trigger_index=trigger_index, trigger=trigger)
async def set_pause_time(entity, service: Any) -> None:
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]
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):
body_decoded = body.decode(response.charset or "utf-8")
else:
raise ValueError("Unknown payload encoding")
raise TypeError("Unknown payload encoding")
return {
"status": response.status,

View File

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

View File

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

View File

@ -1363,7 +1363,7 @@ ANY = _HA_ANY()
def raise_contains_mocks(val: Any) -> None:
"""Raise for mocks."""
if isinstance(val, Mock):
raise ValueError
raise TypeError
if isinstance(val, dict):
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}
)
else:
raise ValueError
raise ValueError # noqa: TRY004
def _get_device_detail(device_type, device_id):
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."""
store, _retrieve = auth._create_auth_code_store()
with pytest.raises(ValueError):
with pytest.raises(TypeError):
store(None, MockUser())
store(None, mock_credential)

View File

@ -479,7 +479,7 @@ async def test_bad_data_from_update_method(
assert processor.available is True
# 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)
assert processor.available is False

View File

@ -252,7 +252,7 @@ async def test_switch_services(
assert state.attributes.get(ATTR_TRIGGER_4) == "00008300"
# 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(
WILIGHT_DOMAIN,
SERVICE_SET_WATERING_TIME,

View File

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

View File

@ -75,7 +75,7 @@ async def test_custom_encoder(hass):
return "9"
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(object())
data = await store.async_load()