Additional test cases for slsutil. Reworking some of the slsutil to ensure test coverage is easier.

This commit is contained in:
Gareth J. Greenaway 2023-10-16 08:14:46 -07:00
parent 05541f6299
commit e1000011ae
No known key found for this signature in database
GPG key ID: 10B62F8A7CAD7A41
2 changed files with 179 additions and 3 deletions

View file

@ -163,13 +163,16 @@ def renderer(path=None, string=None, default_renderer="jinja|yaml", **kwargs):
if not path and not string:
raise salt.exceptions.SaltInvocationError("Must pass either path or string")
if path and string:
raise salt.exceptions.SaltInvocationError("Must not pass both path and string")
renderers = salt.loader.render(__opts__, __salt__)
if path:
path_or_string = __salt__["cp.get_url"](
path, saltenv=kwargs.get("saltenv", "base")
)
elif string:
if string:
path_or_string = ":string:"
kwargs["input_data"] = string

View file

@ -1,18 +1,20 @@
import logging
from io import StringIO
import pytest
import salt.exceptions
import salt.modules.slsutil as slsutil
from tests.support.mock import MagicMock
from tests.support.mock import MagicMock, patch
log = logging.getLogger(__name__)
@pytest.fixture
def configure_loader_modules(master_dirs, master_files):
def configure_loader_modules(master_dirs, master_files, minion_opts):
return {
slsutil: {
"__opts__": minion_opts,
"__salt__": {
"cp.list_master": MagicMock(return_value=master_files),
"cp.list_master_dirs": MagicMock(return_value=master_dirs),
@ -47,6 +49,21 @@ def test_banner():
check_banner(commentchar="//", borderchar="-")
check_banner(title="title here", text="text here")
check_banner(commentchar=" *")
check_banner(commentchar=" *", newline=False)
# Test when width result in a raised exception
with pytest.raises(salt.exceptions.ArgumentValueError):
slsutil.banner(width=4)
ret = slsutil.banner(
title="title here", text="text here", blockstart="/*", blockend="*/"
)
lines = ret.splitlines()
# test blockstart
assert lines[0] == "/*"
# test blockend
assert lines[-1] == "*/"
def check_banner(
@ -125,3 +142,159 @@ def test_findup():
with pytest.raises(salt.exceptions.CommandExecutionError):
slsutil.findup("red", "default.conf")
with pytest.raises(salt.exceptions.SaltInvocationError):
with patch.object(slsutil, "path_exists", return_value=False):
slsutil.findup("red", "default.conf")
with pytest.raises(salt.exceptions.SaltInvocationError):
slsutil.findup("red", {"file": "default.conf"})
def test_update():
"""
Test update function
"""
ret = slsutil.update({"foo": "Foo"}, {"bar": "Bar"})
assert ret == {"foo": "Foo", "bar": "Bar"}
ret = slsutil.update({"foo": "Foo"}, {"foo": "Bar"}, merge_lists=False)
assert ret == {"foo": "Bar"}
def test_merge():
"""
Test merge function
"""
ret = slsutil.merge({"foo": "Foo"}, {"bar": "Bar"}, strategy="smart")
assert ret == {"foo": "Foo", "bar": "Bar"}
ret = slsutil.merge({"foo": "Foo"}, {"foo": "Bar"}, strategy="aggregate")
assert ret == {"foo": "Bar"}
ret = slsutil.merge({"foo": "Foo"}, {"foo": "Bar"}, strategy="list")
assert ret == {"foo": ["Foo", "Bar"]}
ret = slsutil.merge({"foo": "Foo"}, {"foo": "Bar"}, strategy="overwrite")
assert ret == {"foo": "Bar"}
ret = slsutil.merge(
{"foo": {"Foo": "Bar"}}, {"foo": {"Foo": "Baz"}}, strategy="recurse"
)
assert ret == {"foo": {"Foo": "Baz"}}
def test_merge_all():
"""
Test merge_all function
"""
ret = slsutil.merge_all([{"foo": "Foo"}, {"bar": "Bar"}], strategy="smart")
assert ret == {"foo": "Foo", "bar": "Bar"}
ret = slsutil.merge_all([{"foo": "Foo"}, {"foo": "Bar"}], strategy="aggregate")
assert ret == {"foo": "Bar"}
ret = slsutil.merge_all([{"foo": "Foo"}, {"foo": "Bar"}], strategy="overwrite")
assert ret == {"foo": "Bar"}
ret = slsutil.merge_all(
[{"foo": {"Foo": "Bar"}}, {"foo": {"Foo": "Baz"}}], strategy="recurse"
)
assert ret == {"foo": {"Foo": "Baz"}}
def test_renderer():
"""
Test renderer function
"""
with patch.dict(
slsutil.__utils__, {"stringio.is_readable": MagicMock(return_value=False)}
):
ret = slsutil.renderer(string="Hello, {{ name }}.", name="world")
assert ret == "Hello, world."
with pytest.raises(salt.exceptions.SaltInvocationError) as exc:
slsutil.renderer()
assert str(exc.value) == "Must pass path or string."
with pytest.raises(salt.exceptions.SaltInvocationError) as exc:
slsutil.renderer(path="/path/to/file", string="Hello world")
assert str(exc.value) == "Must not pass both path and string."
with patch.dict(
slsutil.__salt__, {"cp.get_url": MagicMock(return_value="/path/to/file")}
):
with patch.dict(
slsutil.__utils__, {"stringio.is_readable": MagicMock(return_value=True)}
):
rendered_file = "Hello, world."
with patch(
"salt.template.compile_template",
MagicMock(return_value=StringIO(rendered_file)),
):
ret = slsutil.renderer(path="/path/to/file")
assert ret == "Hello, world."
def test_serialize():
"""
Test serialize function
"""
ret = slsutil.serialize("json", obj={"foo": "Foo!"})
assert ret == '{"foo": "Foo!"}'
def test_deserialize():
"""
Test serialize function
"""
ret = slsutil.deserialize("json", '{"foo": "Foo!"}')
assert ret == {"foo": "Foo!"}
def dummy_function(args=None, kwargs=None):
return True
def test__set_context():
"""
Test _set_context
"""
with patch.dict(slsutil.__context__, {}):
slsutil._set_context(
["level_one", "level_two", "level_three"], dummy_function, force=True
)
assert slsutil.__context__ == {
"level_one": {"level_two": {"level_three": True}}
}
with patch.dict(slsutil.__context__, {}):
slsutil._set_context(
["level_one", "level_two", "level_three"],
dummy_function,
fun_kwargs={"key_one": "arg_one"},
force=True,
)
assert slsutil.__context__ == {
"level_one": {"level_two": {"level_three": True}}
}
def test__get_serializer_fn():
"""
Test _set_context
"""
# Invalid serializer
with pytest.raises(salt.exceptions.CommandExecutionError) as exc:
slsutil._get_serialize_fn("bad_yaml", "badfunc")
assert str(exc.value) == "Serializer 'bad_yaml' not found."
# Invalid serializer function
with pytest.raises(salt.exceptions.CommandExecutionError) as exc:
slsutil._get_serialize_fn("yaml", "foobar")
assert str(exc.value) == "Serializer 'yaml' does not implement foobar."