diff --git a/src/python/jw/util/load_yaml.py b/src/python/jw/util/load_yaml.py index ed808db..6f9d001 100644 --- a/src/python/jw/util/load_yaml.py +++ b/src/python/jw/util/load_yaml.py @@ -147,18 +147,30 @@ def _merge_at_path(root: dict[str, Any], path: tuple[str, ...], value: Any) -> dict[str, Any]: """Deep-merge *value* into *root* at the given *path*. - Creates intermediate dicts as needed. Returns the modified root. + Creates intermediate dicts as needed. Raises ``ValueError`` when + an existing value on or at the target path is not a mapping. + Returns the modified root. """ if not path: return _deep_merge(root, value) + path_str = '.'.join(path) current = root for i, key in enumerate(path[:-1]): - if key not in current or not isinstance(current[key], dict): + if key in current and not isinstance(current[key], dict): + raise ValueError( + f'Include target path {path_str}: value at ' + f'{".".join(path[:i + 1])} is not a mapping' + ) + if key not in current: current[key] = {} current = current[key] last_key = path[-1] - if (last_key in current and isinstance(current[last_key], dict) - and isinstance(value, dict)): + if last_key in current: + if not isinstance(current[last_key], dict) or not isinstance(value, dict): + raise ValueError( + f'Include target path {path_str}: value at {path_str} ' + f'is not a mapping' + ) # root's existing content wins (merge value into root) current[last_key] = _deep_merge(value, current[last_key]) else: diff --git a/test/unit/python/jw/util/load_yaml/test.py b/test/unit/python/jw/util/load_yaml/test.py index 31e28a9..b933114 100644 --- a/test/unit/python/jw/util/load_yaml/test.py +++ b/test/unit/python/jw/util/load_yaml/test.py @@ -4,6 +4,7 @@ from __future__ import annotations import pathlib import tempfile + from typing import Callable, Generator import pytest @@ -878,6 +879,31 @@ class TestIncludeWithPath: # Local content (original) wins over included (from_include) assert data['entry']['existing'] == 'original' + def test_include_non_dict_intermediate_raises(self, temp_dir: Callable) -> None: + """Including through an existing non-dict value raises.""" + base = temp_dir( + [ + ('base.yaml', 'inc: from_include\n'), + ('main.yaml', 'a:\n b: scalar\njw.include: a.b.c|base.yaml\n'), + ] + ) + with pytest.raises(ValueError, match = 'not a mapping'): + load_yaml(pathlib.Path(base) / 'main.yaml') + + def test_include_non_dict_leaf_raises(self, temp_dir: Callable) -> None: + """Including at an existing non-dict leaf raises.""" + base = temp_dir( + [ + ('base.yaml', 'inc: from_include\n'), + ( + 'main.yaml', + 'entry:\n existing: local\njw.include: entry.existing|base.yaml\n', + ), + ] + ) + with pytest.raises(ValueError, match = 'not a mapping'): + load_yaml(pathlib.Path(base) / 'main.yaml') + def test_multiple_includes_different_paths(self, temp_dir: Callable) -> None: """Multiple includes can target different paths.""" base = temp_dir(