diff --git a/homeassistant/components/auth/__init__.py b/homeassistant/components/auth/__init__.py index 01ce39f5fcc..1b47fb09393 100644 --- a/homeassistant/components/auth/__init__.py +++ b/homeassistant/components/auth/__init__.py @@ -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)] = ( diff --git a/homeassistant/components/bluetooth/passive_update_processor.py b/homeassistant/components/bluetooth/passive_update_processor.py index 04034293491..e1701487409 100644 --- a/homeassistant/components/bluetooth/passive_update_processor.py +++ b/homeassistant/components/bluetooth/passive_update_processor.py @@ -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" ) diff --git a/homeassistant/components/lyric/__init__.py b/homeassistant/components/lyric/__init__.py index 228cf4c1d5d..f34366f24d0 100644 --- a/homeassistant/components/lyric/__init__.py +++ b/homeassistant/components/lyric/__init__.py @@ -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) diff --git a/homeassistant/components/nest/api.py b/homeassistant/components/nest/api.py index 4d92cc30b1a..8c9ca4bec96 100644 --- a/homeassistant/components/nest/api.py +++ b/homeassistant/components/nest/api.py @@ -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( diff --git a/homeassistant/components/nest/config_flow.py b/homeassistant/components/nest/config_flow.py index 6c1768d9855..352a7ba1725 100644 --- a/homeassistant/components/nest/config_flow.py +++ b/homeassistant/components/nest/config_flow.py @@ -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", diff --git a/homeassistant/components/snapcast/media_player.py b/homeassistant/components/snapcast/media_player.py index de3eca18b45..2794c350ed4 100644 --- a/homeassistant/components/snapcast/media_player.py +++ b/homeassistant/components/snapcast/media_player.py @@ -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 diff --git a/homeassistant/components/telegram_bot/__init__.py b/homeassistant/components/telegram_bot/__init__.py index 32be8cbd935..a453a4611bf 100644 --- a/homeassistant/components/telegram_bot/__init__.py +++ b/homeassistant/components/telegram_bot/__init__.py @@ -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 diff --git a/homeassistant/components/vallox/__init__.py b/homeassistant/components/vallox/__init__.py index dceffb47a21..579accc8090 100644 --- a/homeassistant/components/vallox/__init__.py +++ b/homeassistant/components/vallox/__init__.py @@ -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: diff --git a/homeassistant/components/wilight/switch.py b/homeassistant/components/wilight/switch.py index 920fb66908c..f2d74cce359 100644 --- a/homeassistant/components/wilight/switch.py +++ b/homeassistant/components/wilight/switch.py @@ -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) diff --git a/homeassistant/util/aiohttp.py b/homeassistant/util/aiohttp.py index 8248864fd0e..804228b67f7 100644 --- a/homeassistant/util/aiohttp.py +++ b/homeassistant/util/aiohttp.py @@ -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, diff --git a/pyproject.toml b/pyproject.toml index 968bdb1fc83..371927db4ee 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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 ] diff --git a/setup.cfg b/setup.cfg index 1193bbd44d8..323c4c10d26 100644 --- a/setup.cfg +++ b/setup.cfg @@ -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 diff --git a/tests/common.py b/tests/common.py index 52356357779..b78a930ecb7 100644 --- a/tests/common.py +++ b/tests/common.py @@ -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(): diff --git a/tests/components/august/mocks.py b/tests/components/august/mocks.py index 2fa59fe964c..d5517f64249 100644 --- a/tests/components/august/mocks.py +++ b/tests/components/august/mocks.py @@ -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]: diff --git a/tests/components/auth/test_init.py b/tests/components/auth/test_init.py index 6854bb92052..417f08c4036 100644 --- a/tests/components/auth/test_init.py +++ b/tests/components/auth/test_init.py @@ -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) diff --git a/tests/components/bluetooth/test_passive_update_processor.py b/tests/components/bluetooth/test_passive_update_processor.py index 9f72146f364..68fc1730338 100644 --- a/tests/components/bluetooth/test_passive_update_processor.py +++ b/tests/components/bluetooth/test_passive_update_processor.py @@ -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 diff --git a/tests/components/wilight/test_switch.py b/tests/components/wilight/test_switch.py index 035f5b37be5..32b54a9756d 100644 --- a/tests/components/wilight/test_switch.py +++ b/tests/components/wilight/test_switch.py @@ -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, diff --git a/tests/conftest.py b/tests/conftest.py index 5625fcbdfb7..6c0760b1bcb 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -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) diff --git a/tests/helpers/test_storage.py b/tests/helpers/test_storage.py index 0fcfbc46ef9..af217971e99 100644 --- a/tests/helpers/test_storage.py +++ b/tests/helpers/test_storage.py @@ -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()