diff --git a/custom_components/nodered/websocket.py b/custom_components/nodered/websocket.py index f7dae76..50a86d6 100644 --- a/custom_components/nodered/websocket.py +++ b/custom_components/nodered/websocket.py @@ -122,11 +122,11 @@ async def websocket_device_action( ) -> None: """Execute a device action.""" context = connection.context(msg) - platform = await device_automation.async_get_device_automation_platform( - hass, msg["action"][CONF_DOMAIN], DeviceAutomationType.ACTION - ) try: + platform = await device_automation.async_get_device_automation_platform( + hass, msg["action"][CONF_DOMAIN], DeviceAutomationType.ACTION + ) if "entity_id" in msg["action"]: entity_registry = async_get(hass) entity_entry = entity_registry.async_get(msg["action"]["entity_id"]) @@ -405,12 +405,6 @@ def forward_trigger(event: dict[str, Any], _context: Context | None = None) -> N json.dumps(message, cls=NodeRedJSONEncoder, allow_nan=False), ) - def unsubscribe() -> None: - """Remove device trigger.""" - if remove_trigger is not None: - remove_trigger() - _LOGGER.info("Device trigger removed: %s", node_id) - try: trigger_config = await trigger.async_validate_trigger_config( hass, [trigger_data] @@ -423,8 +417,8 @@ def unsubscribe() -> None: DOMAIN, _LOGGER.log, ) - except vol.MultipleInvalid as err: - _LOGGER.exception("Error initializing device trigger for node_id: %s", node_id) + except vol.Invalid as err: + _LOGGER.error("Invalid device trigger config for node_id %s: %s", node_id, err) connection.send_message( error_message( msg[CONF_ID], @@ -433,27 +427,33 @@ def unsubscribe() -> None: ) ) return - except vol.Invalid as err: + except RuntimeError as err: _LOGGER.exception("Error initializing device trigger for node_id: %s", node_id) connection.send_message( error_message( msg[CONF_ID], - "invalid_trigger", + "runtime_error", str(err), ) ) return - except RuntimeError as err: - _LOGGER.exception("Error initializing device trigger for node_id: %s", node_id) + + # async_initialize_triggers logs the reason and returns None if attaching failed + if remove_trigger is None: connection.send_message( error_message( msg[CONF_ID], - "runtime_error", - str(err), + "trigger_not_attached", + "Device trigger could not be attached, check the Home Assistant log", ) ) return + def unsubscribe() -> None: + """Remove device trigger.""" + remove_trigger() + _LOGGER.info("Device trigger removed: %s", node_id) + _LOGGER.info("Device trigger created: %s", node_id) _LOGGER.debug("Device trigger config for %s: %s", node_id, trigger_data) connection.subscriptions[msg[CONF_ID]] = unsubscribe diff --git a/tests/test_websocket.py b/tests/test_websocket.py index 9e57aa7..506c1c7 100644 --- a/tests/test_websocket.py +++ b/tests/test_websocket.py @@ -22,7 +22,10 @@ websocket_device_trigger, websocket_version, ) -from homeassistant.components.device_automation.exceptions import DeviceNotFound +from homeassistant.components.device_automation.exceptions import ( + DeviceNotFound, + InvalidDeviceAutomationConfig, +) from homeassistant.components.webhook import async_register as webhook_real_register from homeassistant.components.websocket_api.messages import ( error_message, @@ -130,6 +133,29 @@ async def fake_get2(_hass: HomeAssistant, _domain: Any, _t: Any) -> Platform: assert sent == error_message(msg["id"], "device_not_found", "no device") +@pytest.mark.asyncio +@patch.object(websocket.device_automation, "async_get_device_automation_platform") +async def test_websocket_device_action_unknown_domain( + mock_get_platform: AsyncMock, + hass: HomeAssistant, + hass_ws_client: WebSocketGenerator, +) -> None: + mock_get_platform.side_effect = InvalidDeviceAutomationConfig("no platform") + websocket.register_websocket_handlers(hass) + client = await hass_ws_client(hass) + + await client.send_json( + { + "id": 8, + "type": "nodered/device/action", + "action": {"domain": "nope", "device_id": "dev-3"}, + } + ) + sent = await client.receive_json() + + assert sent == error_message(8, "invalid_config", "no platform") + + @pytest.mark.asyncio async def test_websocket_device_remove_handles_device_and_entities( hass: HomeAssistant, @@ -751,3 +777,32 @@ def _listener(event: Event) -> None: assert not contrib_announced_version(hass) assert events == [] + + +@pytest.mark.asyncio +@patch.object( + websocket.trigger, "async_initialize_triggers", new=AsyncMock(return_value=None) +) +@patch.object(websocket.trigger, "async_validate_trigger_config") +async def test_websocket_device_trigger_attach_failure( + mock_validate: AsyncMock, + hass: HomeAssistant, +) -> None: + """A trigger that fails to attach replies an error and stores no subscription.""" + mock_validate.side_effect = lambda _hass, config: config + + func: Any = websocket_device_trigger + while hasattr(func, "__wrapped__"): + func = func.__wrapped__ + + fake_conn = FakeConnection() + msg = {"id": 98, "node_id": "node-fail", "device_trigger": {}} + + await func(hass, fake_conn, msg) + + assert fake_conn.sent == error_message( + 98, + "trigger_not_attached", + "Device trigger could not be attached, check the Home Assistant log", + ) + assert fake_conn.subscriptions == {}