Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wrap OSError in loader.load_yaml #124406

Merged
merged 2 commits into from
Aug 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion homeassistant/util/yaml/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,13 +221,21 @@ def __report_deprecated() -> None:
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(
Expand Down
21 changes: 21 additions & 0 deletions tests/util/yaml/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Loading