Move module tests to pytest

This commit is contained in:
krionbsd 2021-11-18 14:40:45 +01:00 committed by Gareth J. Greenaway
parent b961d4f294
commit 08ac1a8613
16 changed files with 915 additions and 965 deletions

View file

@ -0,0 +1,245 @@
"""
Unit tests for salt/modules/salt_version.py
"""
import salt.modules.salt_version as salt_version
import salt.version
from tests.support.mock import MagicMock, patch
def test_mocked_objects():
"""
Test that the mocked objects actually have what we expect.
For example, earlier tests incorrectly mocked the
salt.version.SaltStackVersion.LNAMES dict using upper-case indexes
"""
assert isinstance(salt.version.SaltStackVersion.LNAMES, dict)
sv = salt.version.SaltStackVersion(*salt.version.__version_info__)
for k, v in salt.version.SaltStackVersion.LNAMES.items():
assert k == k.lower()
assert isinstance(v, tuple)
if sv.new_version(major=v[0]):
assert len(v) == 1
else:
assert len(v) == 2
sv = sv.__str__()
assert isinstance(sv, str)
with patch("salt.version.SaltStackVersion.LNAMES", {"neon": (2019, 8)}):
sv = salt.version.SaltStackVersion.from_name("Neon")
assert sv.string == "2019.8.0"
def test_get_release_number_no_codename():
"""
Test that None is returned when the codename isn't found.
"""
assert salt_version.get_release_number("foo") is None
def test_get_release_number_unassigned():
"""
Test that a string is returned when a version is found, but unassigned.
"""
with patch("salt.version.SaltStackVersion.LNAMES", {"foo": (12345, 0)}):
mock_str = "No version assigned."
assert salt_version.get_release_number("foo") == mock_str
def test_get_release_number_success():
"""
Test that a version is returned for a released codename
"""
assert salt_version.get_release_number("Oxygen") == "2018.3"
def test_get_release_number_success_new_version():
"""
Test that a version is returned for new versioning (3000)
"""
assert salt_version.get_release_number("Neon") == "3000"
def test_equal_success():
"""
Test that the current version is equal to the codename
"""
with patch("salt.version.SaltStackVersion", MagicMock(return_value="1900.5.0")):
with patch("salt.version.SaltStackVersion.LNAMES", {"foo": (1900, 5)}):
assert salt_version.equal("foo") is True
def test_equal_success_new_version():
"""
Test that the current version is equal to the codename
while using the new versioning
"""
with patch("salt.version.SaltStackVersion", MagicMock(return_value="3000.1")):
with patch("salt.version.SaltStackVersion.LNAMES", {"foo": (3000,)}):
assert salt_version.equal("foo") is True
def test_equal_older_codename():
"""
Test that when an older codename is passed in, the function returns False.
"""
with patch("salt.version.SaltStackVersion", MagicMock(return_value="2018.3.2")):
with patch(
"salt.version.SaltStackVersion.LNAMES",
{"oxygen": (2018, 3), "nitrogen": (2017, 7)},
):
assert salt_version.equal("Nitrogen") is False
def test_equal_older_codename_new_version():
"""
Test that when an older codename is passed in, the function returns False.
while also testing with the new versioning.
"""
with patch("salt.version.SaltStackVersion", MagicMock(return_value="2018.3.2")):
with patch(
"salt.version.SaltStackVersion.LNAMES",
{"neon": (3000), "nitrogen": (2017, 7)},
):
assert salt_version.equal("Nitrogen") is False
def test_equal_newer_codename():
"""
Test that when a newer codename is passed in, the function returns False
"""
with patch("salt.version.SaltStackVersion", MagicMock(return_value="2018.3.2")):
with patch(
"salt.version.SaltStackVersion.LNAMES",
{"fluorine": (salt.version.MAX_SIZE - 100, 0)},
):
assert salt_version.equal("Fluorine") is False
def test_greater_than_success():
"""
Test that the current version is newer than the codename
"""
with patch(
"salt.modules.salt_version.get_release_number", MagicMock(return_value="2017.7")
):
with patch("salt.version.SaltStackVersion", MagicMock(return_value="2018.3.2")):
assert salt_version.greater_than("Nitrogen") is True
def test_greater_than_success_new_version():
"""
Test that the current version is newer than the codename
"""
with patch(
"salt.modules.salt_version.get_release_number", MagicMock(return_value="2017.7")
):
with patch("salt.version.SaltStackVersion", MagicMock(return_value="3000")):
assert salt_version.greater_than("Nitrogen") is True
def test_greater_than_with_equal_codename():
"""
Test that when an equal codename is passed in, the function returns False.
"""
with patch("salt.version.SaltStackVersion", MagicMock(return_value="2018.3.2")):
with patch("salt.version.SaltStackVersion.LNAMES", {"oxygen": (2018, 3)}):
assert salt_version.greater_than("Oxygen") is False
def test_greater_than_with_newer_codename():
"""
Test that when a newer codename is passed in, the function returns False.
"""
with patch("salt.version.SaltStackVersion", MagicMock(return_value="2018.3.2")):
with patch(
"salt.version.SaltStackVersion.LNAMES",
{"fluorine": (2019, 2), "oxygen": (2018, 3)},
):
assert salt_version.greater_than("Fluorine") is False
def test_greater_than_unassigned():
"""
Test that the unassigned codename is greater than the current version
"""
with patch("salt.version.SaltStackVersion", MagicMock(return_value="2018.3.2")):
with patch(
"salt.modules.salt_version.get_release_number",
MagicMock(return_value="No version assigned."),
):
assert salt_version.greater_than("Fluorine") is False
def test_less_than_success():
"""
Test that when a newer codename is passed in, the function returns True.
"""
with patch("salt.version.SaltStackVersion", MagicMock(return_value="2018.3.2")):
with patch(
"salt.modules.salt_version.get_release_number",
MagicMock(return_value="2019.2"),
):
assert salt_version.less_than("Fluorine") is True
def test_less_than_success_new_version():
"""
Test that when a newer codename is passed in, the function returns True
using new version
"""
with patch("salt.version.SaltStackVersion", MagicMock(return_value="2018.3.2")):
with patch(
"salt.modules.salt_version.get_release_number",
MagicMock(return_value="3000"),
):
assert salt_version.less_than("Fluorine") is True
def test_less_than_with_equal_codename():
"""
Test that when an equal codename is passed in, the function returns False.
"""
with patch("salt.version.SaltStackVersion", MagicMock(return_value="2018.3.2")):
with patch("salt.version.SaltStackVersion.LNAMES", {"oxygen": (2018, 3)}):
assert salt_version.less_than("Oxygen") is False
def test_less_than_with_older_codename():
"""
Test that the current version is less than the codename.
"""
with patch("salt.version.SaltStackVersion", MagicMock(return_value="2018.3.2")):
with patch(
"salt.modules.salt_version.get_release_number",
MagicMock(return_value="2017.7"),
):
assert salt_version.less_than("Nitrogen") is False
def test_less_than_with_unassigned_codename():
"""
Test that when an unassigned codename greater than the current version.
"""
with patch("salt.version.SaltStackVersion", MagicMock(return_value="2018.3.2")):
with patch(
"salt.modules.salt_version.get_release_number",
MagicMock(return_value="No version assigned."),
):
assert salt_version.less_than("Fluorine") is True
def test_check_release_cmp_no_codename():
"""
Test that None is returned when the codename isn't found.
"""
assert salt_version._check_release_cmp("foo") is None
def test_check_release_cmp_success():
"""
Test that an int is returned from the version compare
"""
assert isinstance(salt_version._check_release_cmp("Oxygen"), int)

View file

@ -0,0 +1,27 @@
"""
:codeauthor: Rahul Handay <rahulha@saltstack.com>
"""
import pytest
import salt.modules.saltcloudmod as saltcloudmod
import salt.utils.json
from tests.support.mock import MagicMock, patch
@pytest.fixture
def configure_loader_modules():
return {saltcloudmod: {}}
def test_create():
"""
Test if create the named vm
"""
mock = MagicMock(return_value="""{"foo": "bar"}""")
mock_json_loads = MagicMock(side_effect=ValueError())
with patch.dict(saltcloudmod.__salt__, {"cmd.run_stdout": mock}):
assert saltcloudmod.create("webserver", "rackspace_centos_512")
with patch.object(salt.utils.json, "loads", mock_json_loads):
assert saltcloudmod.create("webserver", "rackspace_centos_512") == {}

View file

@ -0,0 +1,83 @@
import pytest
import salt.modules.saltutil as saltutil
from salt.client import LocalClient
from tests.support.mock import create_autospec
from tests.support.mock import sentinel as s
@pytest.fixture
def configure_loader_modules():
return {saltutil: {}}
def test_exec_kwargs():
_cmd_expected_kwargs = {
"tgt": s.tgt,
"fun": s.fun,
"arg": s.arg,
"timeout": s.timeout,
"tgt_type": s.tgt_type,
"ret": s.ret,
"kwarg": s.kwarg,
}
client = create_autospec(LocalClient)
saltutil._exec(client, **_cmd_expected_kwargs)
client.cmd_iter.assert_called_with(**_cmd_expected_kwargs)
saltutil._exec(
client,
s.tgt,
s.fun,
s.arg,
s.timeout,
s.tgt_type,
s.ret,
s.kwarg,
**{"batch": s.batch}
)
client.cmd_batch.assert_called_with(batch=s.batch, **_cmd_expected_kwargs)
saltutil._exec(
client,
s.tgt,
s.fun,
s.arg,
s.timeout,
s.tgt_type,
s.ret,
s.kwarg,
**{"subset": s.subset}
)
client.cmd_subset.assert_called_with(
subset=s.subset, cli=True, **_cmd_expected_kwargs
)
saltutil._exec(
client,
s.tgt,
s.fun,
s.arg,
s.timeout,
s.tgt_type,
s.ret,
s.kwarg,
**{"subset": s.subset, "cli": s.cli}
)
client.cmd_subset.assert_called_with(
subset=s.subset, cli=s.cli, **_cmd_expected_kwargs
)
# cmd_batch doesn't know what to do with 'subset', don't pass it along.
saltutil._exec(
client,
s.tgt,
s.fun,
s.arg,
s.timeout,
s.tgt_type,
s.ret,
s.kwarg,
**{"subset": s.subset, "batch": s.batch}
)
client.cmd_batch.assert_called_with(batch=s.batch, **_cmd_expected_kwargs)

View file

@ -0,0 +1,84 @@
"""
:codeauthor: Jayesh Kariya <jayeshk@saltstack.com>
"""
import copy
import os
import pytest
import salt.modules.scsi as scsi
import salt.utils.path
from tests.support.mock import MagicMock, patch
@pytest.fixture
def configure_loader_modules():
return {scsi: {}}
def test_ls_():
"""
Test for list SCSI devices, with details
"""
lsscsi = {
"stdout": "[0:0:0:0] disk HP LOGICAL VOLUME 6.68 /dev/sda [8:0]",
"stderr": "",
"retcode": 0,
}
lsscsi_size = {
"stdout": "[0:0:0:0] disk HP LOGICAL VOLUME 6.68 /dev/sda [8:0] 1.20TB",
"stderr": "",
"retcode": 0,
}
result = {
"[0:0:0:0]": {
"major": "8",
"lun": "0:0:0:0",
"device": "/dev/sda",
"model": "LOGICAL VOLUME 6.68",
"minor": "0",
"size": None,
}
}
result_size = copy.deepcopy(result)
result_size["[0:0:0:0]"]["size"] = "1.20TB"
mock = MagicMock(return_value="/usr/bin/lsscsi")
with patch.object(salt.utils.path, "which", mock):
# get_size = True
cmd_mock = MagicMock(return_value=lsscsi_size)
with patch.dict(scsi.__salt__, {"cmd.run_all": cmd_mock}):
assert scsi.ls_() == result_size
with patch.dict(lsscsi_size, {"retcode": 1, "stderr": "An error occurred"}):
assert scsi.ls_() == "An error occurred"
with patch.dict(
lsscsi_size,
{"retcode": 1, "stderr": "lsscsi: invalid option -- 's'\nUsage:"},
):
assert (
scsi.ls_() == "lsscsi: invalid option -- 's' - try get_size=False"
)
# get_size = False
cmd_mock = MagicMock(return_value=lsscsi)
with patch.dict(scsi.__salt__, {"cmd.run_all": cmd_mock}):
assert scsi.ls_(get_size=False) == result
mock = MagicMock(return_value=None)
with patch.object(salt.utils.path, "which", mock):
assert scsi.ls_() == "scsi.ls not available - lsscsi command not found"
def test_rescan_all():
"""
Test for list scsi devices
"""
mock = MagicMock(side_effect=[False, True])
with patch.object(os.path, "isdir", mock):
assert scsi.rescan_all("host") == "Host host does not exist"
with patch.dict(scsi.__salt__, {"cmd.run": MagicMock(return_value="A")}):
assert scsi.rescan_all("host") == ["A"]

View file

@ -0,0 +1,60 @@
"""
:codeauthor: Jayesh Kariya <jayeshk@saltstack.com>
"""
import pytest
import salt.modules.sdb as sdb
from salt.exceptions import SaltInvocationError
@pytest.fixture
def configure_loader_modules():
return {sdb: {}}
def test_get():
"""
Test if it gets a value from a db, using a uri in the form of
sdb://<profile>/<key>
"""
assert sdb.get("sdb://salt/foo") == "sdb://salt/foo"
def test_get_strict_no_sdb_in_uri():
"""
Test if SaltInvocationError exception will be raised if we
don't start uri with sdb://
"""
msg = 'SDB uri must start with "sdb://"'
with pytest.raises(SaltInvocationError, match=msg) as cm:
sdb.get("://salt/foo", strict=True)
def test_get_strict_no_profile():
"""
Test if SaltInvocationError exception will be raised if we
don't have a valid profile in the uri
"""
msg = "SDB uri must have a profile name as a first part of the uri before the /"
with pytest.raises(SaltInvocationError, match=msg) as cm:
sdb.get("sdb://salt", strict=True)
def test_get_strict_no_profile_in_config():
"""
Test if SaltInvocationError exception will be raised if we
don't have expected profile in the minion config
"""
msg = 'SDB profile "salt" wasnt found in the minion configuration'
with pytest.raises(SaltInvocationError, match=msg) as cm:
sdb.get("sdb://salt/foo", strict=True)
def test_set():
"""
Test if it sets a value from a db, using a uri in the form of
sdb://<profile>/<key>
"""
assert not sdb.set_("sdb://mymemcached/foo", "bar")

View file

@ -0,0 +1,100 @@
"""
:codeauthor: Jayesh Kariya <jayeshk@saltstack.com>
"""
import os
import shutil
import uuid
import pytest
import salt.modules.seed as seed
import salt.utils.files
import salt.utils.odict
from tests.support.mock import MagicMock, patch
@pytest.fixture
def configure_loader_modules():
return {seed: {}}
@pytest.mark.slow_test
def test_mkconfig_odict():
with patch.dict(seed.__opts__, {"master": "foo"}):
ddd = salt.utils.odict.OrderedDict()
ddd["b"] = "b"
ddd["a"] = "b"
data = seed.mkconfig(ddd, approve_key=False)
with salt.utils.files.fopen(data["config"]) as fic:
fdata = fic.read()
assert fdata == "b: b\na: b\nmaster: foo\n"
def test_prep_bootstrap():
"""
Test to update and get the random script to a random place
"""
with patch.dict(
seed.__salt__,
{
"config.gather_bootstrap_script": MagicMock(
return_value=os.path.join("BS_PATH", "BS")
)
},
), patch.object(uuid, "uuid4", return_value="UUID"), patch.object(
os.path, "exists", return_value=True
), patch.object(
os, "chmod", return_value=None
), patch.object(
shutil, "copy", return_value=None
):
expect = (
os.path.join("MPT", "tmp", "UUID", "BS"),
os.sep + os.path.join("tmp", "UUID"),
)
assert seed.prep_bootstrap("MPT") == expect
expect = (
os.sep + os.path.join("MPT", "tmp", "UUID", "BS"),
os.sep + os.path.join("tmp", "UUID"),
)
assert seed.prep_bootstrap(os.sep + "MPT") == expect
def test_apply_():
"""
Test to seed a location (disk image, directory, or block device)
with the minion config, approve the minion's key, and/or install
salt-minion.
"""
mock = MagicMock(
side_effect=[
False,
{"type": "type", "target": "target"},
{"type": "type", "target": "target"},
{"type": "type", "target": "target"},
]
)
with patch.dict(seed.__salt__, {"file.stats": mock}):
assert seed.apply_("path") == "path does not exist"
with patch.object(seed, "_mount", return_value=False):
assert seed.apply_("path") == "target could not be mounted"
with patch.object(seed, "_mount", return_value="/mountpoint"):
with patch.object(os.path, "join", return_value="A"):
with patch.object(os, "makedirs", MagicMock(side_effect=OSError("f"))):
with patch.object(os.path, "isdir", return_value=False):
pytest.raises(OSError, seed.apply_, "p")
with patch.object(os, "makedirs", MagicMock()):
with patch.object(seed, "mkconfig", return_value="A"):
with patch.object(seed, "_check_install", return_value=False):
with patch.object(
seed, "_umount", return_value=None
) as umount_mock:
assert not seed.apply_("path", install=False)
umount_mock.assert_called_once_with(
"/mountpoint", "target", "type"
)

View file

@ -0,0 +1,294 @@
import pytest
import salt.modules.selinux as selinux
from salt.exceptions import SaltInvocationError
from tests.support.mock import MagicMock, patch
@pytest.fixture
def configure_loader_modules():
return {selinux: {}}
def test_fcontext_get_policy_parsing():
"""
Test to verify that the parsing of the semanage output into fields is
correct. Added with #45784.
"""
cases = [
{
"semanage_out": (
"/var/www(/.*)? all files "
" system_u:object_r:httpd_sys_content_t:s0"
),
"name": "/var/www(/.*)?",
"filetype": "all files",
"sel_user": "system_u",
"sel_role": "object_r",
"sel_type": "httpd_sys_content_t",
"sel_level": "s0",
},
{
"semanage_out": (
"/var/www(/.*)? all files "
" system_u:object_r:httpd_sys_content_t:s0"
),
"name": "/var/www(/.*)?",
"filetype": "all files",
"sel_user": "system_u",
"sel_role": "object_r",
"sel_type": "httpd_sys_content_t",
"sel_level": "s0",
},
{
"semanage_out": (
"/var/lib/dhcp3? directory "
" system_u:object_r:dhcp_state_t:s0"
),
"name": "/var/lib/dhcp3?",
"filetype": "directory",
"sel_user": "system_u",
"sel_role": "object_r",
"sel_type": "dhcp_state_t",
"sel_level": "s0",
},
{
"semanage_out": (
"/var/lib/dhcp3? directory "
" system_u:object_r:dhcp_state_t:s0"
),
"name": "/var/lib/dhcp3?",
"filetype": "directory",
"sel_user": "system_u",
"sel_role": "object_r",
"sel_type": "dhcp_state_t",
"sel_level": "s0",
},
{
"semanage_out": (
"/var/lib/dhcp3? directory "
" system_u:object_r:dhcp_state_t:s0"
),
"name": "/var/lib/dhcp3?",
"filetype": "directory",
"sel_user": "system_u",
"sel_role": "object_r",
"sel_type": "dhcp_state_t",
"sel_level": "s0",
},
]
for case in cases:
with patch.dict(
selinux.__salt__,
{"cmd.shell": MagicMock(return_value=case["semanage_out"])},
):
ret = selinux.fcontext_get_policy(case["name"])
assert ret["filespec"] == case["name"]
assert ret["filetype"] == case["filetype"]
assert ret["sel_user"] == case["sel_user"]
assert ret["sel_role"] == case["sel_role"]
assert ret["sel_type"] == case["sel_type"]
assert ret["sel_level"] == case["sel_level"]
@pytest.mark.parametrize(
"name, protocol, port, expected",
(
("tcp/80", None, None, ("tcp", "80")),
("udp/53", None, None, ("udp", "53")),
("tcp_test_dns", "tcp", "53", ("tcp", "53")),
("udp_test/dns", "udp", "53", ("udp", "53")),
),
)
def test_parse_protocol_port_positive(name, protocol, port, expected):
"""
Test to verify positive parsing name, protocol and port combinations
"""
ret = selinux._parse_protocol_port(name, protocol, port)
assert ret == expected
@pytest.mark.parametrize(
"name, protocol, port",
(
("invalid_name_no_args", None, None),
("invalid_proto/80", "nottcp", "80"),
("invalid_port", "tcp", "notaport"),
("missing_proto", None, "80"),
("missing_port", "udp", None),
),
)
def test_parse_protocol_port_negative(name, protocol, port):
"""
Test to verify negative parsing of name, protocol and port combinations
"""
pytest.raises(
SaltInvocationError,
selinux._parse_protocol_port,
name,
protocol,
port,
)
def test_port_get_policy_parsing():
"""
Test to verify that the parsing of the semanage port output into fields is correct.
"""
cases = [
{
"semanage_out": "cma_port_t tcp 1050",
"name": "tcp/1050",
"expected": {
"sel_type": "cma_port_t",
"protocol": "tcp",
"port": "1050",
},
},
{
"semanage_out": (
"cluster_port_t tcp 5149, 40040, 50006-50008"
),
"name": "tcp/40040",
"expected": {
"sel_type": "cluster_port_t",
"protocol": "tcp",
"port": "5149, 40040, 50006-50008",
},
},
{
"semanage_out": (
"http_port_t tcp 9008, 8010, 9002-9003, 80,"
" 81, 443, 488, 8008, 8009, 8443, 9000"
),
"name": "tcp/9000",
"expected": {
"sel_type": "http_port_t",
"protocol": "tcp",
"port": (
"9008, 8010, 9002-9003, 80, 81, 443, 488, 8008, 8009, 8443," " 9000"
),
},
},
{
"semanage_out": (
"vnc_port_t tcp 5985-5999, 5900-5983"
),
"name": "tcp/5985-5999",
"expected": {
"sel_type": "vnc_port_t",
"protocol": "tcp",
"port": "5985-5999, 5900-5983",
},
},
{
"semanage_out": (
"zebra_port_t tcp 2606, 2608-2609, 2600-2604"
),
"name": "tcp/2608-2609",
"expected": {
"sel_type": "zebra_port_t",
"protocol": "tcp",
"port": "2606, 2608-2609, 2600-2604",
},
},
{
"semanage_out": (
"radius_port_t udp 1645, 1812, 18120-18121"
),
"name": "tcp/18120-18121",
"expected": {
"sel_type": "radius_port_t",
"protocol": "udp",
"port": "1645, 1812, 18120-18121",
},
},
]
for case in cases:
with patch.dict(
selinux.__salt__,
{"cmd.shell": MagicMock(return_value=case["semanage_out"])},
):
ret = selinux.port_get_policy(case["name"])
assert ret == case["expected"]
def test_fcontext_policy_parsing_new():
"""
Test parsing the stdout response of restorecon used in fcontext_policy_applied, new style.
"""
restorecon_ret = (
"Would relabel /foo/bar from some_u:some_r:some_t:s0 to"
" other_u:other_r:other_t:s0"
)
with patch.object(
selinux, "fcontext_policy_is_applied", return_value=restorecon_ret
), patch.dict(
selinux.__salt__, {"cmd.run_all": MagicMock(return_value={"retcode": 0})}
):
assert selinux.fcontext_apply_policy("/foo/bar") == {
"changes": {
"/foo/bar": {
"old": {
"sel_role": "some_r",
"sel_type": "some_t",
"sel_user": "some_u",
},
"new": {
"sel_role": "other_r",
"sel_type": "other_t",
"sel_user": "other_u",
},
},
},
"retcode": 0,
}
def test_fcontext_policy_parsing_old():
"""
Test parsing the stdout response of restorecon used in fcontext_policy_applied, old style.
"""
restorecon_ret = (
"restorecon reset /foo/bar context"
" some_u:some_r:some_t:s0->other_u:other_r:other_t:s0"
)
with patch.object(
selinux, "fcontext_policy_is_applied", return_value=restorecon_ret
), patch.dict(
selinux.__salt__, {"cmd.run_all": MagicMock(return_value={"retcode": 0})}
):
assert selinux.fcontext_apply_policy("/foo/bar") == {
"changes": {
"/foo/bar": {
"old": {
"sel_role": "some_r",
"sel_type": "some_t",
"sel_user": "some_u",
},
"new": {
"sel_role": "other_r",
"sel_type": "other_t",
"sel_user": "other_u",
},
},
},
"retcode": 0,
}
def test_fcontext_policy_parsing_fail():
"""
Test failure response for invalid restorecon data.
"""
restorecon_ret = "And now for something completely different."
with patch.object(
selinux, "fcontext_policy_is_applied", return_value=restorecon_ret
), patch.dict(
selinux.__salt__, {"cmd.run_all": MagicMock(return_value={"retcode": 0})}
):
assert selinux.fcontext_apply_policy("/foo/bar") == {
"retcode": 1,
"error": "Unrecognized response from restorecon command.",
}

View file

@ -0,0 +1,22 @@
"""
:codeauthor: Jayesh Kariya <jayeshk@saltstack.com>
"""
import pytest
import salt.modules.sensors as sensors
from tests.support.mock import MagicMock, patch
@pytest.fixture
def configure_loader_modules():
return {sensors: {}}
def test_sense():
"""
Test to gather lm-sensors data from a given chip
"""
with patch.dict(
sensors.__salt__, {"cmd.run": MagicMock(return_value="A:a B:b C:c D:d")}
):
assert sensors.sense("chip") == {"A": "a B"}

View file

@ -1,237 +0,0 @@
"""
Unit tests for salt/modules/salt_version.py
"""
import salt.modules.salt_version as salt_version
import salt.version
from tests.support.mock import MagicMock, patch
from tests.support.unit import TestCase
class SaltVersionTestCase(TestCase):
"""
Test cases for salt.modules.salt_version
"""
def test_mocked_objects(self):
"""
Test that the mocked objects actually have what we expect.
For example, earlier tests incorrectly mocked the
salt.version.SaltStackVersion.LNAMES dict using upper-case indexes
"""
assert isinstance(salt.version.SaltStackVersion.LNAMES, dict)
sv = salt.version.SaltStackVersion(*salt.version.__version_info__)
for k, v in salt.version.SaltStackVersion.LNAMES.items():
assert k == k.lower()
assert isinstance(v, tuple)
if sv.new_version(major=v[0]):
assert len(v) == 1
else:
assert len(v) == 2
sv = sv.__str__()
assert isinstance(sv, str)
with patch("salt.version.SaltStackVersion.LNAMES", {"neon": (2019, 8)}):
sv = salt.version.SaltStackVersion.from_name("Neon")
self.assertEqual(sv.string, "2019.8.0")
# get_release_number tests: 3
def test_get_release_number_no_codename(self):
"""
Test that None is returned when the codename isn't found.
"""
assert salt_version.get_release_number("foo") is None
@patch("salt.version.SaltStackVersion.LNAMES", {"foo": (12345, 0)})
def test_get_release_number_unassigned(self):
"""
Test that a string is returned when a version is found, but unassigned.
"""
mock_str = "No version assigned."
assert salt_version.get_release_number("foo") == mock_str
def test_get_release_number_success(self):
"""
Test that a version is returned for a released codename
"""
assert salt_version.get_release_number("Oxygen") == "2018.3"
def test_get_release_number_success_new_version(self):
"""
Test that a version is returned for new versioning (3000)
"""
assert salt_version.get_release_number("Neon") == "3000"
# equal tests: 3
@patch("salt.version.SaltStackVersion.LNAMES", {"foo": (1900, 5)})
@patch("salt.version.SaltStackVersion", MagicMock(return_value="1900.5.0"))
def test_equal_success(self):
"""
Test that the current version is equal to the codename
"""
assert salt_version.equal("foo") is True
@patch("salt.version.SaltStackVersion.LNAMES", {"foo": (3000,)})
@patch("salt.version.SaltStackVersion", MagicMock(return_value="3000.1"))
def test_equal_success_new_version(self):
"""
Test that the current version is equal to the codename
while using the new versioning
"""
assert salt_version.equal("foo") is True
@patch(
"salt.version.SaltStackVersion.LNAMES",
{"oxygen": (2018, 3), "nitrogen": (2017, 7)},
)
@patch("salt.version.SaltStackVersion", MagicMock(return_value="2018.3.2"))
def test_equal_older_codename(self):
"""
Test that when an older codename is passed in, the function returns False.
"""
assert salt_version.equal("Nitrogen") is False
@patch(
"salt.version.SaltStackVersion.LNAMES", {"neon": (3000), "nitrogen": (2017, 7)}
)
@patch("salt.version.SaltStackVersion", MagicMock(return_value="2018.3.2"))
def test_equal_older_codename_new_version(self):
"""
Test that when an older codename is passed in, the function returns False.
while also testing with the new versioning.
"""
assert salt_version.equal("Nitrogen") is False
@patch(
"salt.version.SaltStackVersion.LNAMES",
{"fluorine": (salt.version.MAX_SIZE - 100, 0)},
)
@patch("salt.version.SaltStackVersion", MagicMock(return_value="2018.3.2"))
def test_equal_newer_codename(self):
"""
Test that when a newer codename is passed in, the function returns False
"""
assert salt_version.equal("Fluorine") is False
# greater_than tests: 4
@patch(
"salt.modules.salt_version.get_release_number", MagicMock(return_value="2017.7")
)
@patch("salt.version.SaltStackVersion", MagicMock(return_value="2018.3.2"))
def test_greater_than_success(self):
"""
Test that the current version is newer than the codename
"""
assert salt_version.greater_than("Nitrogen") is True
@patch(
"salt.modules.salt_version.get_release_number", MagicMock(return_value="2017.7")
)
@patch("salt.version.SaltStackVersion", MagicMock(return_value="3000"))
def test_greater_than_success_new_version(self):
"""
Test that the current version is newer than the codename
"""
assert salt_version.greater_than("Nitrogen") is True
@patch("salt.version.SaltStackVersion.LNAMES", {"oxygen": (2018, 3)})
@patch("salt.version.SaltStackVersion", MagicMock(return_value="2018.3.2"))
def test_greater_than_with_equal_codename(self):
"""
Test that when an equal codename is passed in, the function returns False.
"""
assert salt_version.greater_than("Oxygen") is False
@patch(
"salt.version.SaltStackVersion.LNAMES",
{"fluorine": (2019, 2), "oxygen": (2018, 3)},
)
@patch("salt.version.SaltStackVersion", MagicMock(return_value="2018.3.2"))
def test_greater_than_with_newer_codename(self):
"""
Test that when a newer codename is passed in, the function returns False.
"""
assert salt_version.greater_than("Fluorine") is False
@patch(
"salt.modules.salt_version.get_release_number",
MagicMock(return_value="No version assigned."),
)
@patch("salt.version.SaltStackVersion", MagicMock(return_value="2018.3.2"))
def test_greater_than_unassigned(self):
"""
Test that the unassigned codename is greater than the current version
"""
assert salt_version.greater_than("Fluorine") is False
# less_than tests: 4
@patch(
"salt.modules.salt_version.get_release_number", MagicMock(return_value="2019.2")
)
@patch("salt.version.SaltStackVersion", MagicMock(return_value="2018.3.2"))
def test_less_than_success(self):
"""
Test that when a newer codename is passed in, the function returns True.
"""
assert salt_version.less_than("Fluorine") is True
@patch(
"salt.modules.salt_version.get_release_number", MagicMock(return_value="3000")
)
@patch("salt.version.SaltStackVersion", MagicMock(return_value="2018.3.2"))
def test_less_than_success_new_version(self):
"""
Test that when a newer codename is passed in, the function returns True
using new version
"""
assert salt_version.less_than("Fluorine") is True
@patch("salt.version.SaltStackVersion", MagicMock(return_value="2018.3.2"))
@patch("salt.version.SaltStackVersion.LNAMES", {"oxygen": (2018, 3)})
def test_less_than_with_equal_codename(self):
"""
Test that when an equal codename is passed in, the function returns False.
"""
assert salt_version.less_than("Oxygen") is False
@patch(
"salt.modules.salt_version.get_release_number", MagicMock(return_value="2017.7")
)
@patch("salt.version.SaltStackVersion", MagicMock(return_value="2018.3.2"))
def test_less_than_with_older_codename(self):
"""
Test that the current version is less than the codename.
"""
assert salt_version.less_than("Nitrogen") is False
@patch(
"salt.modules.salt_version.get_release_number",
MagicMock(return_value="No version assigned."),
)
@patch("salt.version.SaltStackVersion", MagicMock(return_value="2018.3.2"))
def test_less_than_with_unassigned_codename(self):
"""
Test that when an unassigned codename greater than the current version.
"""
assert salt_version.less_than("Fluorine") is True
# _check_release_cmp tests: 2
def test_check_release_cmp_no_codename(self):
"""
Test that None is returned when the codename isn't found.
"""
assert salt_version._check_release_cmp("foo") is None
def test_check_release_cmp_success(self):
"""
Test that an int is returned from the version compare
"""
assert isinstance(salt_version._check_release_cmp("Oxygen"), int)

View file

@ -1,35 +0,0 @@
"""
:codeauthor: Rahul Handay <rahulha@saltstack.com>
"""
import salt.modules.saltcloudmod as saltcloudmod
import salt.utils.json
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.mock import MagicMock, patch
from tests.support.unit import TestCase
class SaltcloudmodTestCase(TestCase, LoaderModuleMockMixin):
"""
Test cases for salt.modules.saltcloudmod
"""
def setup_loader_modules(self):
return {saltcloudmod: {}}
def setUp(self):
self.mock_json_loads = MagicMock(side_effect=ValueError())
def test_create(self):
"""
Test if create the named vm
"""
mock = MagicMock(return_value="""{"foo": "bar"}""")
with patch.dict(saltcloudmod.__salt__, {"cmd.run_stdout": mock}):
self.assertTrue(saltcloudmod.create("webserver", "rackspace_centos_512"))
with patch.object(salt.utils.json, "loads", self.mock_json_loads):
self.assertDictEqual(
saltcloudmod.create("webserver", "rackspace_centos_512"), {}
)

View file

@ -1,83 +0,0 @@
import salt.modules.saltutil as saltutil
from salt.client import LocalClient
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.mock import create_autospec
from tests.support.mock import sentinel as s
from tests.support.unit import TestCase
class ScheduleTestCase(TestCase, LoaderModuleMockMixin):
def setup_loader_modules(self):
return {saltutil: {}}
def test_exec_kwargs(self):
_cmd_expected_kwargs = {
"tgt": s.tgt,
"fun": s.fun,
"arg": s.arg,
"timeout": s.timeout,
"tgt_type": s.tgt_type,
"ret": s.ret,
"kwarg": s.kwarg,
}
client = create_autospec(LocalClient)
saltutil._exec(client, **_cmd_expected_kwargs)
client.cmd_iter.assert_called_with(**_cmd_expected_kwargs)
saltutil._exec(
client,
s.tgt,
s.fun,
s.arg,
s.timeout,
s.tgt_type,
s.ret,
s.kwarg,
**{"batch": s.batch}
)
client.cmd_batch.assert_called_with(batch=s.batch, **_cmd_expected_kwargs)
saltutil._exec(
client,
s.tgt,
s.fun,
s.arg,
s.timeout,
s.tgt_type,
s.ret,
s.kwarg,
**{"subset": s.subset}
)
client.cmd_subset.assert_called_with(
subset=s.subset, cli=True, **_cmd_expected_kwargs
)
saltutil._exec(
client,
s.tgt,
s.fun,
s.arg,
s.timeout,
s.tgt_type,
s.ret,
s.kwarg,
**{"subset": s.subset, "cli": s.cli}
)
client.cmd_subset.assert_called_with(
subset=s.subset, cli=s.cli, **_cmd_expected_kwargs
)
# cmd_batch doesn't know what to do with 'subset', don't pass it along.
saltutil._exec(
client,
s.tgt,
s.fun,
s.arg,
s.timeout,
s.tgt_type,
s.ret,
s.kwarg,
**{"subset": s.subset, "batch": s.batch}
)
client.cmd_batch.assert_called_with(batch=s.batch, **_cmd_expected_kwargs)

View file

@ -1,91 +0,0 @@
"""
:codeauthor: Jayesh Kariya <jayeshk@saltstack.com>
"""
import copy
import os
import salt.modules.scsi as scsi
import salt.utils.path
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.mock import MagicMock, patch
from tests.support.unit import TestCase
class ScsiTestCase(TestCase, LoaderModuleMockMixin):
"""
Test cases for salt.modules.scsi
"""
def setup_loader_modules(self):
return {scsi: {}}
def test_ls_(self):
"""
Test for list SCSI devices, with details
"""
lsscsi = {
"stdout": "[0:0:0:0] disk HP LOGICAL VOLUME 6.68 /dev/sda [8:0]",
"stderr": "",
"retcode": 0,
}
lsscsi_size = {
"stdout": "[0:0:0:0] disk HP LOGICAL VOLUME 6.68 /dev/sda [8:0] 1.20TB",
"stderr": "",
"retcode": 0,
}
result = {
"[0:0:0:0]": {
"major": "8",
"lun": "0:0:0:0",
"device": "/dev/sda",
"model": "LOGICAL VOLUME 6.68",
"minor": "0",
"size": None,
}
}
result_size = copy.deepcopy(result)
result_size["[0:0:0:0]"]["size"] = "1.20TB"
mock = MagicMock(return_value="/usr/bin/lsscsi")
with patch.object(salt.utils.path, "which", mock):
# get_size = True
cmd_mock = MagicMock(return_value=lsscsi_size)
with patch.dict(scsi.__salt__, {"cmd.run_all": cmd_mock}):
self.assertDictEqual(scsi.ls_(), result_size)
with patch.dict(
lsscsi_size, {"retcode": 1, "stderr": "An error occurred"}
):
self.assertEqual(scsi.ls_(), "An error occurred")
with patch.dict(
lsscsi_size,
{"retcode": 1, "stderr": "lsscsi: invalid option -- 's'\nUsage:"},
):
self.assertEqual(
scsi.ls_(), "lsscsi: invalid option -- 's' - try get_size=False"
)
# get_size = False
cmd_mock = MagicMock(return_value=lsscsi)
with patch.dict(scsi.__salt__, {"cmd.run_all": cmd_mock}):
self.assertDictEqual(scsi.ls_(get_size=False), result)
mock = MagicMock(return_value=None)
with patch.object(salt.utils.path, "which", mock):
self.assertEqual(
scsi.ls_(), "scsi.ls not available - lsscsi command not found"
)
def test_rescan_all(self):
"""
Test for list scsi devices
"""
mock = MagicMock(side_effect=[False, True])
with patch.object(os.path, "isdir", mock):
self.assertEqual(scsi.rescan_all("host"), "Host host does not exist")
with patch.dict(scsi.__salt__, {"cmd.run": MagicMock(return_value="A")}):
self.assertListEqual(scsi.rescan_all("host"), ["A"])

View file

@ -1,64 +0,0 @@
"""
:codeauthor: Jayesh Kariya <jayeshk@saltstack.com>
"""
import salt.modules.sdb as sdb
from salt.exceptions import SaltInvocationError
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.unit import TestCase
class SdbTestCase(TestCase, LoaderModuleMockMixin):
"""
Test cases for salt.modules.sdb
"""
def setup_loader_modules(self):
return {sdb: {}}
# 'get' function tests: 4
def test_get(self):
"""
Test if it gets a value from a db, using a uri in the form of
sdb://<profile>/<key>
"""
self.assertEqual(sdb.get("sdb://salt/foo"), "sdb://salt/foo")
def test_get_strict_no_sdb_in_uri(self):
"""
Test if SaltInvocationError exception will be raised if we
don't start uri with sdb://
"""
msg = 'SDB uri must start with "sdb://"'
with self.assertRaisesRegex(SaltInvocationError, msg) as cm:
sdb.get("://salt/foo", strict=True)
def test_get_strict_no_profile(self):
"""
Test if SaltInvocationError exception will be raised if we
don't have a valid profile in the uri
"""
msg = "SDB uri must have a profile name as a first part of the uri before the /"
with self.assertRaisesRegex(SaltInvocationError, msg) as cm:
sdb.get("sdb://salt", strict=True)
def test_get_strict_no_profile_in_config(self):
"""
Test if SaltInvocationError exception will be raised if we
don't have expected profile in the minion config
"""
msg = 'SDB profile "salt" wasnt found in the minion configuration'
with self.assertRaisesRegex(SaltInvocationError, msg) as cm:
sdb.get("sdb://salt/foo", strict=True)
# 'set_' function tests: 1
def test_set(self):
"""
Test if it sets a value from a db, using a uri in the form of
sdb://<profile>/<key>
"""
self.assertFalse(sdb.set_("sdb://mymemcached/foo", "bar"))

View file

@ -1,107 +0,0 @@
"""
:codeauthor: Jayesh Kariya <jayeshk@saltstack.com>
"""
import os
import shutil
import uuid
import pytest
import salt.modules.seed as seed
import salt.utils.files
import salt.utils.odict
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.mock import MagicMock, patch
from tests.support.unit import TestCase
class SeedTestCase(TestCase, LoaderModuleMockMixin):
"""
Test cases for salt.modules.seed
"""
def setup_loader_modules(self):
return {seed: {}}
@pytest.mark.slow_test
def test_mkconfig_odict(self):
with patch.dict(seed.__opts__, {"master": "foo"}):
ddd = salt.utils.odict.OrderedDict()
ddd["b"] = "b"
ddd["a"] = "b"
data = seed.mkconfig(ddd, approve_key=False)
with salt.utils.files.fopen(data["config"]) as fic:
fdata = fic.read()
self.assertEqual(fdata, "b: b\na: b\nmaster: foo\n")
def test_prep_bootstrap(self):
"""
Test to update and get the random script to a random place
"""
with patch.dict(
seed.__salt__,
{
"config.gather_bootstrap_script": MagicMock(
return_value=os.path.join("BS_PATH", "BS")
)
},
), patch.object(uuid, "uuid4", return_value="UUID"), patch.object(
os.path, "exists", return_value=True
), patch.object(
os, "chmod", return_value=None
), patch.object(
shutil, "copy", return_value=None
):
expect = (
os.path.join("MPT", "tmp", "UUID", "BS"),
os.sep + os.path.join("tmp", "UUID"),
)
self.assertEqual(seed.prep_bootstrap("MPT"), expect)
expect = (
os.sep + os.path.join("MPT", "tmp", "UUID", "BS"),
os.sep + os.path.join("tmp", "UUID"),
)
self.assertEqual(seed.prep_bootstrap(os.sep + "MPT"), expect)
def test_apply_(self):
"""
Test to seed a location (disk image, directory, or block device)
with the minion config, approve the minion's key, and/or install
salt-minion.
"""
mock = MagicMock(
side_effect=[
False,
{"type": "type", "target": "target"},
{"type": "type", "target": "target"},
{"type": "type", "target": "target"},
]
)
with patch.dict(seed.__salt__, {"file.stats": mock}):
self.assertEqual(seed.apply_("path"), "path does not exist")
with patch.object(seed, "_mount", return_value=False):
self.assertEqual(seed.apply_("path"), "target could not be mounted")
with patch.object(seed, "_mount", return_value="/mountpoint"):
with patch.object(os.path, "join", return_value="A"):
with patch.object(
os, "makedirs", MagicMock(side_effect=OSError("f"))
):
with patch.object(os.path, "isdir", return_value=False):
self.assertRaises(OSError, seed.apply_, "p")
with patch.object(os, "makedirs", MagicMock()):
with patch.object(seed, "mkconfig", return_value="A"):
with patch.object(
seed, "_check_install", return_value=False
):
with patch.object(
seed, "_umount", return_value=None
) as umount_mock:
self.assertFalse(seed.apply_("path", install=False))
umount_mock.assert_called_once_with(
"/mountpoint", "target", "type"
)

View file

@ -1,322 +0,0 @@
import salt.modules.selinux as selinux
from salt.exceptions import SaltInvocationError
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.mock import MagicMock, patch
from tests.support.unit import TestCase
class SelinuxModuleTestCase(TestCase, LoaderModuleMockMixin):
"""
Test cases for salt.modules.selinux
"""
def setup_loader_modules(self):
return {selinux: {}}
def test_fcontext_get_policy_parsing(self):
"""
Test to verify that the parsing of the semanage output into fields is
correct. Added with #45784.
"""
cases = [
{
"semanage_out": (
"/var/www(/.*)? all files "
" system_u:object_r:httpd_sys_content_t:s0"
),
"name": "/var/www(/.*)?",
"filetype": "all files",
"sel_user": "system_u",
"sel_role": "object_r",
"sel_type": "httpd_sys_content_t",
"sel_level": "s0",
},
{
"semanage_out": (
"/var/www(/.*)? all files "
" system_u:object_r:httpd_sys_content_t:s0"
),
"name": "/var/www(/.*)?",
"filetype": "all files",
"sel_user": "system_u",
"sel_role": "object_r",
"sel_type": "httpd_sys_content_t",
"sel_level": "s0",
},
{
"semanage_out": (
"/var/lib/dhcp3? directory "
" system_u:object_r:dhcp_state_t:s0"
),
"name": "/var/lib/dhcp3?",
"filetype": "directory",
"sel_user": "system_u",
"sel_role": "object_r",
"sel_type": "dhcp_state_t",
"sel_level": "s0",
},
{
"semanage_out": (
"/var/lib/dhcp3? directory "
" system_u:object_r:dhcp_state_t:s0"
),
"name": "/var/lib/dhcp3?",
"filetype": "directory",
"sel_user": "system_u",
"sel_role": "object_r",
"sel_type": "dhcp_state_t",
"sel_level": "s0",
},
{
"semanage_out": (
"/var/lib/dhcp3? directory "
" system_u:object_r:dhcp_state_t:s0"
),
"name": "/var/lib/dhcp3?",
"filetype": "directory",
"sel_user": "system_u",
"sel_role": "object_r",
"sel_type": "dhcp_state_t",
"sel_level": "s0",
},
]
for case in cases:
with patch.dict(
selinux.__salt__,
{"cmd.shell": MagicMock(return_value=case["semanage_out"])},
):
ret = selinux.fcontext_get_policy(case["name"])
self.assertEqual(ret["filespec"], case["name"])
self.assertEqual(ret["filetype"], case["filetype"])
self.assertEqual(ret["sel_user"], case["sel_user"])
self.assertEqual(ret["sel_role"], case["sel_role"])
self.assertEqual(ret["sel_type"], case["sel_type"])
self.assertEqual(ret["sel_level"], case["sel_level"])
def test_parse_protocol_port_positive(self):
"""
Test to verify positive parsing name, protocol and port combinations
"""
cases = [
{
"name": "tcp/80",
"protocol": None,
"port": None,
"expected": ("tcp", "80"),
},
{
"name": "udp/53",
"protocol": None,
"port": None,
"expected": ("udp", "53"),
},
{
"name": "tcp_test_dns",
"protocol": "tcp",
"port": "53",
"expected": ("tcp", "53"),
},
{
"name": "udp_test/dns",
"protocol": "udp",
"port": "53",
"expected": ("udp", "53"),
},
]
for case in cases:
ret = selinux._parse_protocol_port(
case["name"], case["protocol"], case["port"]
)
self.assertTupleEqual(ret, case["expected"])
def test_parse_protocol_port_negative(self):
"""
Test to verify negative parsing of name, protocol and port combinations
"""
cases = [
{"name": "invalid_name_no_args", "protocol": None, "port": None},
{"name": "invalid_proto/80", "protocol": "nottcp", "port": "80"},
{"name": "invalid_port", "protocol": "tcp", "port": "notaport"},
{"name": "missing_proto", "protocol": None, "port": "80"},
{"name": "missing_port", "protocol": "udp", "port": None},
]
for case in cases:
self.assertRaises(
SaltInvocationError,
selinux._parse_protocol_port,
case["name"],
case["protocol"],
case["port"],
)
def test_port_get_policy_parsing(self):
"""
Test to verify that the parsing of the semanage port output into fields is correct.
"""
cases = [
{
"semanage_out": "cma_port_t tcp 1050",
"name": "tcp/1050",
"expected": {
"sel_type": "cma_port_t",
"protocol": "tcp",
"port": "1050",
},
},
{
"semanage_out": (
"cluster_port_t tcp 5149, 40040, 50006-50008"
),
"name": "tcp/40040",
"expected": {
"sel_type": "cluster_port_t",
"protocol": "tcp",
"port": "5149, 40040, 50006-50008",
},
},
{
"semanage_out": (
"http_port_t tcp 9008, 8010, 9002-9003, 80,"
" 81, 443, 488, 8008, 8009, 8443, 9000"
),
"name": "tcp/9000",
"expected": {
"sel_type": "http_port_t",
"protocol": "tcp",
"port": (
"9008, 8010, 9002-9003, 80, 81, 443, 488, 8008, 8009, 8443,"
" 9000"
),
},
},
{
"semanage_out": (
"vnc_port_t tcp 5985-5999, 5900-5983"
),
"name": "tcp/5985-5999",
"expected": {
"sel_type": "vnc_port_t",
"protocol": "tcp",
"port": "5985-5999, 5900-5983",
},
},
{
"semanage_out": (
"zebra_port_t tcp 2606, 2608-2609, 2600-2604"
),
"name": "tcp/2608-2609",
"expected": {
"sel_type": "zebra_port_t",
"protocol": "tcp",
"port": "2606, 2608-2609, 2600-2604",
},
},
{
"semanage_out": (
"radius_port_t udp 1645, 1812, 18120-18121"
),
"name": "tcp/18120-18121",
"expected": {
"sel_type": "radius_port_t",
"protocol": "udp",
"port": "1645, 1812, 18120-18121",
},
},
]
for case in cases:
with patch.dict(
selinux.__salt__,
{"cmd.shell": MagicMock(return_value=case["semanage_out"])},
):
ret = selinux.port_get_policy(case["name"])
self.assertDictEqual(ret, case["expected"])
def test_fcontext_policy_parsing_new(self):
"""
Test parsing the stdout response of restorecon used in fcontext_policy_applied, new style.
"""
restorecon_ret = (
"Would relabel /foo/bar from some_u:some_r:some_t:s0 to"
" other_u:other_r:other_t:s0"
)
with patch.object(
selinux, "fcontext_policy_is_applied", return_value=restorecon_ret
), patch.dict(
selinux.__salt__, {"cmd.run_all": MagicMock(return_value={"retcode": 0})}
):
self.assertEqual(
selinux.fcontext_apply_policy("/foo/bar"),
{
"changes": {
"/foo/bar": {
"old": {
"sel_role": "some_r",
"sel_type": "some_t",
"sel_user": "some_u",
},
"new": {
"sel_role": "other_r",
"sel_type": "other_t",
"sel_user": "other_u",
},
},
},
"retcode": 0,
},
)
def test_fcontext_policy_parsing_old(self):
"""
Test parsing the stdout response of restorecon used in fcontext_policy_applied, old style.
"""
restorecon_ret = (
"restorecon reset /foo/bar context"
" some_u:some_r:some_t:s0->other_u:other_r:other_t:s0"
)
with patch.object(
selinux, "fcontext_policy_is_applied", return_value=restorecon_ret
), patch.dict(
selinux.__salt__, {"cmd.run_all": MagicMock(return_value={"retcode": 0})}
):
self.assertEqual(
selinux.fcontext_apply_policy("/foo/bar"),
{
"changes": {
"/foo/bar": {
"old": {
"sel_role": "some_r",
"sel_type": "some_t",
"sel_user": "some_u",
},
"new": {
"sel_role": "other_r",
"sel_type": "other_t",
"sel_user": "other_u",
},
},
},
"retcode": 0,
},
)
def test_fcontext_policy_parsing_fail(self):
"""
Test failure response for invalid restorecon data.
"""
restorecon_ret = "And now for something completely different."
with patch.object(
selinux, "fcontext_policy_is_applied", return_value=restorecon_ret
), patch.dict(
selinux.__salt__, {"cmd.run_all": MagicMock(return_value={"retcode": 0})}
):
self.assertEqual(
selinux.fcontext_apply_policy("/foo/bar"),
{
"retcode": 1,
"error": "Unrecognized response from restorecon command.",
},
)

View file

@ -1,26 +0,0 @@
"""
:codeauthor: Jayesh Kariya <jayeshk@saltstack.com>
"""
import salt.modules.sensors as sensors
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.mock import MagicMock, patch
from tests.support.unit import TestCase
class SensorTestCase(TestCase, LoaderModuleMockMixin):
"""
Test cases for salt.modules.sensors
"""
def setup_loader_modules(self):
return {sensors: {}}
def test_sense(self):
"""
Test to gather lm-sensors data from a given chip
"""
with patch.dict(
sensors.__salt__, {"cmd.run": MagicMock(return_value="A:a B:b C:c D:d")}
):
self.assertDictEqual(sensors.sense("chip"), {"A": "a B"})