Wrap OSError in loader.load_yaml (#124406)

This commit is contained in:
Erik Montnemery 2024-08-22 16:06:41 +02:00 committed by GitHub
parent 2337c3ff69
commit 404a7bab18
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 30 additions and 1 deletions

View file

@ -221,13 +221,21 @@ type LoaderType = FastSafeLoader | PythonSafeLoader
def load_yaml(
fname: str | os.PathLike[str], secrets: Secrets | None = None
) -> JSON_TYPE | None:
"""Load a YAML file."""
"""Load a YAML file.
If opening the file raises an OSError it will be wrapped in a HomeAssistantError,
except for FileNotFoundError which will be re-raised.
"""
try:
with open(fname, encoding="utf-8") as conf_file:
return parse_yaml(conf_file, secrets)
except UnicodeDecodeError as exc:
_LOGGER.error("Unable to read file %s: %s", fname, exc)
raise HomeAssistantError(exc) from exc
except FileNotFoundError:
raise
except OSError as exc:
raise HomeAssistantError(exc) from exc
def load_yaml_dict(

View file

@ -746,3 +746,24 @@ def test_include_without_parameter(tag: str) -> None:
pytest.raises(HomeAssistantError, match=f"{tag} needs an argument"),
):
yaml_loader.parse_yaml(file)
@pytest.mark.parametrize(
("open_exception", "load_yaml_exception"),
[
(FileNotFoundError, OSError),
(NotADirectoryError, HomeAssistantError),
(PermissionError, HomeAssistantError),
],
)
@pytest.mark.usefixtures("try_both_loaders")
def test_load_yaml_wrap_oserror(
open_exception: Exception,
load_yaml_exception: Exception,
) -> None:
"""Test load_yaml wraps OSError in HomeAssistantError."""
with (
patch("homeassistant.util.yaml.loader.open", side_effect=open_exception),
pytest.raises(load_yaml_exception),
):
yaml_loader.load_yaml("bla")