Add exception translations to camera (#184427)

This commit is contained in:
Franck Nijhof
2026-10-06 10:09:23 +02:00
committed by GitHub
parent 05f367e672
commit 7767aa8eb9
3 changed files with 90 additions and 22 deletions
+28 -8
View File
@@ -1,6 +1,7 @@
"""Services for the camera integration."""
import asyncio
import errno
import os
from typing import TYPE_CHECKING
@@ -20,7 +21,7 @@ from homeassistant.const import (
SERVICE_TURN_ON,
)
from homeassistant.core import HomeAssistant, ServiceCall, callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.network import get_url
from homeassistant.helpers.template import Template
@@ -34,6 +35,7 @@ from .const import (
CONF_DURATION,
CONF_LOOKBACK,
DATA_COMPONENT,
DOMAIN,
SERVICE_DISABLE_MOTION,
SERVICE_ENABLE_MOTION,
SERVICE_PLAY_STREAM,
@@ -60,6 +62,14 @@ CAMERA_SERVICE_RECORD: VolDictType = {
probatio.Optional(CONF_LOOKBACK, default=0): probatio.Coerce(int),
}
# OS errors are not translatable, so the common causes get their own message
WRITE_ERROR_TRANSLATION_KEYS: dict[int | None, str] = {
errno.EACCES: "write_permission_denied",
errno.EPERM: "write_permission_denied",
errno.ENOSPC: "write_no_space",
errno.EROFS: "write_read_only",
}
async def _async_handle_snapshot_service(
camera: Camera, service_call: ServiceCall
@@ -72,10 +82,10 @@ async def _async_handle_snapshot_service(
# check if we allow to access to that file
if not hass.config.is_allowed_path(snapshot_file):
raise HomeAssistantError(
f"Cannot write `{snapshot_file}`, no access to path;"
" `allowlist_external_dirs` may need to be adjusted"
" in `configuration.yaml`"
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="path_not_allowed",
translation_placeholders={"filename": snapshot_file},
)
try:
@@ -87,7 +97,9 @@ async def _async_handle_snapshot_service(
)
except TimeoutError as err:
raise HomeAssistantError(
f"Unable to get snapshot: Timed out after {CAMERA_IMAGE_TIMEOUT} seconds"
translation_domain=DOMAIN,
translation_key="snapshot_timeout",
translation_placeholders={"timeout": str(CAMERA_IMAGE_TIMEOUT)},
) from err
if image is None:
@@ -102,7 +114,11 @@ async def _async_handle_snapshot_service(
try:
await hass.async_add_executor_job(_write_image, snapshot_file, image)
except OSError as err:
raise HomeAssistantError(f"Can't write image to file: {err}") from err
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key=WRITE_ERROR_TRANSLATION_KEYS.get(err.errno, "write_failed"),
translation_placeholders={"filename": snapshot_file},
) from err
async def _async_handle_play_stream_service(
@@ -134,7 +150,11 @@ async def _async_handle_record_service(
stream = await camera.async_create_stream()
if not stream:
raise HomeAssistantError(f"{camera.entity_id} does not support record service")
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="record_not_supported",
translation_placeholders={"entity_id": camera.entity_id},
)
filename = service_call.data[CONF_FILENAME]
video_path = filename.async_render()
@@ -34,6 +34,29 @@
}
}
},
"exceptions": {
"path_not_allowed": {
"message": "Cannot write to {filename} because access to this path is not allowed. `allowlist_external_dirs` may need to be adjusted in `configuration.yaml`."
},
"record_not_supported": {
"message": "Camera {entity_id} does not support recording."
},
"snapshot_timeout": {
"message": "Unable to get snapshot: timed out after {timeout} seconds."
},
"write_failed": {
"message": "Cannot write image to {filename}."
},
"write_no_space": {
"message": "Cannot write image to {filename}: no space left on the device."
},
"write_permission_denied": {
"message": "Cannot write image to {filename}: permission denied."
},
"write_read_only": {
"message": "Cannot write image to {filename}: the file system is read-only."
}
},
"selector": {},
"services": {
"disable_motion_detection": {
+39 -14
View File
@@ -1,6 +1,7 @@
"""The tests for the camera component."""
from collections.abc import Callable
import errno
from http import HTTPStatus
import io
from unittest.mock import ANY, AsyncMock, Mock, PropertyMock, mock_open, patch
@@ -25,7 +26,7 @@ from homeassistant.const import (
)
from homeassistant.core import HomeAssistant
from homeassistant.core_config import async_process_ha_core_config
from homeassistant.exceptions import HomeAssistantError
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
from homeassistant.helpers import entity_registry as er
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util
@@ -274,8 +275,8 @@ async def test_snapshot_service_not_allowed_path(hass: HomeAssistant) -> None:
"homeassistant.components.camera.services.os.makedirs",
),
pytest.raises(
HomeAssistantError,
match="Cannot write `/test/snapshot.jpg`, no access to path",
ServiceValidationError,
match="Cannot write to /test/snapshot.jpg because access to this path is not allowed",
),
):
await hass.services.async_call(
@@ -291,23 +292,48 @@ async def test_snapshot_service_not_allowed_path(hass: HomeAssistant) -> None:
@pytest.mark.usefixtures("mock_camera")
@pytest.mark.parametrize(
("target", "side_effect"),
("target", "side_effect", "message"),
[
("homeassistant.components.camera.services.os.makedirs", OSError),
(
"homeassistant.components.camera.services.os.makedirs",
OSError(errno.EACCES, "Permission denied"),
"Cannot write image to /test/snapshot.jpg: permission denied$",
),
(
"homeassistant.components.camera.services.os.makedirs",
OSError(errno.EPERM, "Operation not permitted"),
"Cannot write image to /test/snapshot.jpg: permission denied$",
),
(
"homeassistant.components.camera.services.os.makedirs",
OSError(errno.ENOSPC, "No space left on device"),
"Cannot write image to /test/snapshot.jpg: no space left on the device$",
),
(
"homeassistant.components.camera.services.os.makedirs",
OSError(errno.EROFS, "Read-only file system"),
"Cannot write image to /test/snapshot.jpg: the file system is read-only$",
),
(
"homeassistant.components.camera.services.os.makedirs",
OSError(errno.EIO, "Input/output error"),
"Cannot write image to /test/snapshot.jpg$",
),
(
"homeassistant.components.demo.camera.DemoCamera.async_camera_image",
TimeoutError,
"Unable to get snapshot: timed out after 10 seconds",
),
],
)
async def test_snapshot_service_error(
hass: HomeAssistant, target: str, side_effect: Exception
hass: HomeAssistant, target: str, side_effect: Exception, message: str
) -> None:
"""Test snapshot service with error."""
with (
patch.object(hass.config, "is_allowed_path", return_value=True),
patch(target, side_effect=side_effect),
pytest.raises(HomeAssistantError),
pytest.raises(HomeAssistantError, match=message),
):
await hass.services.async_call(
camera.DOMAIN,
@@ -587,19 +613,18 @@ async def test_preload_stream(hass: HomeAssistant, mock_create_stream: Mock) ->
@pytest.mark.usefixtures("mock_camera")
async def test_record_service_invalid_path(hass: HomeAssistant) -> None:
"""Test record service with invalid path."""
with (
patch.object(hass.config, "is_allowed_path", return_value=False),
pytest.raises(HomeAssistantError),
async def test_record_service_not_supported(hass: HomeAssistant) -> None:
"""Test record service on a camera without stream support."""
with pytest.raises(
ServiceValidationError,
match="Camera camera.demo_camera does not support recording",
):
# Call service
await hass.services.async_call(
camera.DOMAIN,
camera.SERVICE_RECORD,
{
ATTR_ENTITY_ID: "camera.demo_camera",
camera.CONF_FILENAME: "/my/invalid/path",
camera.CONF_FILENAME: "/test/recording.mp4",
},
blocking=True,
)