load_yaml: Reject non-dict include targets

When jw.include specifies a target path, _merge_at_path() walks the
existing document to that path.  If an intermediate key holds a
non-dict value, that value is silently replaced by an empty dict; if
the leaf key holds a non-dict value, it is silently replaced by the
included mapping.  Both cases discard local document data without
warning, and the leaf case even inverts the documented precedence in
which local content wins over included content (which holds for the
dict-versus-dict case).

Make _merge_at_path() raise ValueError when an existing value on or
at the target path is not a mapping, and add regression tests for
both the intermediate and the leaf case.

Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v0.84.2
Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
Jan Lindemann 2026-08-16 12:15:47 +02:00
commit 2bd1db5d90
Signed by: Jan Lindemann
GPG key ID: 3750640C9E25DD61

View file

@ -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(