switching to using --formatter=json and working on some functional tests using docker containers.

This commit is contained in:
Gareth J. Greenaway 2021-05-25 08:50:22 -07:00 committed by Megan Wilhite
parent abb062199b
commit ce4fe0eb74
3 changed files with 61 additions and 48 deletions

View file

@ -658,13 +658,19 @@ def list_permissions(vhost, runas=None):
if runas is None and not salt.utils.platform.is_windows():
runas = salt.utils.user.get_user()
res = __salt__["cmd.run_all"](
[RABBITMQCTL, "list_permissions", "-q", "-p", vhost],
[RABBITMQCTL, "list_permissions", "--formatter=json", "-p", vhost],
reset_system_locale=False,
runas=runas,
python_shell=False,
)
return _output_to_dict(res)
perms = salt.utils.json.loads(res["stdout"])
perms_dict = {}
for perm in perms:
user = perm["user"]
perms_dict[user] = perm
del perms_dict[user]["user"]
return perms_dict
def list_user_permissions(name, runas=None):
@ -680,18 +686,19 @@ def list_user_permissions(name, runas=None):
if runas is None and not salt.utils.platform.is_windows():
runas = salt.utils.user.get_user()
res = __salt__["cmd.run_all"](
[RABBITMQCTL, "list_user_permissions", name, "-q"],
[RABBITMQCTL, "list_user_permissions", name, "--formatter=json"],
reset_system_locale=False,
runas=runas,
python_shell=False,
)
perms = _output_to_dict(res)
perms = salt.utils.json.loads(res["stdout"])
perms_dict = {}
for perm in perms:
if len(perms[perm]) < 3:
missing = ["" for i in range(0, 3 - len(perms[perm]))]
perms[perm].extend(missing)
return perms
vhost = perm["vhost"]
perms_dict[vhost] = perm
del perms_dict[vhost]["vhost"]
return perms_dict
def set_user_tags(name, tags, runas=None):

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Manage RabbitMQ Users
=====================
@ -22,15 +21,11 @@ Example:
- runas: rabbitmq
"""
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
# Import salt libs
import salt.utils.path
from salt.exceptions import CommandExecutionError
from salt.ext import six
log = logging.getLogger(__name__)
@ -58,16 +53,18 @@ def _check_perms_changes(name, newperms, runas=None, existing=None):
log.error("Error: %s", err)
return False
empty_perms = {"configure": "", "write": "", "read": ""}
perm_need_change = False
for vhost_perms in newperms:
for vhost, perms in six.iteritems(vhost_perms):
for vhost, perms in vhost_perms.items():
if vhost in existing:
new_perms = {"configure": perms[0], "write": perms[1], "read": perms[2]}
existing_vhost = existing[vhost]
if perms != existing_vhost:
if new_perms != existing_vhost:
# This checks for setting permissions to nothing in the state,
# when previous state runs have already set permissions to
# nothing. We don't want to report a change in this case.
if existing_vhost == "" and perms == ["", "", ""]:
if existing_vhost == empty_perms and perms == empty_perms:
continue
perm_need_change = True
else:
@ -109,7 +106,7 @@ def present(name, password=None, force=False, tags=None, perms=(), runas=None):
try:
user = __salt__["rabbitmq.user_exists"](name, runas=runas)
except CommandExecutionError as err:
ret["comment"] = "Error: {0}".format(err)
ret["comment"] = "Error: {}".format(err)
return ret
passwd_reqs_update = False
@ -119,7 +116,7 @@ def present(name, password=None, force=False, tags=None, perms=(), runas=None):
passwd_reqs_update = True
log.debug("RabbitMQ user %s password update required", name)
except CommandExecutionError as err:
ret["comment"] = "Error: {0}".format(err)
ret["comment"] = "Error: {}".format(err)
return ret
if user and not any((force, perms, tags, passwd_reqs_update)):
@ -130,7 +127,7 @@ def present(name, password=None, force=False, tags=None, perms=(), runas=None):
),
name,
)
ret["comment"] = "User '{0}' is already present.".format(name)
ret["comment"] = "User '{}' is already present.".format(name)
ret["result"] = True
return ret
@ -138,14 +135,14 @@ def present(name, password=None, force=False, tags=None, perms=(), runas=None):
ret["changes"].update({"user": {"old": "", "new": name}})
if __opts__["test"]:
ret["result"] = None
ret["comment"] = "User '{0}' is set to be created.".format(name)
ret["comment"] = "User '{}' is set to be created.".format(name)
return ret
log.debug("RabbitMQ user '%s' doesn't exist - Creating.", name)
try:
__salt__["rabbitmq.add_user"](name, password, runas=runas)
except CommandExecutionError as err:
ret["comment"] = "Error: {0}".format(err)
ret["comment"] = "Error: {}".format(err)
return ret
else:
log.debug("RabbitMQ user '%s' exists", name)
@ -157,7 +154,7 @@ def present(name, password=None, force=False, tags=None, perms=(), runas=None):
name, password, runas=runas
)
except CommandExecutionError as err:
ret["comment"] = "Error: {0}".format(err)
ret["comment"] = "Error: {}".format(err)
return ret
ret["changes"].update({"password": {"old": "", "new": "Set password."}})
else:
@ -166,7 +163,7 @@ def present(name, password=None, force=False, tags=None, perms=(), runas=None):
try:
__salt__["rabbitmq.clear_password"](name, runas=runas)
except CommandExecutionError as err:
ret["comment"] = "Error: {0}".format(err)
ret["comment"] = "Error: {}".format(err)
return ret
ret["changes"].update(
{"password": {"old": "Removed password.", "new": ""}}
@ -174,7 +171,7 @@ def present(name, password=None, force=False, tags=None, perms=(), runas=None):
if tags is not None:
current_tags = _get_current_tags(name, runas=runas)
if isinstance(tags, six.string_types):
if isinstance(tags, str):
tags = tags.split()
# Diff the tags sets. Symmetric difference operator ^ will give us
# any element in one set, but not both
@ -183,44 +180,50 @@ def present(name, password=None, force=False, tags=None, perms=(), runas=None):
try:
__salt__["rabbitmq.set_user_tags"](name, tags, runas=runas)
except CommandExecutionError as err:
ret["comment"] = "Error: {0}".format(err)
ret["comment"] = "Error: {}".format(err)
return ret
ret["changes"].update({"tags": {"old": current_tags, "new": tags}})
try:
existing_perms = __salt__["rabbitmq.list_user_permissions"](name, runas=runas)
except CommandExecutionError as err:
ret["comment"] = "Error: {0}".format(err)
ret["comment"] = "Error: {}".format(err)
return ret
if _check_perms_changes(name, perms, runas=runas, existing=existing_perms):
for vhost_perm in perms:
for vhost, perm in six.iteritems(vhost_perm):
for vhost, perm in vhost_perm.items():
if not __opts__["test"]:
try:
__salt__["rabbitmq.set_permissions"](
vhost, name, perm[0], perm[1], perm[2], runas=runas
)
except CommandExecutionError as err:
ret["comment"] = "Error: {0}".format(err)
ret["comment"] = "Error: {}".format(err)
return ret
new_perms = {vhost: perm}
if existing_perms != new_perms:
if ret["changes"].get("perms") is None:
ret["changes"].update({"perms": {"old": {}, "new": {}}})
ret["changes"]["perms"]["old"].update(existing_perms)
new_perms = {
vhost: {"configure": perm[0], "write": perm[1], "read": perm[2]}
}
if vhost in existing_perms:
if existing_perms[vhost] != new_perms[vhost]:
if ret["changes"].get("perms") is None:
ret["changes"].update({"perms": {"old": {}, "new": {}}})
ret["changes"]["perms"]["old"].update(existing_perms[vhost])
ret["changes"]["perms"]["new"].update(new_perms)
else:
ret["changes"].update({"perms": {"new": {}}})
ret["changes"]["perms"]["new"].update(new_perms)
ret["result"] = True
if ret["changes"] == {}:
ret["comment"] = "'{0}' is already in the desired state.".format(name)
ret["comment"] = "'{}' is already in the desired state.".format(name)
return ret
if __opts__["test"]:
ret["result"] = None
ret["comment"] = "Configuration for '{0}' will change.".format(name)
ret["comment"] = "Configuration for '{}' will change.".format(name)
return ret
ret["comment"] = "'{0}' was configured.".format(name)
ret["comment"] = "'{}' was configured.".format(name)
return ret
@ -238,7 +241,7 @@ def absent(name, runas=None):
try:
user_exists = __salt__["rabbitmq.user_exists"](name, runas=runas)
except CommandExecutionError as err:
ret["comment"] = "Error: {0}".format(err)
ret["comment"] = "Error: {}".format(err)
return ret
if user_exists:
@ -246,19 +249,19 @@ def absent(name, runas=None):
try:
__salt__["rabbitmq.delete_user"](name, runas=runas)
except CommandExecutionError as err:
ret["comment"] = "Error: {0}".format(err)
ret["comment"] = "Error: {}".format(err)
return ret
ret["changes"].update({"name": {"old": name, "new": ""}})
else:
ret["result"] = True
ret["comment"] = "The user '{0}' is not present.".format(name)
ret["comment"] = "The user '{}' is not present.".format(name)
return ret
if __opts__["test"] and ret["changes"]:
ret["result"] = None
ret["comment"] = "The user '{0}' will be removed.".format(name)
ret["comment"] = "The user '{}' will be removed.".format(name)
return ret
ret["result"] = True
ret["comment"] = "The user '{0}' was removed.".format(name)
ret["comment"] = "The user '{}' was removed.".format(name)
return ret

View file

@ -3,11 +3,15 @@
"""
import logging
import pytest
import salt.modules.rabbitmq as rabbitmq
from salt.exceptions import CommandExecutionError
from tests.support.mock import MagicMock, patch
log = logging.getLogger(__name__)
@pytest.fixture
def configure_loader_modules():
@ -326,14 +330,13 @@ def test_list_permissions():
mock_run = MagicMock(
return_value={
"retcode": 0,
"stdout": "Listing stuff ...\nsaltstack\tsaltstack\t.*\t1\nguest\t0\tone\n...done",
"stdout": '[{"user":"myuser","configure":"saltstack","write":".*","read":"1"}]',
"stderr": "",
}
)
with patch.dict(rabbitmq.__salt__, {"cmd.run_all": mock_run}):
assert rabbitmq.list_user_permissions("myuser") == {
"saltstack": ["saltstack", ".*", "1"],
"guest": ["0", "one", ""],
assert rabbitmq.list_permissions("saltstack") == {
"myuser": {"configure": "saltstack", "write": ".*", "read": "1"},
}
@ -346,14 +349,14 @@ def test_list_user_permissions():
mock_run = MagicMock(
return_value={
"retcode": 0,
"stdout": "Listing stuff ...\nsaltstack\tsaltstack\t0\t1\nguest\t0\tone\n...done",
"stdout": '[{"vhost":"saltstack","configure":"saltstack","write":"0","read":"1"},{"vhost":"guest","configure":"0","write":"one","read":""}]',
"stderr": "",
}
)
with patch.dict(rabbitmq.__salt__, {"cmd.run_all": mock_run}):
assert rabbitmq.list_user_permissions("myuser") == {
"saltstack": ["saltstack", "0", "1"],
"guest": ["0", "one", ""],
"saltstack": {"configure": "saltstack", "write": "0", "read": "1"},
"guest": {"configure": "0", "write": "one", "read": ""},
}