Allow NamedLoaderContexts to be returned from loader

It is useful in some cases to return NamedLoaderContexts from loaded
functions. Instead of choking or requireing implimenters to call the
context's value() method before being de-scoped, detect when a
NamedLoaderContext has been returned and return the value from the
current context.
This commit is contained in:
Daniel A. Wozniak 2024-06-18 23:39:16 -07:00 committed by Daniel Wozniak
parent d1d84e87b3
commit c174570e53
3 changed files with 25 additions and 1 deletions

View file

@ -1257,7 +1257,10 @@ class LazyLoader(salt.utils.lazy.LazyDict):
self.parent_loader = current_loader
token = salt.loader.context.loader_ctxvar.set(self)
try:
return _func_or_method(*args, **kwargs)
ret = _func_or_method(*args, **kwargs)
if isinstance(ret, salt.loader.context.NamedLoaderContext):
ret = ret.value()
return ret
finally:
self.parent_loader = None
salt.loader.context.loader_ctxvar.reset(token)

View file

@ -0,0 +1,8 @@
import pytest
@pytest.mark.slow_test
def test_config_items(salt_cli, salt_minion):
ret = salt_cli.run("config.items", minion_tgt=salt_minion.id)
assert ret.returncode == 0
assert isinstance(ret.data, dict)

View file

@ -83,3 +83,16 @@ def test_named_loader_context_name_not_packed(tmp_path):
match="LazyLoader does not have a packed value for: __not_packed__",
):
loader["mymod.foobar"]()
def test_return_named_context_from_loaded_func(tmp_path):
opts = {
"optimization_order": [0],
}
contents = """
def foobar():
return __test__
"""
with pytest.helpers.temp_file("mymod.py", contents, directory=tmp_path):
loader = salt.loader.LazyLoader([tmp_path], opts, pack={"__test__": "meh"})
assert loader["mymod.foobar"]() == "meh"