Skip to content

Commit

Permalink
Allow NamedLoaderContexts to be returned from loader
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
dwoz authored and vzhestkov committed Sep 17, 2024
1 parent b2faa01 commit 438eb4e
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
5 changes: 4 additions & 1 deletion salt/loader/lazy.py
Original file line number Diff line number Diff line change
Expand Up @@ -1246,7 +1246,10 @@ def _run_as(self, _func_or_method, *args, **kwargs):
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)
Expand Down
8 changes: 8 additions & 0 deletions tests/pytests/integration/modules/test_config.py
Original file line number Diff line number Diff line change
@@ -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)
13 changes: 13 additions & 0 deletions tests/pytests/unit/loader/test_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,16 @@ def test_raw_mod_functions():
ret = salt.loader.raw_mod(opts, "grains", "get")
for k, v in ret.items():
assert isinstance(v, salt.loader.lazy.LoadedFunc)


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"

0 comments on commit 438eb4e

Please sign in to comment.