loader: Add __opts__ to pack if not already present

This commit is contained in:
Richard Hansen 2022-11-01 03:06:11 -04:00 committed by Megan Wilhite
parent 29812c3dcd
commit d7168f8a2c
5 changed files with 41 additions and 0 deletions

3
changelog/63013.fixed Normal file
View file

@ -0,0 +1,3 @@
The `__opts__` dunder dictionary is now added to the loader's `pack` if not
already present, which makes it accessible via the
`salt.loader.context.NamedLoaderContext` class.

View file

@ -155,6 +155,11 @@ The following dunder dictionaries are always defined, but may be empty
__opts__
--------
..versionchanged:: 3006.0
The ``__opts__`` dictionary can now be accessed via
:py:mod:`~salt.loader.context``.
Defined in: All modules
The ``__opts__`` dictionary contains all of the options passed in the

View file

@ -590,6 +590,10 @@ class LazyLoader(salt.utils.lazy.LazyDict):
if key == "logger":
continue
mod_opts[key] = val
if "__opts__" not in self.pack:
self.pack["__opts__"] = mod_opts
return mod_opts
def _iter_files(self, mod_name):

View file

@ -45,3 +45,12 @@ def test_named_loader_context_deepcopy():
assert coppied.name == named_context.name
assert id(coppied.loader_context) == id(named_context.loader_context)
assert id(coppied.default) != id(named_context.default)
def test_named_loader_context_opts():
loader_context = salt.loader.context.LoaderContext()
opts = loader_context.named_context("__opts__")
loader = salt.loader.lazy.LazyLoader(["/foo"], opts={"foo": "bar"})
with salt.loader.context.loader_context(loader):
assert "foo" in opts
assert opts["foo"] == "bar"

View file

@ -119,3 +119,23 @@ def test_missing_loader_from_salt_internal_loaders():
salt.loader._module_dirs(
{"extension_modules": "/tmp/foo"}, "missingmodules", "module"
)
def test_loader_pack_always_has_opts(loader_dir):
loader = salt.loader.lazy.LazyLoader([loader_dir], opts={"foo": "bar"})
assert "__opts__" in loader.pack
assert "foo" in loader.pack["__opts__"]
assert loader.pack["__opts__"]["foo"] == "bar"
def test_loader_pack_opts_not_overwritten(loader_dir):
opts = {"foo": "bar"}
loader = salt.loader.lazy.LazyLoader(
[loader_dir],
opts={"foo": "bar"},
pack={"__opts__": {"baz": "bif"}},
)
assert "__opts__" in loader.pack
assert "foo" not in loader.pack["__opts__"]
assert "baz" in loader.pack["__opts__"]
assert loader.pack["__opts__"]["baz"] == "bif"