Home Assistant Unofficial Reference 2024.12.1
entity_store_validation.py
Go to the documentation of this file.
1 """KNX Entity Store Validation."""
2 
3 from typing import Literal, TypedDict
4 
5 import voluptuous as vol
6 
7 from .entity_store_schema import ENTITY_STORE_DATA_SCHEMA
8 
9 
10 class _ErrorDescription(TypedDict):
11  path: list[str] | None
12  error_message: str
13  error_class: str
14 
15 
16 class EntityStoreValidationError(TypedDict):
17  """Negative entity store validation result."""
18 
19  success: Literal[False]
20  error_base: str
21  errors: list[_ErrorDescription]
22 
23 
25  """Positive entity store validation result."""
26 
27  success: Literal[True]
28  entity_id: str | None
29 
30 
31 def parse_invalid(exc: vol.Invalid) -> _ErrorDescription:
32  """Parse a vol.Invalid exception."""
33  return _ErrorDescription(
34  path=[str(path) for path in exc.path], # exc.path: str | vol.Required
35  error_message=exc.msg,
36  error_class=type(exc).__name__,
37  )
38 
39 
40 def validate_entity_data(entity_data: dict) -> dict:
41  """Validate entity data.
42 
43  Return validated data or raise EntityStoreValidationException.
44  """
45  try:
46  # return so defaults are applied
47  return ENTITY_STORE_DATA_SCHEMA(entity_data) # type: ignore[no-any-return]
48  except vol.MultipleInvalid as exc:
50  validation_error={
51  "success": False,
52  "error_base": str(exc),
53  "errors": [parse_invalid(invalid) for invalid in exc.errors],
54  }
55  ) from exc
56  except vol.Invalid as exc:
58  validation_error={
59  "success": False,
60  "error_base": str(exc),
61  "errors": [parse_invalid(exc)],
62  }
63  ) from exc
64 
65 
67  """Entity store validation exception."""
68 
69  def __init__(self, validation_error: EntityStoreValidationError) -> None:
70  """Initialize."""
71  super().__init__(validation_error)
72  self.validation_errorvalidation_error = validation_error