Skip to content

Commit 5bc2e27

Browse files
authored
Re-raise annotated_yaml.YAMLException as HomeAssistantError (home-assistant#147129)
* Re-raise annotated_yaml.YAMLException as HomeAssistantError * Fix comment
1 parent 77dca49 commit 5bc2e27

File tree

2 files changed

+15
-7
lines changed

2 files changed

+15
-7
lines changed

homeassistant/util/yaml/loader.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import os
77
from typing import TextIO
88

9-
from annotatedyaml import YAMLException, YamlTypeError
9+
import annotatedyaml
1010
from annotatedyaml.loader import (
1111
HAS_C_LOADER,
1212
JSON_TYPE,
@@ -35,6 +35,10 @@
3535
]
3636

3737

38+
class YamlTypeError(HomeAssistantError):
39+
"""Raised by load_yaml_dict if top level data is not a dict."""
40+
41+
3842
def load_yaml(
3943
fname: str | os.PathLike[str], secrets: Secrets | None = None
4044
) -> JSON_TYPE | None:
@@ -45,7 +49,7 @@ def load_yaml(
4549
"""
4650
try:
4751
return load_annotated_yaml(fname, secrets)
48-
except YAMLException as exc:
52+
except annotatedyaml.YAMLException as exc:
4953
raise HomeAssistantError(str(exc)) from exc
5054

5155

@@ -59,9 +63,9 @@ def load_yaml_dict(
5963
"""
6064
try:
6165
return load_annotated_yaml_dict(fname, secrets)
62-
except YamlTypeError:
63-
raise
64-
except YAMLException as exc:
66+
except annotatedyaml.YamlTypeError as exc:
67+
raise YamlTypeError(str(exc)) from exc
68+
except annotatedyaml.YAMLException as exc:
6569
raise HomeAssistantError(str(exc)) from exc
6670

6771

@@ -71,13 +75,13 @@ def parse_yaml(
7175
"""Parse YAML with the fastest available loader."""
7276
try:
7377
return parse_annotated_yaml(content, secrets)
74-
except YAMLException as exc:
78+
except annotatedyaml.YAMLException as exc:
7579
raise HomeAssistantError(str(exc)) from exc
7680

7781

7882
def secret_yaml(loader: LoaderType, node: yaml.nodes.Node) -> JSON_TYPE:
7983
"""Load secrets and embed it into the configuration YAML."""
8084
try:
8185
return annotated_secret_yaml(loader, node)
82-
except YAMLException as exc:
86+
except annotatedyaml.YAMLException as exc:
8387
raise HomeAssistantError(str(exc)) from exc

tests/util/yaml/test_init.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -559,6 +559,10 @@ def test_load_yaml_dict(expected_data: Any) -> None:
559559
@pytest.mark.usefixtures("try_both_loaders", "mock_hass_config_yaml")
560560
def test_load_yaml_dict_fail() -> None:
561561
"""Test item without a key."""
562+
# Make sure we raise a subclass of HomeAssistantError, not
563+
# annotated_yaml.YAMLException
564+
assert issubclass(yaml_loader.YamlTypeError, HomeAssistantError)
565+
562566
with pytest.raises(yaml_loader.YamlTypeError):
563567
yaml_loader.load_yaml_dict(YAML_CONFIG_FILE)
564568

0 commit comments

Comments
 (0)