Skip to content

Commit

Permalink
Enable Ruff TRY004 (home-assistant#86811)
Browse files Browse the repository at this point in the history
  • Loading branch information
frenck authored Jan 30, 2023
1 parent 7368c86 commit 3b5fd4b
Show file tree
Hide file tree
Showing 19 changed files with 24 additions and 22 deletions.
2 changes: 1 addition & 1 deletion homeassistant/components/auth/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)] = (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ def async_handle_update(self, update: _T) -> None:

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"
)
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/lyric/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/nest/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/nest/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,7 @@ async def async_step_device_project_upgrade(
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",
Expand Down
8 changes: 4 additions & 4 deletions homeassistant/components/snapcast/media_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])


Expand Down Expand Up @@ -309,7 +309,7 @@ async def async_join(self, master):
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
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/telegram_bot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -547,7 +547,7 @@ def _make_row_inline_keyboard(row_keyboard):
InlineKeyboardButton(text_btn, callback_data=data_btn)
)
else:
raise ValueError(str(row_keyboard))
raise TypeError(str(row_keyboard))
return buttons

# Defaults
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/vallox/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ def uuid(self) -> UUID | None:
"""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:
Expand Down
6 changes: 3 additions & 3 deletions homeassistant/components/wilight/switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
2 changes: 1 addition & 1 deletion homeassistant/util/aiohttp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
]
Expand Down
1 change: 1 addition & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 1 addition & 1 deletion tests/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -1363,7 +1363,7 @@ def __repr__(self) -> str:
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():
Expand Down
2 changes: 1 addition & 1 deletion tests/components/august/mocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand Down
2 changes: 1 addition & 1 deletion tests/components/auth/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -479,7 +479,7 @@ def _async_register_callback(_hass, _callback, _matcher, _mode):
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
Expand Down
2 changes: 1 addition & 1 deletion tests/components/wilight/test_switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ async def go(
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)
Expand Down
2 changes: 1 addition & 1 deletion tests/helpers/test_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def default(self, o):
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()
Expand Down

0 comments on commit 3b5fd4b

Please sign in to comment.