Raise a translated error for an unknown Modbus hub (#194288)

This commit is contained in:
Zé Pedro
2026-11-24 22:57:23 +01:00
committed by GitHub
parent fabc4593d6
commit cb26f245b6
3 changed files with 37 additions and 5 deletions
+11 -5
View File
@@ -67,15 +67,21 @@ def _write_service_schema(
)
def _get_hubs(hass: HomeAssistant) -> dict[str, ModbusHub]:
"""Return the configured Modbus hubs, raising if Modbus is not set up."""
def _get_hub(hass: HomeAssistant, name: str) -> ModbusHub:
"""Return the named Modbus hub, raising if it is not set up."""
if not (hubs := hass.data.get(DATA_MODBUS_HUBS)):
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="not_loaded",
)
if (hub := hubs.get(name)) is None:
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="unknown_hub",
translation_placeholders={"hub": name},
)
return hubs
return hub
def _get_service_call_details(service: ServiceCall) -> tuple[ModbusHub, int, int]:
@@ -84,7 +90,7 @@ def _get_service_call_details(service: ServiceCall) -> tuple[ModbusHub, int, int
ModbusServiceArgument.SLAVE, service.data.get(ModbusServiceArgument.UNIT, 1)
)
address = service.data[ModbusServiceArgument.ADDRESS]
hub = _get_hubs(service.hass)[service.data[ModbusServiceArgument.HUB]]
hub = _get_hub(service.hass, service.data[ModbusServiceArgument.HUB])
return (hub, device_address, address)
@@ -118,7 +124,7 @@ async def _async_write_coil(service: ServiceCall) -> None:
async def _async_stop_hub(service: ServiceCall) -> None:
"""Stop Modbus hub."""
hass = service.hass
hub = _get_hubs(hass)[service.data[ModbusServiceArgument.HUB]]
hub = _get_hub(hass, service.data[ModbusServiceArgument.HUB])
async_dispatcher_send(hass, SIGNAL_STOP_ENTITY.format(hub.name))
await hub.async_close()
@@ -15,6 +15,9 @@
},
"not_loaded": {
"message": "Modbus is not loaded, so this action cannot be performed."
},
"unknown_hub": {
"message": "Modbus hub {hub} is not configured."
}
},
"issues": {
+23
View File
@@ -99,6 +99,29 @@ async def test_service_without_yaml_raises(
assert "Modbus is not loaded" in str(err.value)
@pytest.mark.usefixtures("mock_pymodbus")
@pytest.mark.parametrize(("service", "data"), HUB_SERVICES)
async def test_service_unknown_hub_raises(
hass: HomeAssistant, service: str, data: dict
) -> None:
"""Test the hub actions raise when the named hub is not configured."""
assert await async_setup_component(hass, DOMAIN, HUB_CONFIG)
await hass.async_block_till_done()
with pytest.raises(ServiceValidationError) as err:
await hass.services.async_call(
DOMAIN,
service,
{**data, ModbusServiceArgument.HUB: "unknown"},
blocking=True,
)
assert err.value.translation_domain == DOMAIN
assert err.value.translation_key == "unknown_hub"
assert err.value.translation_placeholders == {"hub": "unknown"}
assert "Modbus hub unknown is not configured" in str(err.value)
@pytest.mark.parametrize(("service", "data"), HUB_SERVICES)
async def test_service_without_hubs_raises(
hass: HomeAssistant, service: str, data: dict