Skip to content
Snippets Groups Projects
Commit cfa296d4 authored by Alexander Schlemmer's avatar Alexander Schlemmer
Browse files

ENH: more tests and replacements of sub dictionaries in lists

parent 9985cde5
No related branches found
No related tags found
2 merge requests!53Release 0.1,!25F macros
Pipeline #23200 passed with warnings
from .macro_yaml_object import defmacro_constructor, macro_constructor
from .macro_yaml_object import defmacro_constructor, macro_constructor, multimacro_constructor
......@@ -79,6 +79,8 @@ def substitute_dict(sourced: dict[str, Any], values: dict[str, Any]):
for i in d[k]:
if isinstance(i, str):
subst_list.append(substitute(i, values))
elif isinstance(i, dict):
subst_list.append(substitute_dict(i, values))
else:
subst_list.append(i)
d[k] = subst_list
......@@ -119,3 +121,12 @@ def macro_constructor(loader, node):
definition = deepcopy(macro.definition)
return substitute_dict(definition, params)
def multimacro_constructor(loader, node):
"""
Function that can be used to chain macros for complex definitions of dictionaries.
It can be registered in pyaml using:
yaml.SafeLoader.add_constructor("!multimacro", multimacro_constructor)
"""
pass
......@@ -22,12 +22,17 @@
# ** end header
#
from caoscrawler.macros import defmacro_constructor, macro_constructor
from caoscrawler.macros import defmacro_constructor, macro_constructor, multimacro_constructor
import yaml
import pytest
def test_macros():
@pytest.fixture
def register_macros():
yaml.SafeLoader.add_constructor("!defmacro", defmacro_constructor)
yaml.SafeLoader.add_constructor("!macro", macro_constructor)
yaml.SafeLoader.add_constructor("!multimacro", multimacro_constructor)
def test_macros(register_macros):
dat = yaml.load("""
defs:
- !defmacro
......@@ -52,3 +57,30 @@ testnode:
assert dat["testnode"]["obl"]["expanded_yea"]["yea"] == "$variable"
assert "expanded_bla" not in dat["testnode"]["obl"]
assert "bla" not in dat["testnode"]["obl"]["expanded_yea"]
def test_macro_list_replacment(register_macros):
dat = yaml.load("""
defs:
- !defmacro
name: test
params:
a: 2
b: bla
c: $variable
definition:
expanded_$b:
blubb:
- ok$a
- $b: $c
testnode:
obl: !macro
name: test
params:
a: 4
b: yea
""", Loader=yaml.SafeLoader)
assert isinstance(dat["testnode"]["obl"]["expanded_yea"]["blubb"], list)
assert len(dat["testnode"]["obl"]["expanded_yea"]["blubb"]) == 2
assert dat["testnode"]["obl"]["expanded_yea"]["blubb"][0] == "ok4"
assert dat["testnode"]["obl"]["expanded_yea"]["blubb"][1]["yea"] == "$variable"
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment