load_yaml: Implement jw.link expansion

Implement link expansion in _expand_links() to resolve jw.link markers
in YAML documents after the include/merge phase.  Two link forms are
supported:

- Inplace links  jw.link: "path.to.target" replace the marker entirely
  with the resolved value at the target path.
- Named links   jw.link: "name|path.to.target" replace the marker with
  {name: resolved_value}, using the first path segment as the key.

Paths use dot-separated segments.  Relative paths start with ".."
(like Python imports): "." stays at the current level, ".." goes up
one level, "..." two, and so on.  A single pipe character in the link
value separates the link name from the target path for named links.

The implementation includes:

- _parse_link(): splits a link value into (is_named, name, path)
- _resolve_path(): resolves an absolute or relative path to a value
- _expand_links_recursive(): walks the structure, expands links,
  detects cycles via a resolving set, and memoises via a resolved dict.

Cyclic links and missing targets both raise ValueError/KeyError.
jw.link markers with sibling keys are left unexpanded.

Add 86 unit tests covering the entire load_yaml module:

- Basic YAML loading, optional loading, root type checking
- Include directive (single, multiple, deep merge, circular detect)
- Inplace links, named links, relative paths (up, descend, same level)
- Transitive links, cycle detection, missing targets
- Regression tests, combined include+links, edge cases, type preservation

Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
Jan Lindemann 2026-07-03 11:26:06 +02:00 • committed by janware DevOps
commit d7454341e8
Signed by: DevOps
SSH key fingerprint: SHA256:cZiw7ExG5q3KAVm7Jse3rGITowu0VjgUgNMPbifmY8g
3 changed files with 850 additions and 1 deletions

View file

@ -7,6 +7,8 @@ from typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing import Any, TypeAlias
import re # noqa: E402
import yaml # type: ignore[import-untyped]
Includes: TypeAlias = list[tuple[bool, Path]]
@ -80,9 +82,161 @@ def _load_yaml(path: str | Path, optional: bool, seen: set[Path]) -> dict[str, A
finally:
seen.remove(path)
_LINK_NAME_RE = re.compile(r'^([a-zA-Z0-9_-]+)\|')
def _parse_link(value: str) -> tuple[bool, str | None, str]:
"""Parse a link value into (is_named, name_or_None, path_string).
A named link uses a single pipe to separate the link name from the
target path, e.g. ``"name|path|to|target"``. Otherwise the entire
string is treated as an absolute or relative target path.
"""
m = _LINK_NAME_RE.match(value)
if m:
return (True, m.group(1), value[len(m.group(1)) + 1:])
return (False, None, value)
def _resolve_path(path_str: str, current_path: tuple,
root: dict[str, Any]) -> tuple[tuple[str, ...], Any]:
"""Resolve *path_str* and return ``(path, value)`` at that location.
Absolute paths are resolved from the document root; relative paths
(starting with ``.``) are resolved from *current_path*. Path segments
are separated by dots.
"""
if not path_str:
resolved_path: tuple = current_path
target = root
for key in current_path:
target = target[key]
return (resolved_path, target)
if path_str.startswith('.'):
# Count consecutive leading dots to determine levels to go up
# from the link's parent. 1 dot = stay, 2 dots = up 1, etc.
dot_count = 0
for ch in path_str:
if ch == '.':
dot_count += 1
else:
break
levels_up = dot_count - 1
rest = path_str[dot_count:]
# Start from the link's parent (the dict that contains the link)
if not current_path:
parent_path: tuple = ()
else:
parent_path = current_path[:-1]
if levels_up > 0:
if levels_up > len(parent_path):
raise ValueError(f"Link target path goes above root: {path_str!r}")
new_path = parent_path[:-levels_up]
else:
new_path = parent_path
# Navigate from root to the base (new_path)
resolved_path = new_path
target = root
for key in new_path:
target = target[key]
if rest:
for key in rest.split('.'):
resolved_path = resolved_path + (key, )
target = target[key]
return (resolved_path, target)
# Absolute path from root
resolved_path = tuple(path_str.split('.'))
target = root
for key in path_str.split('.'):
target = target[key]
return (resolved_path, target)
def _expand_links_recursive(
node: Any,
root: dict[str, Any],
current_path: tuple,
resolved: dict,
resolving: set,
) -> Any:
"""Recursively walk *node* and expand all ``jw.link`` markers.
``resolved`` is a memoisation cache mapping ``(path, link_spec)`` →
expanded value. ``resolving`` tracks links currently being expanded
to detect cycles.
"""
if isinstance(node, dict):
# Link node: dict with only jw.link as key
if 'jw.link' in node and len(node) == 1:
link_spec = node['jw.link']
link_key = (current_path, link_spec)
if link_key in resolving:
raise ValueError(f"Cyclic link detected: {link_spec!r}")
if link_key in resolved:
return resolved[link_key]
resolving.add(link_key)
is_named, name, path = _parse_link(link_spec)
target_path, target_value = _resolve_path(path, current_path, root)
expanded_target = _expand_links_recursive(
target_value, root, target_path, resolved, resolving
)
resolving.discard(link_key)
if is_named:
result = {name: expanded_target}
else:
result = expanded_target
resolved[link_key] = result
return result
# Normal dict — expand values recursively
expanded: dict[str, Any] = {}
for key, value in node.items():
expanded[key] = _expand_links_recursive(
value, root, current_path + (key, ), resolved, resolving
)
return expanded
if isinstance(node, list):
return [
_expand_links_recursive(
item, root, current_path + (i, ), resolved, resolving
) for i, item in enumerate(node)
]
return node # scalar or None
def _expand_links(root: dict[str, Any]) -> dict[str, Any]:
r"""Expand all ``jw.link`` markers in *root* and return the result.
Two link forms are supported:
- **Inplace** ``jw.link: "target.path"`` — the ``jw.link`` key
disappears and is replaced by the resolved value, inline.
- **Named** ``jw.link: "name|target.path"`` — the ``jw.link`` key
is renamed to ``name`` and its value is the resolved target.
Paths use dot-separated segments. A relative path starts with ``.``
(Python-import style): ``.`` stays at the current level, ``..`` goes
up one level, ``...`` two, and so on. The first ``/`` in the link
value (only when the prefix matches ``[a-zA-Z0-9_-]+/``) separates
the link name from the target path for named links.
Cyclic links raise ``ValueError``; missing targets also raise.
"""
resolved: dict = {}
resolving: set = set()
return _expand_links_recursive(root, root, (), resolved, resolving)
def load_yaml(path: str | Path, optional: bool = False) -> dict[str, Any]: # export
seen: set[Path] = set()
return _load_yaml(path, optional, seen)
return _expand_links(_load_yaml(path, optional, seen))
if __name__ == '__main__':
import json

View file

@ -0,0 +1,4 @@
TOPDIR = ../../../../../..
include $(TOPDIR)/make/proj.mk
include $(JWBDIR)/make/py-test.mk

View file

@ -0,0 +1,691 @@
"""Unit tests for jw.util.load_yaml."""
from __future__ import annotations
import pathlib
import tempfile
from typing import Callable, Generator
import pytest
from jw.util.load_yaml import load_yaml
# -- Helpers ------------------------------------------------------------------
@pytest.fixture
def yaml_file() -> Callable[[str], str]:
"""Create a temporary YAML file and return its path."""
def _make(content: str) -> str:
fh = tempfile.NamedTemporaryFile(mode = 'w', suffix = '.yaml', delete = False)
fh.write(content)
fh.flush()
fh.close()
return fh.name
return _make
@pytest.fixture
def temp_dir() -> Generator:
"""Create a temporary directory with files, return the directory."""
import shutil
base_dir: str | None = None
def _make(files: list[tuple[str, str]]) -> str:
nonlocal base_dir
base_dir = tempfile.mkdtemp()
for name, content in files:
path = pathlib.Path(base_dir) / name
path.parent.mkdir(parents = True, exist_ok = True)
path.write_text(content)
return base_dir
yield _make
if base_dir:
shutil.rmtree(base_dir, ignore_errors = True)
# -- Basic YAML loading -------------------------------------------------------
class TestBasicLoading:
"""Tests for basic YAML file loading without links or includes."""
def test_simple_dict(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('key: value\n'))
assert data == {'key': 'value'}
def test_nested_dict(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('outer:\n inner: value\n number: 42\n'))
assert data == {'outer': {'inner': 'value', 'number': 42}}
def test_list_value(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('items:\n - a\n - b\n - c\n'))
assert data == {'items': ['a', 'b', 'c']}
def test_empty_file(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file(''))
assert data == {}
def test_none_root(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('---\n'))
assert data == {}
def test_string_value(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('key: string value\n'))
assert data == {'key': 'string value'}
def test_number_value(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('int: 42\nfloat: 3.14\n'))
assert data['int'] == 42
assert data['float'] == 3.14
def test_boolean_value(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('enabled: true\ndisabled: false\n'))
assert data['enabled'] is True
assert data['disabled'] is False
def test_null_value(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('key: null\n'))
assert data['key'] is None
def test_multiline_string(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('key: |\n line1\n line2\n'))
assert data['key'] == 'line1\nline2\n'
def test_deeply_nested(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('a:\n b:\n c:\n d: deep\n'))
assert data == {'a': {'b': {'c': {'d': 'deep'}}}}
# -- Optional loading ---------------------------------------------------------
class TestOptionalLoading:
"""Tests for the optional parameter."""
def test_missing_optional(self) -> None:
data = load_yaml('nonexistent_file.yaml', optional = True)
assert data == {}
def test_missing_required(self) -> None:
with pytest.raises(FileNotFoundError):
load_yaml('nonexistent_file.yaml', optional = False)
def test_present_optional(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('key: val\n'), optional = True)
assert data == {'key': 'val'}
# -- Non-dict root detection --------------------------------------------------
class TestRootTypeCheck:
"""Tests that non-dict YAML roots are rejected."""
def test_string_root_raises(self, yaml_file: Callable) -> None:
with pytest.raises(TypeError, match = 'root must be a mapping'):
load_yaml(yaml_file('"just a string"\n'))
def test_list_root_raises(self, yaml_file: Callable) -> None:
with pytest.raises(TypeError, match = 'root must be a mapping'):
load_yaml(yaml_file('- item1\n- item2\n'))
def test_number_root_raises(self, yaml_file: Callable) -> None:
with pytest.raises(TypeError, match = 'root must be a mapping'):
load_yaml(yaml_file('42\n'))
# -- Include directive --------------------------------------------------------
class TestIncludeDirective:
"""Tests for the include directive."""
def test_single_include(self, temp_dir: Callable) -> None:
base = temp_dir(
[
('base.yaml', 'shared: from_base\n'),
('main.yaml', 'include: base.yaml\ncurrent: here\n'),
]
)
data = load_yaml(pathlib.Path(base) / 'main.yaml')
assert data['shared'] == 'from_base'
assert data['current'] == 'here'
def test_multiple_includes(self, temp_dir: Callable) -> None:
base = temp_dir(
[
('a.yaml', 'from_a: 1\nshared: a\n'),
('b.yaml', 'from_b: 2\nshared: b\n'),
('main.yaml', 'include:\n - a.yaml\n - b.yaml\nlocal: yes\n'),
]
)
data = load_yaml(pathlib.Path(base) / 'main.yaml')
assert data['from_a'] == 1
assert data['from_b'] == 2
# Later includes override earlier ones
assert data['shared'] == 'b'
assert data['local'] is True
def test_optional_include(self, temp_dir: Callable) -> None:
base = temp_dir(
[
('main.yaml', 'include:\n - "- nonexist.yaml"\nok: true\n'),
]
)
data = load_yaml(pathlib.Path(base) / 'main.yaml')
assert data == {'ok': True}
def test_deep_merge_dicts(self, temp_dir: Callable) -> None:
base = temp_dir(
[
('base.yaml', 'config:\n db:\n host: localhost\n port: 5432\n'),
('override.yaml', 'config:\n db:\n port: 3306\n name: mydb\n'),
('main.yaml', 'include:\n - override.yaml\nconfig:\n cache: true\n'),
]
)
data = load_yaml(pathlib.Path(base) / 'main.yaml')
assert data['config']['db']['port'] == 3306
assert data['config']['db']['name'] == 'mydb'
assert data['config']['cache'] is True
def test_nested_includes(self, temp_dir: Callable) -> None:
base = temp_dir(
[
('level1.yaml', 'from: level1\n'),
('level2.yaml', 'include: level1.yaml\nfrom: level2\n'),
('main.yaml', 'include: level2.yaml\n'),
]
)
data = load_yaml(pathlib.Path(base) / 'main.yaml')
assert data['from'] == 'level2'
def test_include_circular_detect(self, temp_dir: Callable) -> None:
base = temp_dir(
[
('a.yaml', 'include: b.yaml\n'),
('b.yaml', 'include: a.yaml\n'),
]
)
with pytest.raises(ValueError, match = 'Cyclic YAML include'):
load_yaml(pathlib.Path(base) / 'a.yaml')
def test_include_relative_path(self, temp_dir: Callable) -> None:
base = temp_dir(
[
('sub/inner.yaml', 'secret: found\n'),
('main.yaml', 'include: sub/inner.yaml\n'),
]
)
data = load_yaml(pathlib.Path(base) / 'main.yaml')
assert data['secret'] == 'found'
# -- jw.link expansion - Inplace links ----------------------------------------
class TestInplaceLinks:
"""Tests for inplace jw.link expansion."""
def test_inplace_absolute(self, yaml_file: Callable) -> None:
data = load_yaml(
yaml_file('target:\n key: val\nlink:\n jw.link: target.key\n')
)
assert data['link'] == 'val'
# Original target should still be there
assert data['target']['key'] == 'val'
def test_inplace_dict_target(self, yaml_file: Callable) -> None:
data = load_yaml(
yaml_file('target:\n a: 1\n b: 2\nlink:\n jw.link: target\n')
)
assert data['link'] == {'a': 1, 'b': 2}
def test_inplace_list_target(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('target:\n - x\n - y\nlink:\n jw.link: target\n'))
assert data['link'] == ['x', 'y']
def test_inplace_in_list(self, yaml_file: Callable) -> None:
data = load_yaml(
yaml_file(
'target: val\nitems:\n - plain\n - jw.link: target\n - more\n'
)
)
assert data['items'] == ['plain', 'val', 'more']
def test_inplace_scalar_in_list(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('target: 42\nitems:\n - 1\n - jw.link: target\n'))
assert data['items'] == [1, 42]
def test_inplace_in_nested_dict(self, yaml_file: Callable) -> None:
data = load_yaml(
yaml_file(
'target: deep\nnested:\n level:\n link:\n jw.link: target\n'
)
)
assert data['nested']['level']['link'] == 'deep'
# -- jw.link expansion - Named links ------------------------------------------
class TestNamedLinks:
"""Tests for named jw.link expansion."""
def test_named_absolute(self, yaml_file: Callable) -> None:
data = load_yaml(
yaml_file('target:\n key: val\nlink:\n jw.link: name|target.key\n')
)
assert data['link'] == {'name': 'val'}
def test_named_dict_target(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('target:\n a: 1\nlink:\n jw.link: alias|target\n'))
assert data['link'] == {'alias': {'a': 1}}
def test_named_in_list(self, yaml_file: Callable) -> None:
data = load_yaml(
yaml_file('target: val\nitems:\n - plain\n - jw.link: renamed|target\n')
)
assert data['items'] == ['plain', {'renamed': 'val'}]
def test_named_with_dashes_and_underscores(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('target: ok\nlink:\n jw.link: my-name|target\n'))
assert data['link'] == {'my-name': 'ok'}
# -- jw.link expansion - Relative paths ---------------------------------------
class TestRelativePaths:
"""Tests for relative jw.link paths."""
def test_relative_up_one(self, yaml_file: Callable) -> None:
data = load_yaml(
yaml_file(
'parent:\n'
' child:\n'
' link:\n'
' jw.link: ..sibling\n'
' sibling: value\n'
)
)
assert data['parent']['child']['link'] == 'value'
def test_relative_up_one_simple(self, yaml_file: Callable) -> None:
data = load_yaml(
yaml_file('sibling: val\nnode:\n link:\n jw.link: ..sibling\n')
)
assert data['node']['link'] == 'val'
def test_relative_up_two(self, yaml_file: Callable) -> None:
data = load_yaml(
yaml_file(
'root_val: my_root\n'
'level1:\n'
' level2:\n'
' link:\n'
' jw.link: ...root_val\n'
)
)
assert data['level1']['level2']['link'] == 'my_root'
def test_relative_up_two_simple(self, yaml_file: Callable) -> None:
data = load_yaml(
yaml_file('base_val: my_base\nsub:\n link:\n jw.link: ..base_val\n')
)
assert data['sub']['link'] == 'my_base'
def test_relative_up_then_descend(self, yaml_file: Callable) -> None:
data = load_yaml(
yaml_file(
'shared:\n'
' target: found\n'
'nested:\n'
' a:\n'
' b:\n'
' link:\n'
' jw.link: ....shared.target\n'
)
)
assert data['nested']['a']['b']['link'] == 'found'
def test_relative_up_then_descend_simple(self, yaml_file: Callable) -> None:
data = load_yaml(
yaml_file('shared:\n value: ok\nnode:\n link:\n jw.link: ..shared\n')
)
assert data['node']['link'] == {'value': 'ok'}
def test_relative_same_level(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('a: 1\nb:\n link:\n jw.link: ..a\n'))
assert data['b']['link'] == 1
def test_relative_same_level_simple(self, yaml_file: Callable) -> None:
data = load_yaml(
yaml_file('sibling: val\nnode:\n link:\n jw.link: ..sibling\n')
)
assert data['node']['link'] == 'val'
def test_relative_above_root_raises(self, yaml_file: Callable) -> None:
with pytest.raises(ValueError, match = 'above root'):
load_yaml(yaml_file('link:\n jw.link: ....above\n'))
def test_relative_deep_nesting(self, yaml_file: Callable) -> None:
data = load_yaml(
yaml_file(
'shared: value\n'
'depth:\n'
' l1:\n'
' l2:\n'
' l3:\n'
' link:\n'
' jw.link: .....shared\n'
)
)
assert data['depth']['l1']['l2']['l3']['link'] == 'value'
def test_relative_self_same_dict(self, yaml_file: Callable) -> None:
# Link pointing to ancestor dict containing itself is a cycle
with pytest.raises(ValueError, match = 'Cyclic link'):
load_yaml(yaml_file('a:\n x: 1\n b:\n c:\n jw.link: ...a\n'))
def test_relative_up_to_root_then_descend(self, yaml_file: Callable) -> None:
data = load_yaml(
yaml_file(
'root_data: ok\na:\n b:\n link:\n jw.link: ...root_data\n'
)
)
assert data['a']['b']['link'] == 'ok'
def test_relative_up_from_deep(self, yaml_file: Callable) -> None:
data = load_yaml(
yaml_file(
'root_val: here\n'
'top:\n'
' middle:\n'
' bot:\n'
' link:\n'
' jw.link: ....root_val\n'
)
)
assert data['top']['middle']['bot']['link'] == 'here'
def test_relative_link_to_sibling_dict(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('a:\n x: 1\nb:\n link:\n jw.link: ..a\n'))
assert data['b']['link'] == {'x': 1}
def test_relative_up_two_from_deep(self, yaml_file: Callable) -> None:
data = load_yaml(
yaml_file(
'root_val: here\n'
'a:\n'
' b:\n'
' c:\n'
' link:\n'
' jw.link: ....root_val\n'
)
)
assert data['a']['b']['c']['link'] == 'here'
# -- jw.link expansion - Transitive links -------------------------------------
class TestTransitiveLinks:
"""Tests for transitive link resolution."""
def test_chain_of_links(self, yaml_file: Callable) -> None:
data = load_yaml(
yaml_file(
'target: final\n'
'link_a:\n'
' jw.link: link_b\n'
'link_b:\n'
' jw.link: target\n'
)
)
assert data['link_a'] == 'final'
assert data['link_b'] == 'final'
def test_chain_inplace(self, yaml_file: Callable) -> None:
data = load_yaml(
yaml_file('value: 100\na:\n jw.link: b\nb:\n jw.link: value\n')
)
assert data['a'] == 100
def test_chain_named(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('value: ok\nlink:\n jw.link: copy|value\n'))
assert data['link'] == {'copy': 'ok'}
# -- jw.link expansion - Cycle detection --------------------------------------
class TestCycleDetection:
"""Tests for cycle detection in links."""
def test_self_referencing_link(self, yaml_file: Callable) -> None:
with pytest.raises(ValueError, match = 'Cyclic link'):
load_yaml(yaml_file('link:\n jw.link: link\n'))
def test_mutual_cycle(self, yaml_file: Callable) -> None:
with pytest.raises(ValueError, match = 'Cyclic link'):
load_yaml(yaml_file('a:\n jw.link: b\nb:\n jw.link: a\n'))
def test_self_cycle_nested(self, yaml_file: Callable) -> None:
with pytest.raises(ValueError, match = 'Cyclic link'):
load_yaml(
yaml_file('root:\n inner:\n link:\n jw.link: root.inner\n')
)
def test_cycle_deep_chain(self, yaml_file: Callable) -> None:
with pytest.raises(ValueError, match = 'Cyclic link'):
load_yaml(
yaml_file('a:\n jw.link: c\nc:\n jw.link: b\nb:\n jw.link: a\n')
)
# -- jw.link expansion - Missing targets --------------------------------------
class TestMissingTargets:
"""Tests for missing link targets."""
def test_missing_absolute_target(self, yaml_file: Callable) -> None:
with pytest.raises(KeyError):
load_yaml(yaml_file('link:\n jw.link: nonexistent\n'))
def test_missing_relative_target(self, yaml_file: Callable) -> None:
with pytest.raises(ValueError, match = 'above root'):
load_yaml(yaml_file('link:\n jw.link: ..missing\n'))
def test_missing_deep_target(self, yaml_file: Callable) -> None:
with pytest.raises(KeyError):
load_yaml(
yaml_file('exists:\n val: ok\nlink:\n jw.link: exists.missing\n')
)
def test_missing_relative_deep_target(self, yaml_file: Callable) -> None:
with pytest.raises(KeyError):
load_yaml(
yaml_file('a:\n b: val\nnode:\n link:\n jw.link: ..a.missing\n')
)
# -- jw.link expansion - No links (regression) --------------------------------
class TestNoLinksRegression:
"""Ensure data without links passes through unchanged."""
def test_simple_no_links(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('a: 1\nb:\n c: 2\n'))
assert data == {'a': 1, 'b': {'c': 2}}
def test_complex_structure(self, yaml_file: Callable) -> None:
data = load_yaml(
yaml_file('list:\n - a\n - b\nnested:\n deep:\n value: 42\n')
)
assert data['list'] == ['a', 'b']
assert data['nested']['deep']['value'] == 42
def test_jw_link_with_siblings_unchanged(self, yaml_file: Callable) -> None:
"""jw.link with sibling keys should NOT be expanded."""
data = load_yaml(
yaml_file('target: val\nlink:\n jw.link: target\n other: kept\n')
)
# The jw.link marker with siblings is left as-is
assert 'jw.link' in data['link']
assert data['link']['other'] == 'kept'
# -- Combined: Include + Links ------------------------------------------------
class TestIncludePlusLinks:
"""Tests combining include directives and link expansion."""
def test_include_then_link(self, temp_dir: Callable) -> None:
base = temp_dir(
[
('base.yaml', 'shared: from_include\n'),
('main.yaml', 'include: base.yaml\nlink:\n jw.link: shared\n'),
]
)
data = load_yaml(pathlib.Path(base) / 'main.yaml')
assert data['shared'] == 'from_include'
assert data['link'] == 'from_include'
def test_link_in_included_file(self, temp_dir: Callable) -> None:
base = temp_dir(
[
('base.yaml', 'target: included\ndecorator:\n jw.link: target\n'),
('main.yaml', 'include: base.yaml\nlocal: here\n'),
]
)
data = load_yaml(pathlib.Path(base) / 'main.yaml')
assert data['target'] == 'included'
assert data['decorator'] == 'included'
def test_relative_link_to_included(self, temp_dir: Callable) -> None:
base = temp_dir(
[
('base.yaml', 'base_val: ok\n'),
(
'main.yaml',
'include: base.yaml\nlocal:\n link:\n jw.link: ..base_val\n'
),
]
)
data = load_yaml(pathlib.Path(base) / 'main.yaml')
assert data['local']['link'] == 'ok'
# -- jw.link expansion - Edge cases -------------------------------------------
class TestEdgeCases:
"""Tests for edge cases in link expansion."""
def test_empty_string_value(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('target: ""\nlink:\n jw.link: target\n'))
assert data['link'] == ''
def test_zero_value(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('target: 0\nlink:\n jw.link: target\n'))
assert data['link'] == 0
def test_false_value(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('target: false\nlink:\n jw.link: target\n'))
assert data['link'] is False
def test_none_target(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('target: null\nlink:\n jw.link: target\n'))
assert data['link'] is None
def test_complex_nested_inplace(self, yaml_file: Callable) -> None:
data = load_yaml(
yaml_file(
'target:\n'
' nested:\n'
' dict:\n'
' deep: value\n'
'link:\n'
' jw.link: target.nested.dict\n'
)
)
assert data['link']['deep'] == 'value'
def test_link_to_list_of_dicts(self, yaml_file: Callable) -> None:
data = load_yaml(
yaml_file('target:\n - key: a\n - key: b\nlink:\n jw.link: target\n')
)
assert data['link'] == [{'key': 'a'}, {'key': 'b'}]
def test_multiple_links_same_target(self, yaml_file: Callable) -> None:
data = load_yaml(
yaml_file('target: val\na:\n jw.link: target\nb:\n jw.link: target\n')
)
assert data['a'] == 'val'
assert data['b'] == 'val'
def test_named_link_to_list(self, yaml_file: Callable) -> None:
data = load_yaml(
yaml_file('target:\n - x\n - y\nlink:\n jw.link: items|target\n')
)
assert data['link'] == {'items': ['x', 'y']}
def test_link_value_with_pipe_in_target_key(self, yaml_file: Callable) -> None:
"""Key with pipe in name — pipe triggers named link parsing."""
with pytest.raises(KeyError):
load_yaml(yaml_file('my|key: val\nlink:\n jw.link: my|key\n'))
def test_named_link_with_numeric_prefix(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('target: ok\nlink:\n jw.link: 123target|target\n'))
assert data['link'] == {'123target': 'ok'}
# -- jw.link expansion - Path resolution --------------------------------------
class TestPathResolution:
"""Tests for path resolution logic."""
def test_absolute_single_key(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('key: val\nlink:\n jw.link: key\n'))
assert data['link'] == 'val'
def test_absolute_multi_level(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('a:\n b:\n c: deep\nlink:\n jw.link: a.b.c\n'))
assert data['link'] == 'deep'
def test_relative_from_list_index(self, yaml_file: Callable) -> None:
"""Links inside list items should resolve correctly."""
data = load_yaml(
yaml_file(
'target: val\nitems:\n - plain\n - jw.link: target\n - more\n'
)
)
assert data['items'][1] == 'val'
def test_link_to_nested_value(self, yaml_file: Callable) -> None:
data = load_yaml(
yaml_file(
'a:\n nested:\n deep: value\nlink:\n jw.link: a.nested.deep\n'
)
)
assert data['link'] == 'value'
# -- jw.link expansion - Type preservation ------------------------------------
class TestTypePreservation:
"""Ensure linked values preserve their original types."""
def test_string_preserved(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('target: "42"\nlink:\n jw.link: target\n'))
assert isinstance(data['link'], str)
assert data['link'] == '42'
def test_int_preserved(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('target: 42\nlink:\n jw.link: target\n'))
assert isinstance(data['link'], int)
assert data['link'] == 42
def test_float_preserved(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('target: 3.14\nlink:\n jw.link: target\n'))
assert isinstance(data['link'], float)
assert data['link'] == pytest.approx(3.14)
def test_bool_preserved(self, yaml_file: Callable) -> None:
data = load_yaml(yaml_file('target: true\nlink:\n jw.link: target\n'))
assert isinstance(data['link'], bool)
assert data['link'] is True
def test_list_preserved(self, yaml_file: Callable) -> None:
data = load_yaml(
yaml_file('target:\n - 1\n - 2\n - 3\nlink:\n jw.link: target\n')
)
assert isinstance(data['link'], list)
assert data['link'] == [1, 2, 3]
def test_nested_types_preserved(self, yaml_file: Callable) -> None:
data = load_yaml(
yaml_file(
'target:\n - num: 1\n flag: true\nlink:\n jw.link: target\n'
)
)
assert data['link'][0]['num'] == 1
assert data['link'][0]['flag'] is True