"""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 ------------------------------------------------------------------ _YamlFile = Callable[[str], str] _TempDir = Callable[[list[tuple[str, str]]], str] @pytest.fixture def yaml_file() -> _YamlFile: """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[_TempDir, None, None]: """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: _YamlFile) -> None: data = load_yaml(yaml_file('key: value\n')) assert data == {'key': 'value'} def test_nested_dict(self, yaml_file: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> None: data = load_yaml(yaml_file('')) assert data == {} def test_none_root(self, yaml_file: _YamlFile) -> None: data = load_yaml(yaml_file('---\n')) assert data == {} def test_string_value(self, yaml_file: _YamlFile) -> None: data = load_yaml(yaml_file('key: string value\n')) assert data == {'key': 'string value'} def test_number_value(self, yaml_file: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> None: data = load_yaml(yaml_file('key: null\n')) assert data['key'] is None def test_multiline_string(self, yaml_file: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _TempDir) -> None: base = temp_dir( [ ('base.yaml', 'shared: from_base\n'), ('main.yaml', 'jw.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: _TempDir) -> None: base = temp_dir( [ ('a.yaml', 'from_a: 1\nshared: a\n'), ('b.yaml', 'from_b: 2\nshared: b\n'), ('main.yaml', 'jw.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: _TempDir) -> None: base = temp_dir( [ ('main.yaml', 'jw.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: _TempDir) -> 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', 'jw.include:\n' ' - override.yaml\n' 'config:\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: _TempDir) -> None: base = temp_dir( [ ('level1.yaml', 'from: level1\n'), ('level2.yaml', 'jw.include: level1.yaml\nfrom: level2\n'), ('main.yaml', 'jw.include: level2.yaml\n'), ] ) data = load_yaml(pathlib.Path(base) / 'main.yaml') assert data['from'] == 'level2' def test_include_circular_detect(self, temp_dir: _TempDir) -> None: base = temp_dir( [ ('a.yaml', 'jw.include: b.yaml\n'), ('b.yaml', 'jw.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: _TempDir) -> None: base = temp_dir( [ ('sub/inner.yaml', 'secret: found\n'), ('main.yaml', 'jw.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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> None: with pytest.raises(ValueError, match = 'cannot resolve target path'): load_yaml(yaml_file('link:\n jw.link: nonexistent\n')) def test_missing_relative_target(self, yaml_file: _YamlFile) -> 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: _YamlFile) -> None: with pytest.raises(ValueError, match = 'cannot resolve target path'): load_yaml( yaml_file('exists:\n val: ok\nlink:\n jw.link: exists.missing\n') ) def test_missing_relative_deep_target(self, yaml_file: _YamlFile) -> None: with pytest.raises(ValueError, match = 'cannot resolve target path'): load_yaml( yaml_file('a:\n b: val\nnode:\n link:\n jw.link: ..a.missing\n') ) def test_missing_target_in_list_raises(self, yaml_file: _YamlFile) -> None: """Navigating into a list by key name raises with context.""" with pytest.raises(ValueError, match = 'cannot resolve target path'): load_yaml(yaml_file('items:\n - a\nlink:\n jw.link: items.x\n')) def test_missing_target_error_names_link(self, yaml_file: _YamlFile) -> None: """The error message names the failing link and its location.""" with pytest.raises(ValueError, match = "jw.link 'nope' at link"): load_yaml(yaml_file('link:\n jw.link: nope\n')) # -- jw.link expansion - No links (regression) -------------------------------- class TestNoLinksRegression: """Ensure data without links passes through unchanged.""" def test_simple_no_links(self, yaml_file: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _TempDir) -> None: base = temp_dir( [ ('base.yaml', 'shared: from_include\n'), ('main.yaml', 'jw.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: _TempDir) -> None: base = temp_dir( [ ('base.yaml', 'target: included\ndecorator:\n jw.link: target\n'), ('main.yaml', 'jw.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: _TempDir) -> None: base = temp_dir( [ ('base.yaml', 'base_val: ok\n'), ( 'main.yaml', 'jw.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: _YamlFile) -> None: data = load_yaml(yaml_file('target: ""\nlink:\n jw.link: target\n')) assert data['link'] == '' def test_zero_value(self, yaml_file: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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_cached_link_expansion_not_aliased(self, yaml_file: _YamlFile) -> None: """Link results shared via the memoisation cache are independent.""" data = load_yaml( yaml_file( 'target:\n' ' x: 1\n' 'link_b:\n' ' jw.link: target\n' 'link_a:\n' ' jw.link: link_b\n' ) ) data['link_a']['x'] = 99 assert data['link_b']['x'] == 1 assert data['target']['x'] == 1 def test_named_link_to_list(self, yaml_file: _YamlFile) -> 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: _YamlFile) -> None: """Key with pipe in name — pipe triggers named link parsing.""" with pytest.raises(ValueError, match = 'cannot resolve target path'): load_yaml(yaml_file('my|key: val\nlink:\n jw.link: my|key\n')) def test_named_link_with_numeric_prefix(self, yaml_file: _YamlFile) -> None: data = load_yaml(yaml_file('target: ok\nlink:\n jw.link: 123target|target\n')) assert data['link'] == {'123target': 'ok'} def test_non_string_link_value_raises(self, yaml_file: _YamlFile) -> None: """Non-string jw.link values raise TypeError naming the value.""" with pytest.raises(TypeError, match = 'must be a string'): load_yaml(yaml_file('target: 42\nlink:\n jw.link: 42\n')) def test_non_string_inplace_link_value_raises(self, yaml_file: _YamlFile) -> None: """Non-string jw.inplace-link values raise TypeError.""" with pytest.raises(TypeError, match = 'must be a string'): load_yaml(yaml_file('target:\n a: 1\nentry:\n jw.inplace-link: 42\n')) # -- jw.inplace-link expansion ------------------------------------------------ class TestInplaceLink: """Tests for jw.inplace-link expansion with sibling merging.""" def test_inplace_link_no_siblings(self, yaml_file: _YamlFile) -> None: """jw.inplace-link alone replaces the value (like jw.link).""" data = load_yaml(yaml_file('target: val\nlink:\n jw.inplace-link: target\n')) assert data['link'] == 'val' def test_inplace_link_with_dict_siblings(self, yaml_file: _YamlFile) -> None: """jw.inplace-link with sibling keys deep-merges into resolved dict.""" data = load_yaml( yaml_file( 'target:\n' ' a: 1\n' ' b: 2\n' 'entry:\n' ' jw.inplace-link: target\n' ' c: 3\n' ' b: overridden\n' ) ) # a and b from target, c from siblings, b overridden by sibling assert data['entry']['a'] == 1 assert data['entry']['b'] == 'overridden' assert data['entry']['c'] == 3 def test_inplace_link_with_scalar_sibling(self, yaml_file: _YamlFile) -> None: """Scalar siblings merge into resolved dict.""" data = load_yaml( yaml_file( 'target:\n' ' nested: dict\n' 'entry:\n' ' jw.inplace-link: target\n' ' flag: true\n' ) ) assert data['entry']['nested'] == 'dict' assert data['entry']['flag'] is True def test_inplace_link_non_dict_target(self, yaml_file: _YamlFile) -> None: """Non-dict target without siblings replaces the value.""" data = load_yaml(yaml_file('target: val\nentry:\n jw.inplace-link: target\n')) assert data['entry'] == 'val' def test_inplace_link_non_dict_target_siblings_raise( self, yaml_file: _YamlFile ) -> None: """Non-dict target with sibling keys raises instead of dropping them.""" with pytest.raises(ValueError, match = 'not a mapping'): load_yaml( yaml_file( 'target: val\nentry:\n jw.inplace-link: target\n extra: kept\n' ) ) def test_inplace_link_list_target_siblings_raise( self, yaml_file: _YamlFile ) -> None: """List target with sibling keys raises instead of dropping them.""" with pytest.raises(ValueError, match = 'not a mapping'): load_yaml( yaml_file( 'target:\n - a\nentry:\n jw.inplace-link: target\n extra: kept\n' ) ) def test_inplace_link_relative_path(self, yaml_file: _YamlFile) -> None: """jw.inplace-link supports relative paths.""" data = load_yaml( yaml_file( 'sibling:\n' ' x: resolved\n' 'root:\n' ' entry:\n' ' jw.inplace-link: ..sibling\n' ' y: extra\n' ) ) assert data['root']['entry']['x'] == 'resolved' assert data['root']['entry']['y'] == 'extra' def test_inplace_link_cyclic(self, yaml_file: _YamlFile) -> None: """jw.inplace-link detects cycles.""" with pytest.raises(ValueError, match = 'Cyclic link'): load_yaml(yaml_file('a:\n jw.inplace-link: b\nb:\n jw.inplace-link: a\n')) def test_inplace_link_chain(self, yaml_file: _YamlFile) -> None: """jw.inplace-link resolves through transitive chains.""" data = load_yaml( yaml_file( 'target: final\n' 'a:\n' ' jw.inplace-link: b\n' 'b:\n' ' jw.inplace-link: target\n' ) ) assert data['a'] == 'final' def test_inplace_link_with_list_sibling(self, yaml_file: _YamlFile) -> None: """List sibling values merge into resolved dict.""" data = load_yaml( yaml_file( 'target:\n' ' key: val\n' 'entry:\n' ' jw.inplace-link: target\n' ' items:\n' ' - a\n' ' - b\n' ) ) assert data['entry']['key'] == 'val' assert data['entry']['items'] == ['a', 'b'] def test_inplace_link_in_list(self, yaml_file: _YamlFile) -> None: """jw.inplace-link works inside list items.""" data = load_yaml( yaml_file( 'target:\n' ' x: 1\n' 'items:\n' ' - jw.inplace-link: target\n' ' y: 2\n' ' - plain\n' ) ) assert data['items'][0] == {'x': 1, 'y': 2} assert data['items'][1] == 'plain' def test_inplace_link_deep_nesting(self, yaml_file: _YamlFile) -> None: """jw.inplace-link merges deeply nested dicts.""" data = load_yaml( yaml_file( 'target:\n' ' a:\n' ' b:\n' ' c: original\n' 'entry:\n' ' jw.inplace-link: target\n' ' a:\n' ' b:\n' ' d: added\n' ' e: new\n' ) ) assert data['entry']['a']['b']['c'] == 'original' assert data['entry']['a']['b']['d'] == 'added' assert data['entry']['a']['e'] == 'new' def test_inplace_link_override_deep(self, yaml_file: _YamlFile) -> None: """Sibling values override target values in deep merge.""" data = load_yaml( yaml_file( 'target:\n' ' a:\n' ' b: original\n' 'entry:\n' ' jw.inplace-link: target\n' ' a:\n' ' b: overridden\n' ) ) assert data['entry']['a']['b'] == 'overridden' def test_inplace_link_with_include(self, temp_dir: _TempDir) -> None: """jw.inplace-link works with included files.""" base = temp_dir( [ ('base.yaml', 'shared:\n from: include\n'), ( 'main.yaml', 'jw.include: base.yaml\nentry:\n' ' jw.inplace-link: shared\n local: here\n' ), ] ) data = load_yaml(pathlib.Path(base) / 'main.yaml') assert data['entry']['from'] == 'include' assert data['entry']['local'] == 'here' def test_inplace_link_transitive_relative(self, yaml_file: _YamlFile) -> None: """jw.inplace-link with relative paths resolves through chain. Target A's relative link '.chat-janware-com' should resolve from A's position in the tree, not from the position of the link that references A. """ data = load_yaml( yaml_file( 'section:\n' ' a:\n' ' jw.inplace-link: .b\n' ' b:\n' ' interface: open-ai\n' ' base_uri: http://example.com\n' 'ref:\n' ' jw.inplace-link: section.a\n' ) ) # ref -> section.a -> .b (relative from section.a -> section.b) assert data['ref']['interface'] == 'open-ai' assert data['ref']['base_uri'] == 'http://example.com' # -- jw.include with target path ------------------------------------------------ class TestIncludeWithPath: """Tests for jw.include with target path specification.""" def test_include_at_root(self, temp_dir: _TempDir) -> None: """Plain include merges at root (original behavior).""" base = temp_dir( [ ('base.yaml', 'shared: from_base\n'), ('main.yaml', 'jw.include: base.yaml\n') ] ) data = load_yaml(pathlib.Path(base) / 'main.yaml') assert data['shared'] == 'from_base' def test_include_at_nested_path(self, temp_dir: _TempDir) -> None: """Include with path merges at the specified location.""" base = temp_dir( [ ('base.yaml', 'nested: value\n'), ('main.yaml', 'jw.include: entry|base.yaml\n') ] ) data = load_yaml(pathlib.Path(base) / 'main.yaml') assert data['entry']['nested'] == 'value' def test_include_at_deep_path(self, temp_dir: _TempDir) -> None: """Include at deep nested path creates intermediate dicts.""" base = temp_dir( [ ('base.yaml', 'deep: nested\n'), ('main.yaml', 'jw.include: a.b.c|base.yaml\n') ] ) data = load_yaml(pathlib.Path(base) / 'main.yaml') assert data['a']['b']['c']['deep'] == 'nested' def test_include_merge_with_existing(self, temp_dir: _TempDir) -> None: """Include merges with existing content at target path.""" base = temp_dir( [ ('base.yaml', 'from_include: included\n'), ( 'main.yaml', 'entry:\n existing: here\njw.include: entry|base.yaml\n' ), ] ) data = load_yaml(pathlib.Path(base) / 'main.yaml') assert data['entry']['existing'] == 'here' assert data['entry']['from_include'] == 'included' def test_include_override_existing(self, temp_dir: _TempDir) -> None: """Local content at target path overrides included content.""" base = temp_dir( [ ('base.yaml', 'existing: from_include\n'), ( 'main.yaml', 'entry:\n existing: original\njw.include: entry|base.yaml\n' ), ] ) data = load_yaml(pathlib.Path(base) / 'main.yaml') # Local content (original) wins over included (from_include) assert data['entry']['existing'] == 'original' def test_include_non_dict_intermediate_raises(self, temp_dir: _TempDir) -> 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: _TempDir) -> 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: _TempDir) -> None: """Multiple includes can target different paths.""" base = temp_dir( [ ('base1.yaml', 'a: 1\n'), ('base2.yaml', 'b: 2\n'), ( 'main.yaml', 'jw.include:\n - section1|base1.yaml\n' ' - section2|base2.yaml\n' ), ] ) data = load_yaml(pathlib.Path(base) / 'main.yaml') assert data['section1']['a'] == 1 assert data['section2']['b'] == 2 def test_include_with_optional(self, temp_dir: _TempDir) -> None: """Optional includes with path work correctly.""" base = temp_dir( [ ('base.yaml', 'opt: val\n'), ('main.yaml', 'jw.include: -section|base.yaml\n'), ] ) data = load_yaml(pathlib.Path(base) / 'main.yaml') assert data['section']['opt'] == 'val' def test_optional_include_missing_target(self, temp_dir: _TempDir) -> None: """A missing optional include at a target path creates no key.""" base = temp_dir( [ ('main.yaml', 'jw.include: -a.b|missing.yaml\nlocal: yes\n'), ] ) data = load_yaml(pathlib.Path(base) / 'main.yaml') assert data == {'local': True} def test_optional_include_missing_existing_target(self, temp_dir: _TempDir) -> None: """A missing optional include leaves an existing target untouched.""" base = temp_dir( [ ( 'main.yaml', 'jw.include: -section|missing.yaml\nsection:\n kept: yes\n', ), ] ) data = load_yaml(pathlib.Path(base) / 'main.yaml') assert data == {'section': {'kept': True}} def test_include_pipe_in_filename(self, temp_dir: _TempDir) -> None: """The first pipe separates target and file, pipes stay in the file.""" base = temp_dir( [ ('weird|name.yaml', 'pip: ed\n'), ('main.yaml', 'jw.include: section|weird|name.yaml\n'), ] ) data = load_yaml(pathlib.Path(base) / 'main.yaml') assert data['section']['pip'] == 'ed' def test_include_plain_and_path_mixed(self, temp_dir: _TempDir) -> None: """Mix plain and path-based includes in same document.""" base = temp_dir( [ ('plain.yaml', 'plain_key: plain_val\n'), ('target.yaml', 'target_key: target_val\n'), ( 'main.yaml', 'jw.include:\n - plain.yaml\n' ' - section|target.yaml\n' ), ] ) data = load_yaml(pathlib.Path(base) / 'main.yaml') assert data['plain_key'] == 'plain_val' assert data['section']['target_key'] == 'target_val' # -- jw.include globbing -------------------------------------------------------- class TestIncludeGlobbing: """Tests for glob support in jw.include file specs.""" def test_glob_multiple_files(self, temp_dir: _TempDir) -> None: """All glob matches are included.""" base = temp_dir( [ ('conf/a.yaml', 'from_a: 1\n'), ('conf/b.yaml', 'from_b: 2\n'), ('main.yaml', 'jw.include: conf/*.yaml\n'), ] ) data = load_yaml(pathlib.Path(base) / 'main.yaml') assert data['from_a'] == 1 assert data['from_b'] == 2 def test_glob_lexical_order(self, temp_dir: _TempDir) -> None: """Matches are included in lexical order, later files win.""" base = temp_dir( [ ('conf/1.yaml', 'order: first\nshared: one\n'), ('conf/10.yaml', 'order: ten\n'), ('conf/2.yaml', 'order: second\nshared: two\n'), ('main.yaml', 'jw.include: conf/*.yaml\n'), ] ) data = load_yaml(pathlib.Path(base) / 'main.yaml') # Lexical order: 1.yaml, 10.yaml, 2.yaml assert data['order'] == 'second' assert data['shared'] == 'two' def test_glob_char_class(self, temp_dir: _TempDir) -> None: """Character classes match like other glob syntax.""" base = temp_dir( [ ('conf/g1.yaml', 'one: 1\n'), ('conf/g2.yaml', 'two: 2\n'), ('conf/g3.yaml', 'three: 3\n'), ('main.yaml', 'jw.include: conf/g[12].yaml\n'), ] ) data = load_yaml(pathlib.Path(base) / 'main.yaml') assert data['one'] == 1 assert data['two'] == 2 assert 'three' not in data def test_glob_question_mark(self, temp_dir: _TempDir) -> None: """A question mark matches exactly one character.""" base = temp_dir( [ ('conf/g1.yaml', 'one: 1\n'), ('conf/g12.yaml', 'twelve: 12\n'), ('main.yaml', 'jw.include: conf/g?.yaml\n'), ] ) data = load_yaml(pathlib.Path(base) / 'main.yaml') assert data['one'] == 1 assert 'twelve' not in data def test_glob_no_match_raises(self, temp_dir: _TempDir) -> None: """A non-optional glob matching no files raises.""" base = temp_dir([('main.yaml', 'jw.include: missing/*.yaml\n')]) with pytest.raises(ValueError, match = 'matches no files'): load_yaml(pathlib.Path(base) / 'main.yaml') def test_glob_optional_no_match(self, temp_dir: _TempDir) -> None: """An optional glob matching no files contributes nothing.""" base = temp_dir([('main.yaml', 'jw.include: -missing/*.yaml\n')]) data = load_yaml(pathlib.Path(base) / 'main.yaml') assert data == {} def test_glob_with_target_path(self, temp_dir: _TempDir) -> None: """Each match is merged at the target path, in lexical order.""" base = temp_dir( [ ('conf/a.yaml', 'first: a\nshared: from_a\n'), ('conf/b.yaml', 'shared: from_b\nextra: b\n'), ('main.yaml', 'jw.include: section|conf/*.yaml\n'), ] ) data = load_yaml(pathlib.Path(base) / 'main.yaml') assert data['section']['first'] == 'a' # Existing content at the target path wins, so a.yaml's 'shared' # beats b.yaml's; b.yaml still contributes its new key assert data['section']['shared'] == 'from_a' assert data['section']['extra'] == 'b' def test_glob_absolute_path(self, temp_dir: _TempDir) -> None: """Absolute glob paths work, not just relative ones.""" base = temp_dir( [ ('conf/a.yaml', 'from_a: 1\n'), ('conf/b.yaml', 'from_b: 2\n'), ] ) main = pathlib.Path(base) / 'main.yaml' main.write_text(f'jw.include: {base}/conf/*.yaml\n') data = load_yaml(main) assert data['from_a'] == 1 assert data['from_b'] == 2 def test_glob_self_include_raises(self, temp_dir: _TempDir) -> None: """A glob matching the including file itself is a cycle.""" base = temp_dir([('main.yaml', 'jw.include: "*.yaml"\n')]) with pytest.raises(ValueError, match = 'Cyclic YAML include'): load_yaml(pathlib.Path(base) / 'main.yaml') class TestIncludeVarExpansion: """Tests for $(VAR) and ${VAR} expansion in include specs.""" def test_expand_braced_var( self, temp_dir: _TempDir, monkeypatch: pytest.MonkeyPatch ) -> None: """${VAR} in a top-level include spec is expanded.""" base = temp_dir([('conf/a.yaml', 'from_a: 1\n')]) monkeypatch.setenv('LOAD_YAML_TEST_TOP', base) main = pathlib.Path(base) / 'main.yaml' main.write_text('jw.include: ${LOAD_YAML_TEST_TOP}/conf/a.yaml\n') data = load_yaml(main) assert data['from_a'] == 1 def test_expand_paren_var( self, temp_dir: _TempDir, monkeypatch: pytest.MonkeyPatch ) -> None: """$(VAR) in a top-level include spec is expanded.""" base = temp_dir([('conf/a.yaml', 'from_a: 1\n')]) monkeypatch.setenv('LOAD_YAML_TEST_TOP', base) main = pathlib.Path(base) / 'main.yaml' main.write_text('jw.include: $(LOAD_YAML_TEST_TOP)/conf/a.yaml\n') data = load_yaml(main) assert data['from_a'] == 1 def test_expand_var_with_glob( self, temp_dir: _TempDir, monkeypatch: pytest.MonkeyPatch ) -> None: """Expansion and glob expansion compose.""" base = temp_dir( [ ('conf/a.yaml', 'from_a: 1\n'), ('conf/b.yaml', 'from_b: 2\n'), ] ) monkeypatch.setenv('LOAD_YAML_TEST_TOP', base) main = pathlib.Path(base) / 'main.yaml' main.write_text('jw.include: ${LOAD_YAML_TEST_TOP}/conf/*.yaml\n') data = load_yaml(main) assert data['from_a'] == 1 assert data['from_b'] == 2 def test_undefined_var_raises(self, temp_dir: _TempDir) -> None: """An undefined variable in a top-level spec raises.""" base = temp_dir([('main.yaml', 'jw.include: ${LOAD_YAML_TEST_NOPE}/x.yaml\n')]) with pytest.raises(ValueError, match = 'Undefined variable'): load_yaml(pathlib.Path(base) / 'main.yaml') def test_nested_spec_not_expanded(self, temp_dir: _TempDir) -> None: """Specs in included documents are never expanded.""" base = temp_dir( [ ('main.yaml', 'jw.include: nested/real.yaml\n'), ('nested/real.yaml', 'jw.include: ${HOME}/x.yaml\n'), ('nested/${HOME}/x.yaml', 'literal: yes\n'), ] ) data = load_yaml(pathlib.Path(base) / 'main.yaml') assert data['literal'] is True class TestIncludeMap: """Tests for the jw.include-map include spec rewrite table.""" def test_exact_rewrite(self, temp_dir: _TempDir) -> None: """An exact LHS rewrites the spec to the RHS.""" base = temp_dir( [ ( 'wrapper.yaml', 'jw.include-map:\n' ' - /prod/etc/app.yaml: test/app.yaml\n' 'jw.include: /prod/etc/app.yaml\n' ), ('test/app.yaml', 'from_test: 1\n'), ] ) data = load_yaml(pathlib.Path(base) / 'wrapper.yaml') assert data['from_test'] == 1 def test_glob_rewrite(self, temp_dir: _TempDir) -> None: """A glob LHS captures into a glob RHS.""" base = temp_dir( [ ('prod.d/one.yaml', 'one: prod\n'), ('prod.d/two.yaml', 'two: prod\n'), ('test.d/one.yaml', 'one: test\n'), ('test.d/two.yaml', 'two: test\n'), ( 'wrapper.yaml', 'jw.include-map:\n' ' - prod.d/*.yaml: test.d/*.yaml\n' 'jw.include: prod.d/*.yaml\n' ), ] ) data = load_yaml(pathlib.Path(base) / 'wrapper.yaml') assert data['one'] == 'test' assert data['two'] == 'test' def test_rhs_list(self, temp_dir: _TempDir) -> None: """A list RHS expands to multiple sources in list order.""" base = temp_dir( [ ('t1/a.yaml', 'one: 1\nshared: t1a\n'), ('t1/b.yaml', 'shared: t1b\ntwo: 2\n'), ('t2/a.yaml', 'shared: t2a\nthree: 3\n'), ( 'wrapper.yaml', 'jw.include-map:\n' ' - prod.d/*.yaml: [t1/*.yaml, t2/*.yaml]\n' 'jw.include: prod.d/*.yaml\n' ), ] ) data = load_yaml(pathlib.Path(base) / 'wrapper.yaml') assert data['one'] == 1 assert data['two'] == 2 assert data['three'] == 3 # Sources merge in RHS list order, later files win assert data['shared'] == 't2a' def test_rewrite_before_disk_lookup(self, temp_dir: _TempDir) -> None: """The LHS pattern need not match anything on disk.""" base = temp_dir( [ ('test.d/one.yaml', 'one: 1\n'), ( 'wrapper.yaml', 'jw.include-map:\n' ' - prod.d/*.yaml: test.d/*.yaml\n' 'jw.include: prod.d/one.yaml\n' ), ] ) data = load_yaml(pathlib.Path(base) / 'wrapper.yaml') assert data['one'] == 1 def test_first_match_wins(self, temp_dir: _TempDir) -> None: """The first matching entry wins; later entries are ignored.""" base = temp_dir( [ ('first.yaml', 'source: first\n'), ('second.yaml', 'source: second\n'), ( 'wrapper.yaml', 'jw.include-map:\n' ' - /prod/etc/app.yaml: first.yaml\n' ' - /prod/etc/app.yaml: second.yaml\n' 'jw.include: /prod/etc/app.yaml\n' ), ] ) data = load_yaml(pathlib.Path(base) / 'wrapper.yaml') assert data['source'] == 'first' def test_relative_lhs_collision(self, temp_dir: _TempDir) -> None: """Same-named relative includes are disambiguated by directory.""" base = temp_dir( [ ('prod/a/doc.yaml', 'jw.include: x.yaml\n'), ('prod/b/doc.yaml', 'jw.include: x.yaml\n'), ('ax.yaml', 'from_ax: 1\n'), ('bx.yaml', 'from_bx: 2\n'), ( 'wrapper.yaml', 'jw.include-map:\n' ' - prod/a/x.yaml: ax.yaml\n' ' - prod/b/x.yaml: bx.yaml\n' 'jw.include:\n' ' - prod/a/doc.yaml\n' ' - prod/b/doc.yaml\n' ), ] ) data = load_yaml(pathlib.Path(base) / 'wrapper.yaml') assert data['from_ax'] == 1 assert data['from_bx'] == 2 def test_relative_rhs_against_wrapper(self, temp_dir: _TempDir) -> None: """A relative RHS resolves against the wrapper's directory.""" base = temp_dir( [ ('prod/app.yaml', 'jw.include: deep.yaml\n'), ('copies/deep.yaml', 'deep: ok\n'), ( 'wrapper.yaml', 'jw.include-map:\n' ' - prod/deep.yaml: copies/deep.yaml\n' 'jw.include: prod/app.yaml\n' ), ] ) data = load_yaml(pathlib.Path(base) / 'wrapper.yaml') assert data['deep'] == 'ok' def test_absolute_lhs(self, temp_dir: _TempDir) -> None: """Absolute LHS patterns match production-style includes.""" base = temp_dir( [ ('prod.yaml', 'jw.include: /etc/jw/app/*.yaml\n'), ('test/app.yaml', 'from_test: 1\n'), ( 'wrapper.yaml', 'jw.include-map:\n' ' - /etc/jw/app/*.yaml: test/app.yaml\n' 'jw.include: prod.yaml\n' ), ] ) data = load_yaml(pathlib.Path(base) / 'wrapper.yaml') assert data['from_test'] == 1 def test_optional_flag_inherited(self, temp_dir: _TempDir) -> None: """Rewritten sources inherit the original spec's optionality.""" base = temp_dir( [ ( 'wrapper.yaml', 'jw.include-map:\n' ' - prod/*.yaml: nowhere/*.yaml\n' 'jw.include: -prod/missing.yaml\n' ), ] ) data = load_yaml(pathlib.Path(base) / 'wrapper.yaml') assert data == {} def test_non_optional_rewrite_missing_raises(self, temp_dir: _TempDir) -> None: """A rewritten plain path that does not exist raises.""" base = temp_dir( [ ( 'wrapper.yaml', 'jw.include-map:\n' ' - prod/*.yaml: nowhere/*.yaml\n' 'jw.include: prod/missing.yaml\n' ), ] ) with pytest.raises(FileNotFoundError): load_yaml(pathlib.Path(base) / 'wrapper.yaml') def test_target_path_preserved(self, temp_dir: _TempDir) -> None: """The target path prefix survives the rewrite.""" base = temp_dir( [ ('t/one.yaml', 'a: 1\n'), ('t/two.yaml', 'b: 2\n'), ( 'wrapper.yaml', 'jw.include-map:\n' ' - prod/*.yaml: t/*.yaml\n' 'jw.include: section|prod/*.yaml\n' ), ] ) data = load_yaml(pathlib.Path(base) / 'wrapper.yaml') assert data['section'] == {'a': 1, 'b': 2} def test_nested_map_raises(self, temp_dir: _TempDir) -> None: """jw.include-map in a non-top-level document raises.""" base = temp_dir( [ ('inner.yaml', 'jw.include-map:\n - a.yaml: b.yaml\n'), ('wrapper.yaml', 'jw.include: inner.yaml\n'), ] ) with pytest.raises(ValueError, match = 'top-level'): load_yaml(pathlib.Path(base) / 'wrapper.yaml') def test_empty_map_is_noop(self, temp_dir: _TempDir) -> None: """An empty map leaves all includes untouched.""" base = temp_dir( [ ('app.yaml', 'ok: 1\n'), ('wrapper.yaml', 'jw.include-map: []\n' 'jw.include: app.yaml\n'), ] ) data = load_yaml(pathlib.Path(base) / 'wrapper.yaml') assert data['ok'] == 1 def test_map_not_a_list_raises(self, temp_dir: _TempDir) -> None: """A non-list jw.include-map value raises.""" base = temp_dir([('wrapper.yaml', 'jw.include-map: {}\n')]) with pytest.raises(TypeError, match = 'must be a list'): load_yaml(pathlib.Path(base) / 'wrapper.yaml') def test_multi_key_entry_raises(self, temp_dir: _TempDir) -> None: """A map entry with two keys raises.""" base = temp_dir( [ ( 'wrapper.yaml', 'jw.include-map:\n' ' - a.yaml: b.yaml\n' ' c.yaml: d.yaml\n' ), ] ) with pytest.raises(ValueError, match = 'single-key'): load_yaml(pathlib.Path(base) / 'wrapper.yaml') def test_rhs_star_overflow_raises(self, temp_dir: _TempDir) -> None: """A RHS with more stars than the LHS raises.""" base = temp_dir( [ ('wrapper.yaml', 'jw.include-map:\n - a/*.yaml: b/*/*.yaml\n'), ] ) with pytest.raises(ValueError, match = r'more "\*"'): load_yaml(pathlib.Path(base) / 'wrapper.yaml') def test_lhs_question_mark_raises(self, temp_dir: _TempDir) -> None: """A '?' in the LHS raises; only '*' is supported.""" base = temp_dir([('wrapper.yaml', 'jw.include-map:\n - a/?.yaml: b.yaml\n')]) with pytest.raises(ValueError, match = r'only "\*"'): load_yaml(pathlib.Path(base) / 'wrapper.yaml') def test_var_in_rhs( self, temp_dir: _TempDir, monkeypatch: pytest.MonkeyPatch ) -> None: """RHS values expand environment variables.""" base = temp_dir([('app.yaml', 'ok: 1\n')]) monkeypatch.setenv('LOAD_YAML_TEST_TOP', base) main = pathlib.Path(base) / 'wrapper.yaml' main.write_text( 'jw.include-map:\n' ' - /etc/app.yaml: ${LOAD_YAML_TEST_TOP}/app.yaml\n' 'jw.include: /etc/app.yaml\n' ) data = load_yaml(main) assert data['ok'] == 1 class TestIncludeMapNoAbsolute: """Tests for the jw.include-map-no-absolute guard.""" def test_absolute_uncovered_raises(self, temp_dir: _TempDir) -> None: """An absolute spec with no matching entry raises.""" base = temp_dir( [ ( 'wrapper.yaml', 'jw.include-map: []\n' 'jw.include-map-no-absolute: true\n' 'jw.include: /etc/app.yaml\n' ), ] ) with pytest.raises(ValueError, match = 'not covered by the include map'): load_yaml(pathlib.Path(base) / 'wrapper.yaml') def test_absolute_covered_ok(self, temp_dir: _TempDir) -> None: """An absolute spec covered by the map loads.""" base = temp_dir( [ ('app.yaml', 'ok: 1\n'), ( 'wrapper.yaml', 'jw.include-map:\n' ' - /etc/app.yaml: app.yaml\n' 'jw.include-map-no-absolute: true\n' 'jw.include: /etc/app.yaml\n' ), ] ) data = load_yaml(pathlib.Path(base) / 'wrapper.yaml') assert data['ok'] == 1 def test_nested_absolute_uncovered_raises(self, temp_dir: _TempDir) -> None: """The guard covers nested includes, not just the wrapper's own.""" base = temp_dir( [ ('prod.yaml', 'jw.include: /etc/app.yaml\n'), ( 'wrapper.yaml', 'jw.include-map: []\n' 'jw.include-map-no-absolute: true\n' 'jw.include: prod.yaml\n' ), ] ) with pytest.raises(ValueError, match = 'not covered by the include map'): load_yaml(pathlib.Path(base) / 'wrapper.yaml') def test_relative_specs_pass(self, temp_dir: _TempDir) -> None: """Relative specs are unaffected by the guard.""" base = temp_dir( [ ('app.yaml', 'ok: 1\n'), ( 'wrapper.yaml', 'jw.include-map: []\n' 'jw.include-map-no-absolute: true\n' 'jw.include: app.yaml\n' ), ] ) data = load_yaml(pathlib.Path(base) / 'wrapper.yaml') assert data['ok'] == 1 def test_identity_entry_whitelists(self, temp_dir: _TempDir) -> None: """An identity entry whitelists an absolute path.""" base = temp_dir([('real.yaml', 'ok: 1\n')]) main = pathlib.Path(base) / 'wrapper.yaml' main.write_text( 'jw.include-map:\n' f' - {base}/real.yaml: {base}/real.yaml\n' 'jw.include-map-no-absolute: true\n' f'jw.include: {base}/real.yaml\n' ) data = load_yaml(main) assert data['ok'] == 1 def test_default_is_false(self, temp_dir: _TempDir) -> None: """Without the flag, an uncovered absolute spec is read from disk.""" base = temp_dir( [('wrapper.yaml', 'jw.include-map: []\n' 'jw.include: /etc/app.yaml\n')] ) with pytest.raises(FileNotFoundError): load_yaml(pathlib.Path(base) / 'wrapper.yaml') def test_nested_flag_raises(self, temp_dir: _TempDir) -> None: """The flag in a non-top-level document raises.""" base = temp_dir( [ ('inner.yaml', 'jw.include-map-no-absolute: true\n'), ('wrapper.yaml', 'jw.include: inner.yaml\n'), ] ) with pytest.raises(ValueError, match = 'top-level'): load_yaml(pathlib.Path(base) / 'wrapper.yaml') # -- jw.include with target path ------------------------------------------------ class TestPathResolution: """Tests for path resolution logic.""" def test_absolute_single_key(self, yaml_file: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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: _YamlFile) -> 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