Exemplo n.º 1
0
    def test_validation(self):
        '''test validation of tests'''
        sc_instance = saltcheck.SaltCheck()

        # Fail on empty test
        test_dict = {}
        expected_return = False
        val_ret = sc_instance._SaltCheck__is_valid_test(test_dict)
        self.assertEqual(val_ret, expected_return)

        # Succeed on standard test
        test_dict = {
                    'module_and_function': 'test.echo',
                    'args': ["hello"],
                    'kwargs': {},
                    'assertion': 'assertEqual',
                    'expected_return':  'hello'
                    }
        expected_return = True
        with patch.dict(saltcheck.__salt__, {'sys.list_modules': MagicMock(return_value=['test']),
                                             'sys.list_functions': MagicMock(return_value=['test.echo'])
                                            }):
            val_ret = sc_instance._SaltCheck__is_valid_test(test_dict)
            self.assertEqual(val_ret, expected_return)

        # Succeed on standard test with older expected-return syntax
        test_dict = {
                    'module_and_function': 'test.echo',
                    'args': ["hello"],
                    'kwargs': {},
                    'assertion': 'assertEqual',
                    'expected-return':  'hello'
                    }
        expected_return = True
        with patch.dict(saltcheck.__salt__, {'sys.list_modules': MagicMock(return_value=['test']),
                                             'sys.list_functions': MagicMock(return_value=['test.echo'])
                                            }):
            val_ret = sc_instance._SaltCheck__is_valid_test(test_dict)
            self.assertEqual(val_ret, expected_return)

        # Do not require expected_return for some assertions
        assertions = ["assertEmpty",
                      "assertNotEmpty",
                      "assertTrue",
                      "assertFalse"]
        for assertion in assertions:
            test_dict = {
                        'module_and_function': 'test.echo',
                        'args': ["hello"]
                        }
            test_dict['assertion'] = assertion
            expected_return = True
            with patch.dict(saltcheck.__salt__, {'sys.list_modules': MagicMock(return_value=['test']),
                                                'sys.list_functions': MagicMock(return_value=['test.echo'])
                                                }):
                val_ret = sc_instance._SaltCheck__is_valid_test(test_dict)
                self.assertEqual(val_ret, expected_return)

        # Fail on invalid module
        test_dict = {
                    'module_and_function': 'broken.echo',
                    'args': ["hello"],
                    'kwargs': {},
                    'assertion': 'assertEqual',
                    'expected_return':  'hello'
                    }
        expected_return = False
        with patch.dict(saltcheck.__salt__, {'sys.list_modules': MagicMock(return_value=['test']),
                                             'sys.list_functions': MagicMock(return_value=['test.echo'])
                                            }):
            val_ret = sc_instance._SaltCheck__is_valid_test(test_dict)
            self.assertEqual(val_ret, expected_return)

        # Fail on invalid function
        test_dict = {
                    'module_and_function': 'test.broken',
                    'args': ["hello"],
                    'kwargs': {},
                    'assertion': 'assertEqual',
                    'expected_return':  'hello'
                    }
        expected_return = False
        with patch.dict(saltcheck.__salt__, {'sys.list_modules': MagicMock(return_value=['test']),
                                             'sys.list_functions': MagicMock(return_value=['test.echo'])
                                            }):
            val_ret = sc_instance._SaltCheck__is_valid_test(test_dict)
            self.assertEqual(val_ret, expected_return)

        # Fail on missing expected_return
        test_dict = {
                    'module_and_function': 'test.echo',
                    'args': ["hello"],
                    'kwargs': {},
                    'assertion': 'assertEqual'
                    }
        expected_return = False
        with patch.dict(saltcheck.__salt__, {'sys.list_modules': MagicMock(return_value=['test']),
                                             'sys.list_functions': MagicMock(return_value=['test.echo'])
                                            }):
            val_ret = sc_instance._SaltCheck__is_valid_test(test_dict)
            self.assertEqual(val_ret, expected_return)

        # Fail on empty expected_return
        test_dict = {
                    'module_and_function': 'test.echo',
                    'args': ["hello"],
                    'kwargs': {},
                    'assertion': 'assertEqual',
                    'expected_return':  None
                    }
        expected_return = False
        with patch.dict(saltcheck.__salt__, {'sys.list_modules': MagicMock(return_value=['test']),
                                             'sys.list_functions': MagicMock(return_value=['test.echo'])
                                            }):
            val_ret = sc_instance._SaltCheck__is_valid_test(test_dict)
            self.assertEqual(val_ret, expected_return)

        # Succeed on m_and_f saltcheck.state_apply with only args
        test_dict = {
                    'module_and_function': 'saltcheck.state_apply',
                    'args': ["common"]
                    }
        expected_return = True
        with patch.dict(saltcheck.__salt__, {'sys.list_modules': MagicMock(return_value=['saltcheck']),
                                             'sys.list_functions': MagicMock(return_value=['saltcheck.state_apply'])
                                            }):
            val_ret = sc_instance._SaltCheck__is_valid_test(test_dict)
            self.assertEqual(val_ret, expected_return)
Exemplo n.º 2
0
class WinDnsClientTestCase(TestCase, LoaderModuleMockMixin):
    """
        Validate the win_dns_client state
    """

    def setup_loader_modules(self):
        return {win_dns_client: {}}

    def test_dns_exists(self):
        """
            Test to configure the DNS server list in the specified interface
        """
        ret = {"name": "salt", "changes": {}, "result": False, "comment": ""}
        with patch.dict(win_dns_client.__opts__, {"test": False}):
            ret.update(
                {
                    "changes": {
                        "Servers Added": [],
                        "Servers Removed": [],
                        "Servers Reordered": [],
                    },
                    "comment": "servers entry is not a list !",
                }
            )
            self.assertDictEqual(win_dns_client.dns_exists("salt"), ret)

            mock = MagicMock(return_value=[2, "salt"])
            with patch.dict(
                win_dns_client.__salt__, {"win_dns_client.get_dns_servers": mock}
            ):
                ret.update(
                    {
                        "changes": {},
                        "comment": repr([2, "salt"]) + " are already" " configured",
                        "result": True,
                    }
                )
                self.assertDictEqual(
                    win_dns_client.dns_exists("salt", [2, "salt"]), ret
                )

                mock = MagicMock(side_effect=[False, True, True])
                with patch.dict(
                    win_dns_client.__salt__, {"win_dns_client.add_dns": mock}
                ):
                    ret.update(
                        {
                            "comment": "Failed to add 1 as DNS" " server number 1",
                            "result": False,
                        }
                    )
                    self.assertDictEqual(
                        win_dns_client.dns_exists("salt", [1, "salt"]), ret
                    )

                    mock = MagicMock(return_value=False)
                    with patch.dict(
                        win_dns_client.__salt__, {"win_dns_client.rm_dns": mock}
                    ):
                        ret.update(
                            {
                                "changes": {
                                    "Servers Added": ["a"],
                                    "Servers Removed": [],
                                    "Servers Reordered": [],
                                },
                                "comment": "Failed to remove 2 from DNS" " server list",
                            }
                        )
                        self.assertDictEqual(
                            win_dns_client.dns_exists("salt", ["a"], "a", 1), ret
                        )

                    ret.update(
                        {"comment": "DNS Servers have been updated", "result": True}
                    )
                    self.assertDictEqual(win_dns_client.dns_exists("salt", ["a"]), ret)

    def test_dns_dhcp(self):
        """
            Test to configure the DNS server list from DHCP Server
        """
        ret = {"name": "salt", "changes": {}, "result": True, "comment": ""}
        mock = MagicMock(side_effect=["dhcp", "salt", "salt"])
        with patch.dict(
            win_dns_client.__salt__, {"win_dns_client.get_dns_config": mock}
        ):
            ret.update(
                {
                    "comment": "Local Area Connection already configured"
                    " with DNS from DHCP"
                }
            )
            self.assertDictEqual(win_dns_client.dns_dhcp("salt"), ret)

            with patch.dict(win_dns_client.__opts__, {"test": True}):
                ret.update(
                    {
                        "comment": "",
                        "result": None,
                        "changes": {"dns": "configured from DHCP"},
                    }
                )
                self.assertDictEqual(win_dns_client.dns_dhcp("salt"), ret)

            with patch.dict(win_dns_client.__opts__, {"test": False}):
                mock = MagicMock(return_value=True)
                with patch.dict(
                    win_dns_client.__salt__, {"win_dns_client.dns_dhcp": mock}
                ):
                    ret.update({"result": True})
                    self.assertDictEqual(win_dns_client.dns_dhcp("salt"), ret)

    def test_primary_suffix(self):
        """
            Test to configure the global primary DNS suffix of a DHCP client.
        '''
        ret = {'name': 'salt',
               'changes': {},
               'result': False,
               'comment': ''}
        ret.update({'comment': "'updates' must be a boolean value"})
        self.assertDictEqual(win_dns_client.primary_suffix('salt', updates='a'
                                                           ), ret)

        mock = MagicMock(side_effect=[{'vdata': 'a'}, {'vdata': False}, {'vdata': 'b'}, {'vdata': False}])
        with patch.dict(win_dns_client.__utils__, {'reg.read_value': mock}):
            ret.update({'comment': 'No changes needed', 'result': True})
            self.assertDictEqual(win_dns_client.primary_suffix('salt', 'a'),
                                 ret)

            mock = MagicMock(return_value=True)
            with patch.dict(win_dns_client.__utils__, {'reg.set_value': mock}):
                ret.update({'changes': {'new': {'suffix': 'a'},
                                        'old': {'suffix': 'b'}},
                            'comment': 'Updated primary DNS suffix (a)'})
                self.assertDictEqual(win_dns_client.primary_suffix('salt',
                                                                   'a'), ret)
Exemplo n.º 3
0
def test_get_key():
    """
    Test gpg.get_key
    """

    _user_mock = {
        "shell": "/bin/bash",
        "workphone": "",
        "uid": 0,
        "passwd": "x",
        "roomnumber": "",
        "gid": 0,
        "groups": ["root"],
        "home": "/root",
        "fullname": "root",
        "homephone": "",
        "name": "root",
    }

    _list_result = [{
        "dummy":
        "",
        "keyid":
        "xxxxxxxxxxxxxxxx",
        "expires":
        "2011188692",
        "sigs": [],
        "subkeys":
        [["xxxxxxxxxxxxxxxx", "e",
          "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"]],
        "length":
        "4096",
        "ownertrust":
        "-",
        "sig":
        "",
        "algo":
        "1",
        "fingerprint":
        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
        "date":
        "1506612692",
        "trust":
        "-",
        "type":
        "pub",
        "uids": ["GPG Person <*****@*****.**>"],
    }]

    _expected_result = {
        "fingerprint": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
        "keyid": "xxxxxxxxxxxxxxxx",
        "uids": ["GPG Person <*****@*****.**>"],
        "created": "2017-09-28",
        "trust": "Unknown",
        "ownerTrust": "Unknown",
        "expires": "2033-09-24",
        "keyLength": "4096",
    }

    mock_opt = MagicMock(return_value="root")
    with patch.dict(gpg.__salt__,
                    {"user.info": MagicMock(return_value=_user_mock)}):
        with patch.dict(gpg.__salt__, {"config.option": mock_opt}):
            with patch.object(gpg, "_list_keys", return_value=_list_result):
                ret = gpg.get_key("xxxxxxxxxxxxxxxx")
                assert ret == _expected_result
Exemplo n.º 4
0
def test_present():
    """
    Test to ensures that the named host is present with the given ip
    """
    add_host = MagicMock(return_value=True)
    rm_host = MagicMock(return_value=True)
    hostname = "salt"
    ip_str = "127.0.0.1"
    ip_list = ["10.1.2.3", "10.4.5.6"]

    # Case 1: No match for hostname. Single IP address passed to the state.
    list_hosts = MagicMock(return_value={"127.0.0.1": {"aliases": ["localhost"]}})
    with patch.dict(
        host.__salt__,
        {
            "hosts.list_hosts": list_hosts,
            "hosts.add_host": add_host,
            "hosts.rm_host": rm_host,
        },
    ):
        ret = host.present(hostname, ip_str)
        assert ret["result"] is True
        assert ret["comment"] == "Added host {} ({})".format(hostname, ip_str), ret[
            "comment"
        ]
        assert ret["changes"] == {"added": {ip_str: [hostname]}}, ret["changes"]
        expected = [call(ip_str, hostname)]
        assert add_host.mock_calls == expected, add_host.mock_calls
        assert rm_host.mock_calls == [], rm_host.mock_calls

    # Case 2: No match for hostname. Multiple IP addresses passed to the
    # state.
    list_hosts = MagicMock(return_value={"127.0.0.1": {"aliases": ["localhost"]}})
    add_host.reset_mock()
    rm_host.reset_mock()
    with patch.dict(
        host.__salt__,
        {
            "hosts.list_hosts": list_hosts,
            "hosts.add_host": add_host,
            "hosts.rm_host": rm_host,
        },
    ):
        ret = host.present(hostname, ip_list)
        assert ret["result"] is True
        assert "Added host {} ({})".format(hostname, ip_list[0]) in ret["comment"]
        assert "Added host {} ({})".format(hostname, ip_list[1]) in ret["comment"]
        assert ret["changes"] == {
            "added": {ip_list[0]: [hostname], ip_list[1]: [hostname]}
        }, ret["changes"]
        expected = sorted([call(x, hostname) for x in ip_list])
        assert sorted(add_host.mock_calls) == expected, add_host.mock_calls
        assert rm_host.mock_calls == [], rm_host.mock_calls

    # Case 3: Match for hostname, but no matching IP. Single IP address
    # passed to the state.
    list_hosts = MagicMock(
        return_value={
            "127.0.0.1": {"aliases": ["localhost"]},
            ip_list[0]: {"aliases": [hostname]},
        }
    )
    add_host.reset_mock()
    rm_host.reset_mock()
    with patch.dict(
        host.__salt__,
        {
            "hosts.list_hosts": list_hosts,
            "hosts.add_host": add_host,
            "hosts.rm_host": rm_host,
        },
    ):
        ret = host.present(hostname, ip_str)
        assert ret["result"] is True
        assert "Added host {} ({})".format(hostname, ip_str) in ret["comment"]
        assert (
            "Host {} present for IP address {}".format(hostname, ip_list[0])
            in ret["warnings"][0]
        )
        assert ret["changes"] == {"added": {ip_str: [hostname]}}, ret["changes"]
        expected = [call(ip_str, hostname)]
        assert add_host.mock_calls == expected, add_host.mock_calls
        assert rm_host.mock_calls == [], rm_host.mock_calls

    # Case 3a: Repeat the above with clean=True
    add_host.reset_mock()
    rm_host.reset_mock()
    with patch.dict(
        host.__salt__,
        {
            "hosts.list_hosts": list_hosts,
            "hosts.add_host": add_host,
            "hosts.rm_host": rm_host,
        },
    ):
        ret = host.present(hostname, ip_str, clean=True)
        assert ret["result"] is True
        assert "Added host {} ({})".format(hostname, ip_str) in ret["comment"]
        assert "Removed host {} ({})".format(hostname, ip_list[0]) in ret["comment"]
        assert ret["changes"] == {
            "added": {ip_str: [hostname]},
            "removed": {ip_list[0]: [hostname]},
        }, ret["changes"]
        expected = [call(ip_str, hostname)]
        assert add_host.mock_calls == expected, add_host.mock_calls
        expected = [call(ip_list[0], hostname)]
        assert rm_host.mock_calls == expected, rm_host.mock_calls

    # Case 4: Match for hostname, but no matching IP. Multiple IP addresses
    # passed to the state.
    cur_ip = "1.2.3.4"
    list_hosts = MagicMock(
        return_value={
            "127.0.0.1": {"aliases": ["localhost"]},
            cur_ip: {"aliases": [hostname]},
        }
    )
    add_host.reset_mock()
    rm_host.reset_mock()
    with patch.dict(
        host.__salt__,
        {
            "hosts.list_hosts": list_hosts,
            "hosts.add_host": add_host,
            "hosts.rm_host": rm_host,
        },
    ):
        ret = host.present(hostname, ip_list)
        assert ret["result"] is True
        assert "Added host {} ({})".format(hostname, ip_list[0]) in ret["comment"]
        assert "Added host {} ({})".format(hostname, ip_list[1]) in ret["comment"]
        assert ret["changes"] == {
            "added": {ip_list[0]: [hostname], ip_list[1]: [hostname]},
        }, ret["changes"]
        expected = sorted([call(x, hostname) for x in ip_list])
        assert sorted(add_host.mock_calls) == expected, add_host.mock_calls
        assert rm_host.mock_calls == [], rm_host.mock_calls

    # Case 4a: Repeat the above with clean=True
    add_host.reset_mock()
    rm_host.reset_mock()
    with patch.dict(
        host.__salt__,
        {
            "hosts.list_hosts": list_hosts,
            "hosts.add_host": add_host,
            "hosts.rm_host": rm_host,
        },
    ):
        ret = host.present(hostname, ip_list, clean=True)
        assert ret["result"] is True
        assert "Added host {} ({})".format(hostname, ip_list[0]) in ret["comment"]
        assert "Added host {} ({})".format(hostname, ip_list[1]) in ret["comment"]
        assert "Removed host {} ({})".format(hostname, cur_ip) in ret["comment"]
        assert ret["changes"] == {
            "added": {ip_list[0]: [hostname], ip_list[1]: [hostname]},
            "removed": {cur_ip: [hostname]},
        }, ret["changes"]
        expected = sorted([call(x, hostname) for x in ip_list])
        assert sorted(add_host.mock_calls) == expected, add_host.mock_calls
        expected = [call(cur_ip, hostname)]
        assert rm_host.mock_calls == expected, rm_host.mock_calls

    # Case 5: Multiple IP addresses passed to the state. One of them
    # matches, the other does not. There is also a non-matching IP that
    # must be removed.
    cur_ip = "1.2.3.4"
    list_hosts = MagicMock(
        return_value={
            "127.0.0.1": {"aliases": ["localhost"]},
            cur_ip: {"aliases": [hostname]},
            ip_list[0]: {"aliases": [hostname]},
        }
    )
    add_host.reset_mock()
    rm_host.reset_mock()
    with patch.dict(
        host.__salt__,
        {
            "hosts.list_hosts": list_hosts,
            "hosts.add_host": add_host,
            "hosts.rm_host": rm_host,
        },
    ):
        ret = host.present(hostname, ip_list)
        assert ret["result"] is True
        assert "Added host {} ({})".format(hostname, ip_list[1]) in ret["comment"]
        assert ret["changes"] == {"added": {ip_list[1]: [hostname]}}, ret["changes"]
        expected = [call(ip_list[1], hostname)]
        assert add_host.mock_calls == expected, add_host.mock_calls
        assert rm_host.mock_calls == [], rm_host.mock_calls

    # Case 5a: Repeat the above with clean=True
    add_host.reset_mock()
    rm_host.reset_mock()
    with patch.dict(
        host.__salt__,
        {
            "hosts.list_hosts": list_hosts,
            "hosts.add_host": add_host,
            "hosts.rm_host": rm_host,
        },
    ):
        ret = host.present(hostname, ip_list, clean=True)
        assert ret["result"] is True
        assert "Added host {} ({})".format(hostname, ip_list[1]) in ret["comment"]
        assert "Removed host {} ({})".format(hostname, cur_ip) in ret["comment"]
        assert ret["changes"] == {
            "added": {ip_list[1]: [hostname]},
            "removed": {cur_ip: [hostname]},
        }, ret["changes"]
        expected = [call(ip_list[1], hostname)]
        assert add_host.mock_calls == expected, add_host.mock_calls
        expected = [call(cur_ip, hostname)]
        assert rm_host.mock_calls == expected, rm_host.mock_calls

    # Case 6: Single IP address passed to the state, which matches the
    # current configuration for that hostname. No changes should be made.
    list_hosts = MagicMock(return_value={ip_str: {"aliases": [hostname]}})
    add_host.reset_mock()
    rm_host.reset_mock()
    with patch.dict(
        host.__salt__,
        {
            "hosts.list_hosts": list_hosts,
            "hosts.add_host": add_host,
            "hosts.rm_host": rm_host,
        },
    ):
        ret = host.present(hostname, ip_str)
        assert ret["result"] is True
        assert (
            ret["comment"]
            == "Host {} ({}) already present".format(hostname, ip_str)
            in ret["comment"]
        )
        assert ret["changes"] == {}, ret["changes"]
        assert add_host.mock_calls == [], add_host.mock_calls
        assert rm_host.mock_calls == [], rm_host.mock_calls

    # Case 7: Multiple IP addresses passed to the state, which both match
    # the current configuration for that hostname. No changes should be
    # made.
    list_hosts = MagicMock(
        return_value={
            ip_list[0]: {"aliases": [hostname]},
            ip_list[1]: {"aliases": [hostname]},
        }
    )
    add_host.reset_mock()
    rm_host.reset_mock()
    with patch.dict(
        host.__salt__,
        {
            "hosts.list_hosts": list_hosts,
            "hosts.add_host": add_host,
            "hosts.rm_host": rm_host,
        },
    ):
        ret = host.present(hostname, ip_list)
        assert ret["result"] is True
        assert (
            "Host {} ({}) already present".format(hostname, ip_list[0])
            in ret["comment"]
        )
        assert (
            "Host {} ({}) already present".format(hostname, ip_list[1])
            in ret["comment"]
        )
        assert ret["changes"] == {}, ret["changes"]
        assert add_host.mock_calls == [], add_host.mock_calls
        assert rm_host.mock_calls == [], rm_host.mock_calls

    # Case 8: Passing a comment to host.present with multiple IPs
    list_hosts = MagicMock(return_value={"127.0.0.1": {"aliases": ["localhost"]}})
    add_host_mock = MagicMock(return_value=True)
    rm_host_mock = MagicMock(return_value=True)
    set_comment_mock = MagicMock(return_value=True)
    add_host_mock.reset_mock()
    rm_host_mock.reset_mock()
    set_comment_mock.reset_mock()
    with patch.dict(
        host.__salt__,
        {
            "hosts.list_hosts": list_hosts,
            "hosts.add_host": add_host_mock,
            "hosts.rm_host": rm_host_mock,
            "hosts.set_comment": set_comment_mock,
        },
    ):
        ret = host.present(hostname, ip_list, comment="A comment")
        assert ret["result"] is True
        assert "Added host {} ({})".format(hostname, ip_list[0]) in ret["comment"]
        assert "Added host {} ({})".format(hostname, ip_list[1]) in ret["comment"]
        assert (
            "Set comment for host {} (A comment)".format(ip_list[0]) in ret["comment"]
        )
        assert (
            "Set comment for host {} (A comment)".format(ip_list[1]) in ret["comment"]
        )
        assert ret["changes"] == {
            "added": {ip_list[0]: [hostname], ip_list[1]: [hostname]},
            "comment_added": {ip_list[0]: ["A comment"], ip_list[1]: ["A comment"]},
        }, ret["changes"]
        expected = sorted([call(x, hostname) for x in ip_list])
        assert sorted(add_host_mock.mock_calls) == expected, add_host_mock.mock_calls

        expected = sorted([call(x, "A comment") for x in ip_list])
        assert (
            sorted(set_comment_mock.mock_calls) == expected
        ), set_comment_mock.mock_calls

        assert rm_host_mock.mock_calls == [], rm_host_mock.mock_calls
Exemplo n.º 5
0
    def test_mount(self):
        """
        Test if it mounts an image
        """
        # Test case with non-existing mount folder
        run_mock = MagicMock(return_value="")
        with patch(
            "os.path.join", MagicMock(return_value="/tmp/guest/fedora.qcow")
        ), patch("os.path.isdir", MagicMock(return_value=False)), patch(
            "os.makedirs", MagicMock()
        ) as makedirs_mock, patch(
            "os.listdir", MagicMock(return_value=False)
        ), patch.dict(
            guestfs.__salt__, {"cmd.run": run_mock}
        ):
            self.assertTrue(guestfs.mount("/srv/images/fedora.qcow"))
            run_mock.assert_called_once_with(
                "guestmount -i -a /srv/images/fedora.qcow --rw /tmp/guest/fedora.qcow",
                python_shell=False,
            )
            makedirs_mock.assert_called_once()

        # Test case with existing but empty mount folder
        run_mock.reset_mock()
        with patch(
            "os.path.join", MagicMock(return_value="/tmp/guest/fedora.qcow")
        ), patch("os.path.isdir", MagicMock(return_value=True)), patch(
            "os.makedirs", MagicMock()
        ) as makedirs_mock, patch(
            "os.listdir", MagicMock(return_value=False)
        ), patch.dict(
            guestfs.__salt__, {"cmd.run": run_mock}
        ):
            self.assertTrue(guestfs.mount("/srv/images/fedora.qcow"))
            run_mock.assert_called_once_with(
                "guestmount -i -a /srv/images/fedora.qcow --rw /tmp/guest/fedora.qcow",
                python_shell=False,
            )
            makedirs_mock.assert_not_called()

        # Test case with existing but not empty mount folder
        run_mock.reset_mock()
        with patch(
            "os.path.join",
            MagicMock(
                side_effect=["/tmp/guest/fedora.qcow", "/tmp/guest/fedora.qcowabc"]
            ),
        ), patch("os.path.isdir", MagicMock(side_effect=[True, False])), patch(
            "os.makedirs", MagicMock()
        ) as makedirs_mock, patch(
            "os.listdir", MagicMock(side_effect=[True, False])
        ), patch.dict(
            guestfs.__salt__, {"cmd.run": run_mock}
        ):
            self.assertTrue(guestfs.mount("/srv/images/fedora.qcow"))
            run_mock.assert_called_once_with(
                "guestmount -i -a /srv/images/fedora.qcow --rw"
                " /tmp/guest/fedora.qcowabc",
                python_shell=False,
            )
            makedirs_mock.assert_called_once()
Exemplo n.º 6
0
    def test_present_multi(self):
        '''
        Test to ensure that multiple kernel modules are loaded.
        '''
        name = 'salted kernel'
        mods = ['cheese', 'crackers']
        ret = {'name': name, 'result': True, 'changes': {}}

        mock_mod_list = MagicMock(return_value=mods)
        with patch.dict(kmod.__salt__, {'kmod.mod_list': mock_mod_list}):
            call_ret = kmod.present(name, mods=mods)

            # Check comment independently: makes test more stable on PY3
            comment = call_ret.pop('comment')
            self.assertIn('cheese', comment)
            self.assertIn('crackers', comment)
            self.assertIn('are already present', comment)

            # Assert against all other dictionary key/values
            self.assertDictEqual(ret, call_ret)

        mock_mod_list = MagicMock(return_value=[])
        with patch.dict(kmod.__salt__, {'kmod.mod_list': mock_mod_list}):
            with patch.dict(kmod.__opts__, {'test': True}):
                call_ret = kmod.present(name, mods=mods)
                ret.update({'result': None})

                # Check comment independently: makes test more stable on PY3
                comment = call_ret.pop('comment')
                self.assertIn('cheese', comment)
                self.assertIn('crackers', comment)
                self.assertIn('are set to be loaded', comment)

                # Assert against all other dictionary key/values
                self.assertDictEqual(ret, call_ret)

        mock_mod_list = MagicMock(return_value=[])
        mock_available = MagicMock(return_value=mods)
        mock_load = MagicMock(return_value=mods)
        with patch.dict(
                kmod.__salt__, {
                    'kmod.mod_list': mock_mod_list,
                    'kmod.available': mock_available,
                    'kmod.load': mock_load
                }):
            with patch.dict(kmod.__opts__, {'test': False}):
                call_ret = kmod.present(name, mods=mods)
                ret.update({
                    'result': True,
                    'changes': {
                        mods[0]: 'loaded',
                        mods[1]: 'loaded'
                    }
                })

                # Check comment independently: makes test more stable on PY3
                comment = call_ret.pop('comment')
                self.assertIn('cheese', comment)
                self.assertIn('crackers', comment)
                self.assertIn('Loaded kernel modules', comment)

                # Assert against all other dictionary key/values
                self.assertDictEqual(ret, call_ret)
Exemplo n.º 7
0
    def test_install_requirements_parsing(self):
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        pip_list = MagicMock(return_value={'pep8': '1.3.3'})
        pip_version = pip.__version__
        mock_pip_version = MagicMock(return_value=pip_version)
        with patch.dict(pip_state.__salt__, {'pip.version': mock_pip_version}):
            with patch.dict(pip_state.__salt__, {'cmd.run_all': mock,
                                                 'pip.list': pip_list}):
                with patch.dict(pip_state.__opts__, {'test': True}):
                    if salt.utils.compare_versions(ver1=pip_version,
                                                   oper='<',
                                                   ver2='10.0'):
                        ret = pip_state.installed('pep8=1.3.2')
                        self.assertSaltFalseReturn({'test': ret})
                        self.assertInSaltComment(
                            'Invalid version specification in package pep8=1.3.2. '
                            '\'=\' is not supported, use \'==\' instead.',
                            {'test': ret})
                    else:
                        self.assertRaises(
                            pip._internal.exceptions.InstallationError,
                            pip_state.installed, 'pep=1.3.2')

            mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
            pip_list = MagicMock(return_value={'pep8': '1.3.3'})
            pip_install = MagicMock(return_value={'retcode': 0})
            with patch.dict(pip_state.__salt__, {'cmd.run_all': mock,
                                                 'pip.list': pip_list,
                                                 'pip.install': pip_install}):
                with patch.dict(pip_state.__opts__, {'test': True}):
                    ret = pip_state.installed('pep8>=1.3.2')
                    self.assertSaltTrueReturn({'test': ret})
                    self.assertInSaltComment(
                        'Python package pep8>=1.3.2 was already installed',
                        {'test': ret}
                    )

            mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
            pip_list = MagicMock(return_value={'pep8': '1.3.3'})
            with patch.dict(pip_state.__salt__, {'cmd.run_all': mock,
                                                 'pip.list': pip_list}):
                with patch.dict(pip_state.__opts__, {'test': True}):
                    ret = pip_state.installed('pep8<1.3.2')
                    self.assertSaltNoneReturn({'test': ret})
                    self.assertInSaltComment(
                        'Python package pep8<1.3.2 is set to be installed',
                        {'test': ret}
                    )

            mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
            pip_list = MagicMock(return_value={'pep8': '1.3.2'})
            pip_install = MagicMock(return_value={'retcode': 0})
            with patch.dict(pip_state.__salt__, {'cmd.run_all': mock,
                                                 'pip.list': pip_list,
                                                 'pip.install': pip_install}):
                with patch.dict(pip_state.__opts__, {'test': True}):
                    ret = pip_state.installed('pep8>1.3.1,<1.3.3')
                    self.assertSaltTrueReturn({'test': ret})
                    self.assertInSaltComment(
                        'Python package pep8>1.3.1,<1.3.3 was already installed',
                        {'test': ret}
                    )

            mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
            pip_list = MagicMock(return_value={'pep8': '1.3.1'})
            pip_install = MagicMock(return_value={'retcode': 0})
            with patch.dict(pip_state.__salt__, {'cmd.run_all': mock,
                                                 'pip.list': pip_list,
                                                 'pip.install': pip_install}):
                with patch.dict(pip_state.__opts__, {'test': True}):
                    ret = pip_state.installed('pep8>1.3.1,<1.3.3')
                    self.assertSaltNoneReturn({'test': ret})
                    self.assertInSaltComment(
                        'Python package pep8>1.3.1,<1.3.3 is set to be installed',
                        {'test': ret}
                    )

            mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
            pip_list = MagicMock(return_value={'pep8': '1.3.1'})
            with patch.dict(pip_state.__salt__, {'cmd.run_all': mock,
                                                 'pip.list': pip_list}):
                with patch.dict(pip_state.__opts__, {'test': True}):
                    ret = pip_state.installed(
                        'git+https://github.com/saltstack/salt-testing.git#egg=SaltTesting>=0.5.1'
                    )
                    self.assertSaltNoneReturn({'test': ret})
                    self.assertInSaltComment(
                        'Python package git+https://github.com/saltstack/'
                        'salt-testing.git#egg=SaltTesting>=0.5.1 is set to be '
                        'installed',
                        {'test': ret}
                    )

            mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
            pip_list = MagicMock(return_value={'pep8': '1.3.1'})
            with patch.dict(pip_state.__salt__, {'cmd.run_all': mock,
                                                 'pip.list': pip_list}):
                with patch.dict(pip_state.__opts__, {'test': True}):
                    ret = pip_state.installed(
                        'git+https://github.com/saltstack/salt-testing.git#egg=SaltTesting'
                    )
                    self.assertSaltNoneReturn({'test': ret})
                    self.assertInSaltComment(
                        'Python package git+https://github.com/saltstack/'
                        'salt-testing.git#egg=SaltTesting is set to be '
                        'installed',
                        {'test': ret}
                    )

            mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
            pip_list = MagicMock(return_value={'pep8': '1.3.1'})
            with patch.dict(pip_state.__salt__, {'cmd.run_all': mock,
                                                 'pip.list': pip_list}):
                with patch.dict(pip_state.__opts__, {'test': True}):
                    ret = pip_state.installed(
                        'https://pypi.python.org/packages/source/S/SaltTesting/'
                        'SaltTesting-0.5.0.tar.gz'
                        '#md5=e6760af92b7165f8be53b5763e40bc24'
                    )
                    self.assertSaltNoneReturn({'test': ret})
                    self.assertInSaltComment(
                        'Python package https://pypi.python.org/packages/source/'
                        'S/SaltTesting/SaltTesting-0.5.0.tar.gz'
                        '#md5=e6760af92b7165f8be53b5763e40bc24 is set to be '
                        'installed',
                        {'test': ret}
                    )

            mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
            pip_list = MagicMock(return_value={'SaltTesting': '0.5.0'})
            pip_install = MagicMock(return_value={
                'retcode': 0,
                'stderr': '',
                'stdout': 'Downloading/unpacking https://pypi.python.org/packages'
                          '/source/S/SaltTesting/SaltTesting-0.5.0.tar.gz\n  '
                          'Downloading SaltTesting-0.5.0.tar.gz\n  Running '
                          'setup.py egg_info for package from '
                          'https://pypi.python.org/packages/source/S/SaltTesting/'
                          'SaltTesting-0.5.0.tar.gz\n    \nCleaning up...'
            })
            with patch.dict(pip_state.__salt__, {'cmd.run_all': mock,
                                                 'pip.list': pip_list,
                                                 'pip.install': pip_install}):
                ret = pip_state.installed(
                    'https://pypi.python.org/packages/source/S/SaltTesting/'
                    'SaltTesting-0.5.0.tar.gz'
                    '#md5=e6760af92b7165f8be53b5763e40bc24'
                )
                self.assertSaltTrueReturn({'test': ret})
                self.assertInSaltComment('All packages were successfully installed',
                    {'test': ret}
                )
                self.assertInSaltReturn(
                    'Installed',
                    {'test': ret},
                    ('changes', 'https://pypi.python.org/packages/source/S/'
                                'SaltTesting/SaltTesting-0.5.0.tar.gz'
                                '#md5=e6760af92b7165f8be53b5763e40bc24==???')
                )

            mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
            pip_list = MagicMock(return_value={'SaltTesting': '0.5.0'})
            pip_install = MagicMock(return_value={
                'retcode': 0,
                'stderr': '',
                'stdout': 'Cloned!'
            })
            with patch.dict(pip_state.__salt__, {'cmd.run_all': mock,
                                                 'pip.list': pip_list,
                                                 'pip.install': pip_install}):
                with patch.dict(pip_state.__opts__, {'test': False}):
                    ret = pip_state.installed(
                        'git+https://github.com/saltstack/salt-testing.git#egg=SaltTesting'
                    )
                    self.assertSaltTrueReturn({'test': ret})
                    self.assertInSaltComment(
                        'packages are already installed',
                        {'test': ret}
                    )

            mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
            pip_list = MagicMock(return_value={'pep8': '1.3.1'})
            pip_install = MagicMock(return_value={'retcode': 0})
            with patch.dict(pip_state.__salt__, {'cmd.run_all': mock,
                                                 'pip.list': pip_list,
                                                 'pip.install': pip_install}):
                with patch.dict(pip_state.__opts__, {'test': False}):
                    ret = pip_state.installed(
                        'arbitrary ID that should be ignored due to requirements specified',
                        requirements='/tmp/non-existing-requirements.txt'
                    )
                    self.assertSaltTrueReturn({'test': ret})

            # Test VCS installations using git+git://
            mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
            pip_list = MagicMock(return_value={'SaltTesting': '0.5.0'})
            pip_install = MagicMock(return_value={
                'retcode': 0,
                'stderr': '',
                'stdout': 'Cloned!'
            })
            with patch.dict(pip_state.__salt__, {'cmd.run_all': mock,
                                                 'pip.list': pip_list,
                                                 'pip.install': pip_install}):
                with patch.dict(pip_state.__opts__, {'test': False}):
                    ret = pip_state.installed(
                        'git+git://github.com/saltstack/salt-testing.git#egg=SaltTesting'
                    )
                    self.assertSaltTrueReturn({'test': ret})
                    self.assertInSaltComment(
                        'packages are already installed',
                        {'test': ret}
                    )

            # Test VCS installations with version info like >= 0.1
            with patch.object(pip, '__version__', MagicMock(side_effect=AttributeError(
                                                        'Faked missing __version__ attribute'))):
                mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
                pip_list = MagicMock(return_value={'SaltTesting': '0.5.0'})
                pip_install = MagicMock(return_value={
                    'retcode': 0,
                    'stderr': '',
                    'stdout': 'Cloned!'
                })
                with patch.dict(pip_state.__salt__, {'cmd.run_all': mock,
                                                     'pip.list': pip_list,
                                                     'pip.install': pip_install}):
                    with patch.dict(pip_state.__opts__, {'test': False}):
                        ret = pip_state.installed(
                            'git+https://github.com/saltstack/salt-testing.git#egg=SaltTesting>=0.5.0'
                        )
                        self.assertSaltTrueReturn({'test': ret})
                        self.assertInSaltComment(
                            'packages are already installed',
                            {'test': ret}
                        )
Exemplo n.º 8
0
    def test_suse_os_from_cpe_data(self):
        '''
        Test if 'os' grain is parsed from CPE_NAME of /etc/os-release
        '''
        _path_exists_map = {
            '/proc/1/cmdline': False
        }
        _os_release_map = {
            'NAME': 'SLES',
            'VERSION': '12-SP1',
            'VERSION_ID': '12.1',
            'PRETTY_NAME': 'SUSE Linux Enterprise Server 12 SP1',
            'ID': 'sles',
            'ANSI_COLOR': '0;32',
            'CPE_NAME': 'cpe:/o:suse:sles:12:sp1'
        }

        path_exists_mock = MagicMock(side_effect=lambda x: _path_exists_map[x])
        empty_mock = MagicMock(return_value={})
        osarch_mock = MagicMock(return_value="amd64")
        os_release_mock = MagicMock(return_value=_os_release_map)

        orig_import = __import__
        if six.PY2:
            built_in = '__builtin__'
        else:
            built_in = 'builtins'

        def _import_mock(name, *args):
            if name == 'lsb_release':
                raise ImportError('No module named lsb_release')
            return orig_import(name, *args)

        distro_mock = MagicMock(
            return_value=('SUSE Linux Enterprise Server ', '12', 'x86_64')
        )

        # - Skip the first if statement
        # - Skip the selinux/systemd stuff (not pertinent)
        # - Skip the init grain compilation (not pertinent)
        # - Ensure that lsb_release fails to import
        # - Skip all the /etc/*-release stuff (not pertinent)
        # - Mock linux_distribution to give us the OS name that we want
        # - Mock the osarch
        with patch.object(salt.utils.platform, 'is_proxy',
                          MagicMock(return_value=False)), \
                patch.object(core, '_linux_bin_exists',
                             MagicMock(return_value=False)), \
                patch.object(os.path, 'exists', path_exists_mock), \
                patch('{0}.__import__'.format(built_in),
                      side_effect=_import_mock), \
                patch.object(os.path, 'isfile', MagicMock(return_value=False)), \
                patch.object(core, '_parse_os_release', os_release_mock), \
                patch.object(core, '_parse_lsb_release', empty_mock), \
                patch.object(core, 'linux_distribution', distro_mock), \
                patch.object(core, '_linux_gpu_data', empty_mock), \
                patch.object(core, '_hw_data', empty_mock), \
                patch.object(core, '_linux_cpudata', empty_mock), \
                patch.object(core, '_virtual', empty_mock), \
                patch.dict(core.__salt__, {'cmd.run': osarch_mock}):
            os_grains = core.os_data()

        self.assertEqual(os_grains.get('os_family'), 'Suse')
        self.assertEqual(os_grains.get('os'), 'SUSE')
Exemplo n.º 9
0
    def test_bsd_memdata(self):
        '''
        Test to memdata on *BSD systems
        '''
        _path_exists_map = {}
        _path_isfile_map = {}
        _cmd_run_map = {
            'freebsd-version -u': '10.3-RELEASE',
            '/sbin/sysctl -n hw.physmem': '2121781248',
            '/sbin/sysctl -n vm.swap_total': '419430400'
        }

        path_exists_mock = MagicMock(side_effect=lambda x: _path_exists_map[x])
        path_isfile_mock = MagicMock(
            side_effect=lambda x: _path_isfile_map.get(x, False)
        )
        cmd_run_mock = MagicMock(
            side_effect=lambda x: _cmd_run_map[x]
        )
        empty_mock = MagicMock(return_value={})

        mock_freebsd_uname = ('FreeBSD',
                              'freebsd10.3-hostname-8148',
                              '10.3-RELEASE',
                              'FreeBSD 10.3-RELEASE #0 r297264: Fri Mar 25 02:10:02 UTC 2016     [email protected]:/usr/obj/usr/src/sys/GENERIC',
                              'amd64',
                              'amd64')

        with patch('platform.uname',
                   MagicMock(return_value=mock_freebsd_uname)):
            with patch.object(salt.utils.platform, 'is_linux',
                              MagicMock(return_value=False)):
                with patch.object(salt.utils.platform, 'is_freebsd',
                                  MagicMock(return_value=True)):
                    # Skip the first if statement
                    with patch.object(salt.utils.platform, 'is_proxy',
                                      MagicMock(return_value=False)):
                        # Skip the init grain compilation (not pertinent)
                        with patch.object(os.path, 'exists', path_exists_mock):
                            with patch('salt.utils.path.which') as mock:
                                mock.return_value = '/sbin/sysctl'
                                # Make a bunch of functions return empty dicts,
                                # we don't care about these grains for the
                                # purposes of this test.
                                with patch.object(
                                        core,
                                        '_bsd_cpudata',
                                        empty_mock):
                                    with patch.object(
                                            core,
                                            '_hw_data',
                                            empty_mock):
                                        with patch.object(
                                                core,
                                                '_virtual',
                                                empty_mock):
                                            with patch.object(
                                                    core,
                                                    '_ps',
                                                    empty_mock):
                                                # Mock the osarch
                                                with patch.dict(
                                                        core.__salt__,
                                                        {'cmd.run': cmd_run_mock}):
                                                    os_grains = core.os_data()

        self.assertEqual(os_grains.get('mem_total'), 2023)
        self.assertEqual(os_grains.get('swap_total'), 400)
Exemplo n.º 10
0
def test_update_local_specific(mock_cache):
    """
    Tests the ``update``-function on the minion's local cache.
    Updates mine functions from kwargs only.
    """
    foo_ret = "baz"
    ip_ret = "2001:db8::1:3"
    manual_mine_functions = {
        "ip_addr": {
            "mine_function": "network.ip_addrs"
        },
        "network.ip_addrs": [],
        "kernel": [
            {
                "mine_function": "grains.get"
            },
            "kernel",
            {
                "allow_tgt": "web*"
            },
        ],
        "foo.bar": {
            "allow_tgt": "G@roles:webserver",
            "allow_tgt_type": "compound"
        },
    }
    with patch.dict(mine.__opts__, {
            "file_client": "local",
            "id": "webserver"
    }), patch.dict(
            mine.__salt__,
        {
            "config.merge": MagicMock(return_value={}),
            "grains.get": lambda x: "Linux!!",
            "network.ip_addrs": MagicMock(return_value=ip_ret),
            "foo.bar": MagicMock(return_value=foo_ret),
        },
    ):
        ret = mine.update(mine_functions=manual_mine_functions)
    assert ret == "FakeCache:StoreSuccess!"
    assert mock_cache.fetch("minions/webserver",
                            "mine_cache") == {
                                "ip_addr": ip_ret,
                                "network.ip_addrs": ip_ret,
                                "foo.bar": {
                                    salt.utils.mine.MINE_ITEM_ACL_DATA:
                                    foo_ret,
                                    salt.utils.mine.MINE_ITEM_ACL_ID:
                                    salt.utils.mine.MINE_ITEM_ACL_VERSION,
                                    "allow_tgt":
                                    "G@roles:webserver",
                                    "allow_tgt_type":
                                    "compound",
                                },
                                "kernel": {
                                    salt.utils.mine.MINE_ITEM_ACL_DATA:
                                    "Linux!!",
                                    salt.utils.mine.MINE_ITEM_ACL_ID:
                                    salt.utils.mine.MINE_ITEM_ACL_VERSION,
                                    "allow_tgt":
                                    "web*",
                                },
                            }
Exemplo n.º 11
0
    def test_check_mine_cache_is_refreshed_on_container_change_event(self):
        '''
        Every command that might modify docker containers state.
        Should trig an update on ``mine.send``
        '''
        with patch.object(docker_mod, '_get_exec_driver'):
            client_args_mock = MagicMock(
                return_value={
                    'create_container': [
                        'image', 'command', 'hostname', 'user', 'detach',
                        'stdin_open', 'tty', 'ports', 'environment', 'volumes',
                        'network_disabled', 'name', 'entrypoint',
                        'working_dir', 'domainname', 'cpuset', 'host_config',
                        'mac_address', 'labels', 'volume_driver',
                        'stop_signal', 'networking_config', 'healthcheck',
                        'stop_timeout'
                    ],
                    'host_config': [
                        'binds', 'port_bindings', 'lxc_conf',
                        'publish_all_ports', 'links', 'privileged', 'dns',
                        'dns_search', 'volumes_from', 'network_mode',
                        'restart_policy', 'cap_add', 'cap_drop', 'devices',
                        'extra_hosts', 'read_only', 'pid_mode', 'ipc_mode',
                        'security_opt', 'ulimits', 'log_config', 'mem_limit',
                        'memswap_limit', 'mem_reservation', 'kernel_memory',
                        'mem_swappiness', 'cgroup_parent', 'group_add',
                        'cpu_quota', 'cpu_period', 'blkio_weight',
                        'blkio_weight_device', 'device_read_bps',
                        'device_write_bps', 'device_read_iops',
                        'device_write_iops', 'oom_kill_disable', 'shm_size',
                        'sysctls', 'tmpfs', 'oom_score_adj', 'dns_opt',
                        'cpu_shares', 'cpuset_cpus', 'userns_mode',
                        'pids_limit', 'isolation', 'auto_remove', 'storage_opt'
                    ],
                    'networking_config': [
                        'aliases', 'links', 'ipv4_address', 'ipv6_address',
                        'link_local_ips'
                    ],
                })

            for command_name, args in (
                ('create', ()),
                ('rm_', ()),
                ('kill', ()),
                ('pause', ()),
                ('signal_', ('KILL', )),
                ('start_', ()),
                ('stop', ()),
                ('unpause', ()),
                ('_run', ('command', )),
                ('_script', ('command', )),
            ):
                mine_send = Mock()
                command = getattr(docker_mod, command_name)
                client = MagicMock()
                client.api_version = '1.12'
                with patch.dict(
                        docker_mod.__salt__, {
                            'mine.send': mine_send,
                            'container_resource.run': MagicMock(),
                            'cp.cache_file': MagicMock(return_value=False)
                        }):
                    with patch.dict(
                            docker_mod.__utils__,
                        {'docker.get_client_args': client_args_mock}):
                        with patch.object(docker_mod, '_get_client', client):
                            command('container', *args)
                mine_send.assert_called_with('docker.ps',
                                             verbose=True,
                                             all=True,
                                             host=True)
Exemplo n.º 12
0
 def test_get_all_proxies_macos_fails(self):
     mock = MagicMock()
     with patch.dict(proxy.__utils__, {"reg.read_value": mock}):
         out = proxy.get_proxy_win()
         assert not mock.called
         self.assertEqual(out, None)
Exemplo n.º 13
0
    def test_linux_memdata(self):
        '''
        Test memdata on Linux systems
        '''
        _path_exists_map = {'/proc/1/cmdline': False, '/proc/meminfo': True}
        _path_isfile_map = {'/proc/meminfo': True}
        _cmd_run_map = {
            'dpkg --print-architecture': 'amd64',
            'rpm --eval %{_host_cpu}': 'x86_64'
        }

        path_exists_mock = MagicMock(side_effect=lambda x: _path_exists_map[x])
        path_isfile_mock = MagicMock(
            side_effect=lambda x: _path_isfile_map.get(x, False))
        cmd_run_mock = MagicMock(side_effect=lambda x: _cmd_run_map[x])
        empty_mock = MagicMock(return_value={})

        _proc_meminfo_file = '''MemTotal:       16277028 kB
SwapTotal:       4789244 kB'''

        orig_import = __import__
        if six.PY2:
            built_in = '__builtin__'
        else:
            built_in = 'builtins'

        def _import_mock(name, *args):
            if name == 'lsb_release':
                raise ImportError('No module named lsb_release')
            return orig_import(name, *args)

        # Skip the first if statement
        with patch.object(salt.utils.platform, 'is_proxy',
                          MagicMock(return_value=False)):
            # Skip the selinux/systemd stuff (not pertinent)
            with patch.object(core, '_linux_bin_exists',
                              MagicMock(return_value=False)):
                # Skip the init grain compilation (not pertinent)
                with patch.object(os.path, 'exists', path_exists_mock):
                    # Ensure that lsb_release fails to import
                    with patch('{0}.__import__'.format(built_in),
                               side_effect=_import_mock):
                        # Skip all the /etc/*-release stuff (not pertinent)
                        with patch.object(os.path, 'isfile', path_isfile_mock):
                            # Make a bunch of functions return empty dicts,
                            # we don't care about these grains for the
                            # purposes of this test.
                            with patch.object(core, '_linux_cpudata',
                                              empty_mock):
                                with patch.object(core, '_linux_gpu_data',
                                                  empty_mock):
                                    with patch('salt.utils.files.fopen',
                                               mock_open()) as _proc_meminfo:
                                        _proc_meminfo.return_value.__iter__.return_value = _proc_meminfo_file.splitlines(
                                        )
                                        with patch.object(
                                                core, '_hw_data', empty_mock):
                                            with patch.object(
                                                    core, '_virtual',
                                                    empty_mock):
                                                with patch.object(
                                                        core, '_ps',
                                                        empty_mock):
                                                    # Mock the osarch
                                                    with patch.dict(
                                                            core.__salt__, {
                                                                'cmd.run':
                                                                cmd_run_mock
                                                            }):
                                                        os_grains = core.os_data(
                                                        )

        self.assertEqual(os_grains.get('mem_total'), 15895)
        self.assertEqual(os_grains.get('swap_total'), 4676)
Exemplo n.º 14
0
    def _run_ubuntu_os_grains_tests(self, os_release_map):
        path_isfile_mock = MagicMock(
            side_effect=lambda x: x in ['/etc/os-release'])
        empty_mock = MagicMock(return_value={})
        osarch_mock = MagicMock(return_value="amd64")
        os_release_mock = MagicMock(
            return_value=os_release_map.get('os_release_file'))

        if six.PY2:
            built_in = '__builtin__'
        else:
            built_in = 'builtins'

        orig_import = __import__

        def _import_mock(name, *args):
            if name == 'lsb_release':
                raise ImportError('No module named lsb_release')
            return orig_import(name, *args)

        # Skip the first if statement
        with patch.object(salt.utils.platform, 'is_proxy',
                          MagicMock(return_value=False)):
            # Skip the selinux/systemd stuff (not pertinent)
            with patch.object(core, '_linux_bin_exists',
                              MagicMock(return_value=False)):
                # Skip the init grain compilation (not pertinent)
                with patch.object(os.path, 'exists', path_isfile_mock):
                    # Ensure that lsb_release fails to import
                    with patch('{0}.__import__'.format(built_in),
                               side_effect=_import_mock):
                        # Skip all the /etc/*-release stuff (not pertinent)
                        with patch.object(os.path, 'isfile', path_isfile_mock):
                            with patch.object(core, '_parse_os_release',
                                              os_release_mock):
                                # Mock linux_distribution to give us the OS
                                # name that we want.
                                distro_mock = MagicMock(
                                    return_value=('Ubuntu', '16.04', 'xenial'))
                                with patch('salt.utils.files.fopen',
                                           mock_open()) as suse_release_file:
                                    suse_release_file.return_value.__iter__.return_value = os_release_map.get(
                                        'suse_release_file', '').splitlines()
                                    with patch.object(core,
                                                      'linux_distribution',
                                                      distro_mock):
                                        with patch.object(
                                                core, '_linux_gpu_data',
                                                empty_mock):
                                            with patch.object(
                                                    core, '_linux_cpudata',
                                                    empty_mock):
                                                with patch.object(
                                                        core, '_virtual',
                                                        empty_mock):
                                                    # Mock the osarch
                                                    with patch.dict(
                                                            core.__salt__, {
                                                                'cmd.run':
                                                                osarch_mock
                                                            }):
                                                        os_grains = core.os_data(
                                                        )

        self.assertEqual(os_grains.get('os'), 'Ubuntu')
        self.assertEqual(os_grains.get('os_family'), 'Debian')
        self.assertEqual(os_grains.get('osfullname'),
                         os_release_map['osfullname'])
        self.assertEqual(os_grains.get('oscodename'),
                         os_release_map['oscodename'])
        self.assertEqual(os_grains.get('osrelease'),
                         os_release_map['osrelease'])
        self.assertListEqual(list(os_grains.get('osrelease_info')),
                             os_release_map['osrelease_info'])
        self.assertEqual(os_grains.get('osmajorrelease'),
                         os_release_map['osmajorrelease'])
Exemplo n.º 15
0
    def test_present(self):
        '''
        Test to ensure the SQS queue exists.
        '''
        name = 'mysqs'
        attributes = {'DelaySeconds': 20}
        base_ret = {'name': name, 'changes': {}}

        mock = MagicMock(
            side_effect=[{'result': b} for b in [False, False, True, True]],
        )
        mock_bool = MagicMock(return_value={'error': 'create error'})
        mock_attr = MagicMock(return_value={'result': {}})
        with patch.dict(boto_sqs.__salt__,
                        {'boto_sqs.exists': mock,
                         'boto_sqs.create': mock_bool,
                         'boto_sqs.get_attributes': mock_attr}):
            with patch.dict(boto_sqs.__opts__, {'test': False}):
                comt = ['Failed to create SQS queue {0}: create error'.format(
                    name,
                )]
                ret = base_ret.copy()
                ret.update({'result': False, 'comment': comt})
                self.assertDictEqual(boto_sqs.present(name), ret)

            with patch.dict(boto_sqs.__opts__, {'test': True}):
                comt = ['SQS queue {0} is set to be created.'.format(name)]
                ret = base_ret.copy()
                ret.update({
                    'result': None,
                    'comment': comt,
                    'pchanges': {'old': None, 'new': 'mysqs'},
                })
                self.assertDictEqual(boto_sqs.present(name), ret)
                diff = textwrap.dedent('''\
                    ---
                    +++
                    @@ -1 +1 @@
                    -{}
                    +DelaySeconds: 20

                ''').splitlines()
                # Difflib adds a trailing space after the +++/--- lines,
                # programatically add them back here. Having them in the test
                # file itself is not feasible since a few popular plugins for
                # vim will remove trailing whitespace.
                for idx in (0, 1):
                    diff[idx] += ' '
                diff = '\n'.join(diff)

                comt = [
                    'SQS queue mysqs present.',
                    'Attribute(s) DelaySeconds set to be updated:\n{0}'.format(
                        diff,
                    ),
                ]
                ret.update({
                    'comment': comt,
                    'pchanges': {'attributes': {'diff': diff}},
                })
                self.assertDictEqual(boto_sqs.present(name, attributes), ret)

            comt = ['SQS queue mysqs present.']
            ret = base_ret.copy()
            ret.update({'result': True, 'comment': comt})
            self.assertDictEqual(boto_sqs.present(name), ret)
Exemplo n.º 16
0
    def test_gnu_slash_linux_in_os_name(self):
        '''
        Test to return a list of all enabled services
        '''
        _path_exists_map = {
            '/proc/1/cmdline': False
        }
        _path_isfile_map = {}
        _cmd_run_map = {
            'dpkg --print-architecture': 'amd64',
        }

        path_exists_mock = MagicMock(side_effect=lambda x: _path_exists_map[x])
        path_isfile_mock = MagicMock(
            side_effect=lambda x: _path_isfile_map.get(x, False)
        )
        cmd_run_mock = MagicMock(
            side_effect=lambda x: _cmd_run_map[x]
        )
        empty_mock = MagicMock(return_value={})

        orig_import = __import__
        if six.PY2:
            built_in = '__builtin__'
        else:
            built_in = 'builtins'

        def _import_mock(name, *args):
            if name == 'lsb_release':
                raise ImportError('No module named lsb_release')
            return orig_import(name, *args)

        # - Skip the first if statement
        # - Skip the selinux/systemd stuff (not pertinent)
        # - Skip the init grain compilation (not pertinent)
        # - Ensure that lsb_release fails to import
        # - Skip all the /etc/*-release stuff (not pertinent)
        # - Mock linux_distribution to give us the OS name that we want
        # - Make a bunch of functions return empty dicts, we don't care about
        #   these grains for the purposes of this test.
        # - Mock the osarch
        distro_mock = MagicMock(return_value=('Debian GNU/Linux', '8.3', ''))
        with patch.object(salt.utils.platform, 'is_proxy',
                          MagicMock(return_value=False)), \
                patch.object(core, '_linux_bin_exists',
                             MagicMock(return_value=False)), \
                patch.object(os.path, 'exists', path_exists_mock), \
                patch('{0}.__import__'.format(built_in), side_effect=_import_mock), \
                patch.object(os.path, 'isfile', path_isfile_mock), \
                patch.object(core, '_parse_lsb_release', empty_mock), \
                patch.object(core, '_parse_os_release', empty_mock), \
                patch.object(core, '_parse_lsb_release', empty_mock), \
                patch.object(core, 'linux_distribution', distro_mock), \
                patch.object(core, '_linux_cpudata', empty_mock), \
                patch.object(core, '_linux_gpu_data', empty_mock), \
                patch.object(core, '_memdata', empty_mock), \
                patch.object(core, '_hw_data', empty_mock), \
                patch.object(core, '_virtual', empty_mock), \
                patch.object(core, '_ps', empty_mock), \
                patch.dict(core.__salt__, {'cmd.run': cmd_run_mock}):
            os_grains = core.os_data()

        self.assertEqual(os_grains.get('os_family'), 'Debian')
Exemplo n.º 17
0
    def test_set_proxy_macos(self):
        """
            Test to make sure we can set the proxy settings on macOS
        """
        with patch.dict(proxy.__grains__, {"os": "Darwin"}):
            expected = {
                "changes": {
                    "new": [
                        {
                            "port": "3128",
                            "server": "192.168.0.1",
                            "service": "http",
                            "user": "******",
                        },
                        {
                            "port": "3128",
                            "server": "192.168.0.1",
                            "service": "https",
                            "user": "******",
                        },
                        {
                            "port": "3128",
                            "server": "192.168.0.1",
                            "service": "ftp",
                            "user": "******",
                        },
                        {
                            "bypass_domains": ["salt.com", "test.com"]
                        },
                    ]
                },
                "comment":
                "http proxy settings updated correctly\nhttps proxy settings updated correctly\nftp proxy "
                "settings updated correctly\nProxy bypass domains updated correctly\n",
                "name":
                "192.168.0.1",
                "result":
                True,
            }

            set_proxy_mock = MagicMock(return_value=True)
            patches = {
                "proxy.get_http_proxy": MagicMock(return_value={}),
                "proxy.get_https_proxy": MagicMock(return_value={}),
                "proxy.get_ftp_proxy": MagicMock(return_value={}),
                "proxy.get_proxy_bypass": MagicMock(return_value=[]),
                "proxy.set_http_proxy": set_proxy_mock,
                "proxy.set_https_proxy": set_proxy_mock,
                "proxy.set_ftp_proxy": set_proxy_mock,
                "proxy.set_proxy_bypass": set_proxy_mock,
            }

            with patch.dict(proxy.__salt__, patches):
                out = proxy.managed(
                    "192.168.0.1",
                    "3128",
                    user="******",
                    password="******",
                    bypass_domains=["salt.com", "test.com"],
                )
                out["changes"]["new"][-1]["bypass_domains"] = sorted(
                    out["changes"]["new"][-1]["bypass_domains"])

                calls = [
                    call("192.168.0.1", "3128", "frank", "passw0rd",
                         "Ethernet"),
                    call("192.168.0.1", "3128", "frank", "passw0rd",
                         "Ethernet"),
                    call("192.168.0.1", "3128", "frank", "passw0rd",
                         "Ethernet"),
                    call(["salt.com", "test.com"], "Ethernet"),
                ]

                set_proxy_mock.assert_has_calls(calls)
                self.assertEqual(out, expected)
Exemplo n.º 18
0
def test_create_a_new_host_with_multiple_interfaces(basic_host_configuration):
    """
    Tests the creation of a host with multiple interfaces. This creates
    one interface of each type, which needs to have their default
    parameters filled. Also, tests the different dns, ip and useip
    combinations.
    """
    host, groups, _, kwargs, ret = basic_host_configuration
    interfaces = [
        OrderedDict([
            (
                "agent_interface",
                [
                    OrderedDict([("dns", "new_host")]),
                    OrderedDict([("type", "agent")]),
                ],
            ),
            (
                "snmp_interface",
                [
                    OrderedDict([("ip", "127.0.0.1")]),
                    OrderedDict([("dns", "new_host")]),
                    OrderedDict([("useip", False)]),
                    OrderedDict([("type", "snmp")]),
                ],
            ),
            (
                "ipmi_interface",
                [
                    OrderedDict([("ip", "127.0.0.1")]),
                    OrderedDict([("dns", "new_host")]),
                    OrderedDict([("type", "ipmi")]),
                ],
            ),
            (
                "jmx_interface",
                [
                    OrderedDict([("ip", "127.0.0.1")]),
                    OrderedDict([("dns", "new_host")]),
                    OrderedDict([("useip", True)]),
                    OrderedDict([("type", "jmx")]),
                ],
            ),
        ])
    ]

    hostgroup_get_output = [
        [{
            "groupid": "16",
            "name": "Testing Group",
            "internal": "0",
            "flags": "0"
        }],
        [{
            "groupid": "17",
            "name": "Tested Group",
            "internal": "0",
            "flags": "0"
        }],
    ]
    host_exists_output = False
    host_create_output = "31337"

    mock_hostgroup_get = MagicMock(side_effect=hostgroup_get_output)
    mock_host_exists = MagicMock(return_value=host_exists_output)
    mock_host_create = MagicMock(return_value=host_create_output)
    with patch.dict(
            zabbix_host.__salt__,
        {
            "zabbix.hostgroup_get": mock_hostgroup_get,
            "zabbix.host_exists": mock_host_exists,
            "zabbix.host_create": mock_host_create,
        },
    ):
        assert zabbix_host.present(host, groups, interfaces, **kwargs) == ret
        # Blame Python 3.5 for this:
        host_create_call = mock_host_create.call_args[0]
        assert host_create_call[0] == "new_host"
        assert host_create_call[1] == [16]
        for interface in host_create_call[2]:
            if interface["type"] == "1":
                assert interface == {
                    "type": "1",
                    "main": "1",
                    "useip": "1",
                    "ip": "",
                    "dns": "new_host",
                    "port": "10050",
                    "details": [],
                }
            elif interface["type"] == "2":
                assert interface == {
                    "type": "2",
                    "main": "1",
                    "useip": "0",
                    "ip": "127.0.0.1",
                    "dns": "new_host",
                    "port": "161",
                    "details": {
                        "version": "2",
                        "bulk": "1",
                        "community": "{$SNMP_COMMUNITY}",
                    },
                }
            elif interface["type"] == "3":
                assert interface == {
                    "type": "3",
                    "main": "1",
                    "useip": "1",
                    "ip": "127.0.0.1",
                    "dns": "new_host",
                    "port": "623",
                    "details": [],
                }
            elif interface["type"] == "4":
                assert interface == {
                    "type": "4",
                    "main": "1",
                    "useip": "1",
                    "ip": "127.0.0.1",
                    "dns": "new_host",
                    "port": "12345",
                    "details": [],
                }
            else:
                assert interface["type"] == "Should be 1, 2, 3 or 4"
Exemplo n.º 19
0
def test_format_pkg_list_with_attr():
    """
    Test to output format of the package list with attr parameter.
    In this case, any redundant "arch" reference will be removed
    from the package name since it's included as part of the requested attr.
    """
    name_arch_mapping = {
        "glibc": {"name": "glibc", "arch": None},
        "glibc.i686": {"name": "glibc", "arch": "i686"},
        "foobar": {"name": "foobar", "arch": None},
        "foobar.something": {"name": "foobar.something", "arch": None},
        "foobar.": {"name": "foobar.", "arch": None},
    }
    packages = {
        "glibc": [
            {
                "version": "2.12",
                "epoch": None,
                "release": "1.212.el6",
                "arch": "x86_64",
            }
        ],
        "glibc.i686": [
            {
                "version": "2.12",
                "epoch": None,
                "release": "1.212.el6",
                "arch": "i686",
            }
        ],
        "foobar": [
            {"version": "1.2.0", "epoch": "2", "release": "7", "arch": "x86_64"},
            {"version": "1.2.3", "epoch": "2", "release": "27", "arch": "x86_64"},
        ],
        "foobar.something": [
            {"version": "1.1", "epoch": "3", "release": "23.1", "arch": "i686"}
        ],
        "foobar.": [
            {"version": "1.1", "epoch": "3", "release": "23.1", "arch": "i686"}
        ],
    }
    expected_pkg_list = {
        "glibc": [
            {
                "arch": "x86_64",
                "release": "1.212.el6",
                "epoch": None,
                "version": "2.12",
            },
            {
                "arch": "i686",
                "release": "1.212.el6",
                "epoch": None,
                "version": "2.12",
            },
        ],
        "foobar": [
            {"arch": "x86_64", "release": "7", "epoch": "2", "version": "1.2.0"},
            {"arch": "x86_64", "release": "27", "epoch": "2", "version": "1.2.3"},
        ],
        "foobar.": [
            {"arch": "i686", "release": "23.1", "epoch": "3", "version": "1.1"}
        ],
        "foobar.something": [
            {"arch": "i686", "release": "23.1", "epoch": "3", "version": "1.1"}
        ],
    }
    with patch.dict(pkg_resource.__salt__, {"pkg.parse_arch": name_arch_mapping.get}):
        pkgs = pkg_resource.format_pkg_list(packages, False, attr=["epoch", "release"])
        assert sorted(pkgs) == sorted(expected_pkg_list)
Exemplo n.º 20
0
def test_create_a_new_host_with_proxy_by_name(basic_host_configuration):
    """
    Test the handling of proxy_host parameter when it is a name
    """
    host, groups, interfaces, kwargs, ret = basic_host_configuration
    kwargs["proxy_host"] = "RemoteProxy"

    hostgroup_get_output = [{
        "groupid": "16",
        "name": "Testing Group",
        "internal": "0",
        "flags": "0"
    }]
    host_exists_output = False
    host_create_output = "31337"
    run_query_output = [{
        "proxyid": "10356",
        "interface": {
            "interfaceid": "56",
            "hostid": "10356",
            "main": "1",
            "type": "0",
            "useip": "1",
            "ip": "127.0.0.1",
            "dns": "remoteproxy.veryfar",
            "port": "10051",
            "details": [],
        },
    }]

    mock_hostgroup_get = MagicMock(return_value=hostgroup_get_output)
    mock_host_exists = MagicMock(return_value=host_exists_output)
    mock_host_create = MagicMock(return_value=host_create_output)
    mock_run_query = MagicMock(return_value=run_query_output)
    with patch.dict(
            zabbix_host.__salt__,
        {
            "zabbix.hostgroup_get": mock_hostgroup_get,
            "zabbix.host_exists": mock_host_exists,
            "zabbix.host_create": mock_host_create,
            "zabbix.run_query": mock_run_query,
        },
    ):
        assert zabbix_host.present(host, groups, interfaces, **kwargs) == ret
        mock_host_create.assert_called_with(
            "new_host",
            [16],
            [{
                "type": "1",
                "main": "1",
                "useip": "1",
                "ip": "127.0.0.1",
                "dns": "basic_interface",
                "port": "10050",
                "details": [],
            }],
            _connection_password="******",
            _connection_url="http://XXXXXXXXX/zabbix/api_jsonrpc.php",
            _connection_user="******",
            inventory={},
            proxy_hostid="10356",
            visible_name=None,
        )
Exemplo n.º 21
0
    def test_present_update_nochange_success(self):
        '''
        Test zpool present with non existing pool
        '''
        ret = {'name': 'myzpool',
               'result': True,
               'comment': 'no update needed',
               'changes': {}}

        config = {
            'import': False,
        }
        layout = [
            OrderedDict([('mirror', ['disk0', 'disk1'])]),
            OrderedDict([('mirror', ['disk2', 'disk3'])]),
        ]
        properties = {
            'autoexpand': True,
        }

        mock_exists = MagicMock(return_value=True)
        mock_get = MagicMock(return_value=OrderedDict([
            ('comment', 'salt managed pool'),
            ('freeing', 0),
            ('listsnapshots', False),
            ('leaked', 0),
            ('feature@obsolete_counts', 'enabled'),
            ('feature@sha512', 'enabled'),
            ('delegation', True),
            ('dedupditto', '0'),
            ('dedupratio', '1.00x'),
            ('autoexpand', True),
            ('feature@bookmarks', 'enabled'),
            ('allocated', 115712),
            ('guid', 1591906802560842214),
            ('feature@large_blocks', 'enabled'),
            ('size', 2113929216),
            ('feature@enabled_txg', 'active'),
            ('feature@hole_birth', 'active'),
            ('capacity', 0),
            ('feature@multi_vdev_crash_dump', 'enabled'),
            ('feature@extensible_dataset', 'enabled'),
            ('cachefile', '-'),
            ('bootfs', '-'),
            ('autoreplace', True),
            ('readonly', False),
            ('version', '-'),
            ('health', 'ONLINE'),
            ('expandsize', '-'),
            ('feature@embedded_data', 'active'),
            ('feature@lz4_compress', 'active'),
            ('feature@async_destroy', 'enabled'),
            ('feature@skein', 'enabled'),
            ('feature@empty_bpobj', 'enabled'),
            ('feature@spacemap_histogram', 'active'),
            ('bootsize', '-'),
            ('free', 2113813504),
            ('feature@device_removal', 'enabled'),
            ('failmode', 'wait'),
            ('feature@filesystem_limits', 'enabled'),
            ('feature@edonr', 'enabled'),
            ('altroot', '-'),
            ('fragmentation', '0%'),
        ]))
        with patch.dict(zpool.__salt__, {'zpool.exists': mock_exists}), \
             patch.dict(zpool.__salt__, {'zpool.get': mock_get}), \
             patch.dict(zpool.__utils__, utils_patch):
            self.assertEqual(
                zpool.present(
                    'myzpool',
                    config=config,
                    layout=layout,
                    properties=properties,
                ),
                ret,
            )
Exemplo n.º 22
0
def test_to_add_new_groups_to_a_host(basic_host_configuration,
                                     existing_host_responses):
    """
    Tests if new groups are added to a host
    """
    host, _, interfaces, kwargs, _ = basic_host_configuration
    (
        host_get_output,
        hostgroup_get_output_up,
        hostinterface_get_output,
        host_inventory_get_output,
    ) = existing_host_responses

    groups = ["Testing Group", 15, "Tested Group"]

    hostgroup_get_output = [
        hostgroup_get_output_up,
        [{
            "groupid": "17",
            "name": "Actual Group",
            "internal": "0",
            "flags": "0"
        }],
        hostgroup_get_output_up,
    ]
    host_exists_output = True
    host_update_output = "31337"

    ret = {
        "changes": {
            "groups": "[16, 15, 17]"
        },
        "comment": "Host new_host updated.",
        "name": "new_host",
        "result": True,
    }

    mock_hostgroup_get = MagicMock(side_effect=hostgroup_get_output)
    mock_host_exists = MagicMock(return_value=host_exists_output)
    mock_host_get = MagicMock(return_value=host_get_output)
    mock_hostinterface_get = MagicMock(return_value=hostinterface_get_output)
    mock_host_inventory_get = MagicMock(return_value=host_inventory_get_output)
    mock_host_update = MagicMock(return_value=host_update_output)
    with patch.dict(
            zabbix_host.__salt__,
        {
            "zabbix.hostgroup_get": mock_hostgroup_get,
            "zabbix.host_exists": mock_host_exists,
            "zabbix.host_get": mock_host_get,
            "zabbix.hostinterface_get": mock_hostinterface_get,
            "zabbix.host_inventory_get": mock_host_inventory_get,
            "zabbix.host_update": mock_host_update,
        },
    ):
        assert zabbix_host.present(host, groups, interfaces, **kwargs) == ret
        mock_host_update.assert_called_with(
            "31337",
            groups=[16, 15, 17],
            _connection_password="******",
            _connection_url="http://XXXXXXXXX/zabbix/api_jsonrpc.php",
            _connection_user="******",
        )
Exemplo n.º 23
0
    def test_check(self):
        '''
        Test if it check for the existence of a rule in the table and chain
        '''
        self.assertEqual(
            iptables.check(table='filter',
                           chain=None,
                           rule=None,
                           family='ipv4'),
            'Error: Chain needs to be specified')

        self.assertEqual(
            iptables.check(table='filter',
                           chain='INPUT',
                           rule=None,
                           family='ipv4'), 'Error: Rule needs to be specified')

        mock_rule = 'm state --state RELATED,ESTABLISHED -j ACCEPT'
        mock_chain = 'INPUT'
        mock_uuid = 31337
        mock_cmd = MagicMock(
            return_value='-A {0}\n-A {1}'.format(mock_chain, hex(mock_uuid)))
        mock_has = MagicMock(return_value=True)
        mock_not = MagicMock(return_value=False)

        with patch.object(iptables, '_has_option', mock_not):
            with patch.object(uuid, 'getnode',
                              MagicMock(return_value=mock_uuid)):
                with patch.dict(iptables.__salt__, {'cmd.run': mock_cmd}):
                    self.assertTrue(
                        iptables.check(table='filter',
                                       chain=mock_chain,
                                       rule=mock_rule,
                                       family='ipv4'))

        mock_cmd = MagicMock(return_value='')

        with patch.object(iptables, '_has_option', mock_not):
            with patch.object(uuid, 'getnode',
                              MagicMock(return_value=mock_uuid)):
                with patch.dict(iptables.__salt__,
                                {'cmd.run': MagicMock(return_value='')}):
                    self.assertFalse(
                        iptables.check(table='filter',
                                       chain=mock_chain,
                                       rule=mock_rule,
                                       family='ipv4'))

        with patch.object(iptables, '_has_option', mock_has):
            with patch.dict(iptables.__salt__, {'cmd.run': mock_cmd}):
                self.assertTrue(
                    iptables.check(table='filter',
                                   chain='INPUT',
                                   rule=mock_rule,
                                   family='ipv4'))

        mock_cmd = MagicMock(return_value='-A 0x4d2')
        mock_uuid = MagicMock(return_value=1234)

        with patch.object(iptables, '_has_option', mock_has):
            with patch.object(uuid, 'getnode', mock_uuid):
                with patch.dict(iptables.__salt__, {'cmd.run': mock_cmd}):
                    self.assertTrue(
                        iptables.check(table='filter',
                                       chain='0x4d2',
                                       rule=mock_rule,
                                       family='ipv4'))
Exemplo n.º 24
0
def test_update_a_host_with_additional_parameters(basic_host_configuration,
                                                  existing_host_responses):
    """
    This test checks if additional parameters can be added to an
    existing host
    """
    host, groups, interfaces, kwargs, _ = basic_host_configuration
    (
        host_get_output,
        hostgroup_get_output,
        hostinterface_get_output,
        host_inventory_get_output,
    ) = existing_host_responses

    kwargs["inventory_mode"] = 0
    kwargs["description"] = "An amazing test host entry"
    host_exists_output = True
    host_update_output = "31337"

    ret = {
        "changes": {
            "host":
            "{'description': 'An amazing test host entry', 'inventory_mode': 0}"
        },
        "comment": "Host new_host updated.",
        "name": "new_host",
        "result": True,
    }

    mock_hostgroup_get = MagicMock(return_value=hostgroup_get_output)
    mock_host_exists = MagicMock(return_value=host_exists_output)
    mock_host_get = MagicMock(return_value=host_get_output)
    mock_hostinterface_get = MagicMock(return_value=hostinterface_get_output)
    mock_host_inventory_get = MagicMock(return_value=host_inventory_get_output)
    mock_host_update = MagicMock(return_value=host_update_output)
    with patch.dict(
            zabbix_host.__salt__,
        {
            "zabbix.hostgroup_get": mock_hostgroup_get,
            "zabbix.host_exists": mock_host_exists,
            "zabbix.host_get": mock_host_get,
            "zabbix.hostinterface_get": mock_hostinterface_get,
            "zabbix.host_inventory_get": mock_host_inventory_get,
            "zabbix.host_update": mock_host_update,
        },
    ):
        # Blame Python 3.5 support for all this black magic
        host_present_ret = zabbix_host.present(host, groups, interfaces,
                                               **kwargs)
        host_present_changes = ast.literal_eval(
            host_present_ret["changes"]["host"])
        assert host_present_changes == ast.literal_eval(ret["changes"]["host"])
        assert host_present_ret["comment"] == "Host new_host updated."
        assert host_present_ret["name"] == "new_host"
        assert host_present_ret["result"] is True
        # When Python 3.5 is gone, the following line does the job:
        # assert zabbix_host.present(host, groups, interfaces, **kwargs) == ret
        mock_host_update.assert_called_with(
            "31337",
            _connection_password="******",
            _connection_url="http://XXXXXXXXX/zabbix/api_jsonrpc.php",
            _connection_user="******",
            description="An amazing test host entry",
            inventory_mode=0,
        )
Exemplo n.º 25
0
    def test_set_host_true_remove(self):
        '''
        Test if an empty hosts value removes existing entries
        '''
        with patch('salt.modules.hosts.__get_hosts_filename',
                   MagicMock(return_value='/etc/hosts')), \
                patch('os.path.isfile', MagicMock(return_value=True)):
            data = [
                '\n'.join((
                    '1.1.1.1 foo.foofoo foo',
                    '2.2.2.2 bar.barbar bar',
                    '3.3.3.3 asdf.asdfadsf asdf',
                    '1.1.1.1 foofoo.foofoo foofoo',
                ))
            ]

            class TmpStringIO(StringIO, object):
                def __init__(self, fn, mode='r'):
                    self.mode = mode
                    initial_value = data[0]
                    if 'w' in self.mode:
                        initial_value = ''
                    super(TmpStringIO, self).__init__(initial_value)

                def __enter__(self):
                    return self

                def __exit__(self, exc_type, exc_value, traceback):
                    self.close()

                def close(self):
                    # Don't save unless there's something there. In Windows
                    # the class gets initialized the first time with mode = w
                    # which sets the initial value to ''. When the class closes
                    # it clears out data and causes the test to fail.
                    # I don't know why it get's initialized with a mode of 'w'
                    # For the purposes of this test data shouldn't be empty
                    # This is a problem with this class and not with the hosts
                    # module
                    if self.getvalue():
                        data[0] = self.getvalue()
                    StringIO.close(self)

                def read(self, *args):
                    ret = super(TmpStringIO, self).read(*args)
                    if six.PY3 and 'b' in self.mode:
                        return salt.utils.stringutils.to_bytes(ret)
                    else:
                        return ret

                def write(self, s, *args):
                    if six.PY3:
                        if 'b' in self.mode:
                            if not isinstance(s, bytes):
                                # Make this act like a binary filehandle
                                raise TypeError(
                                    "a bytes-like object is required, not 'str'"
                                )
                            # The StringIO wants a str type, it won't take
                            # bytes. Convert before writing to it.
                            return super(TmpStringIO, self).write(
                                salt.utils.stringutils.to_str(s), *args)
                        else:
                            if not isinstance(s, str):
                                # Make this act like a non-binary filehandle
                                raise TypeError(
                                    "write() argument must be str, not bytes")
                    return super(TmpStringIO, self).write(s, *args)

                def readlines(self):
                    ret = super(TmpStringIO, self).readlines()
                    if six.PY3 and 'b' in self.mode:
                        return salt.utils.data.encode(ret)
                    else:
                        return ret

                def writelines(self, lines):
                    for line in lines:
                        self.write(line)

            expected = '\n'.join((
                '2.2.2.2 bar.barbar bar',
                '3.3.3.3 asdf.asdfadsf asdf',
            )) + '\n'

            with patch('salt.utils.files.fopen', TmpStringIO):
                mock_opt = MagicMock(return_value=None)
                with patch.dict(hosts.__salt__, {'config.option': mock_opt}):
                    self.assertTrue(hosts.set_host('1.1.1.1', ' '))

            self.assertEqual(data[0], expected)
Exemplo n.º 26
0
def test_update_a_hostinterface(basic_host_configuration,
                                existing_host_responses):
    """
    Tests the update of a current hostinterface of a host.
    """
    host, groups, _, kwargs, _ = basic_host_configuration
    (
        host_get_output,
        hostgroup_get_output,
        hostinterface_get_output,
        host_inventory_get_output,
    ) = existing_host_responses

    interfaces = [
        OrderedDict([
            (
                "basic_interface",
                [
                    OrderedDict([("dns", "new_host")]),
                    OrderedDict([("type", "agent")]),
                    OrderedDict([("useip", False)]),
                ],
            ),
        ])
    ]
    host_exists_output = True
    hostinterface_update_output = "29"

    ret = {
        "changes": {
            "interfaces":
            "[{'type': '1', 'main': '1', 'useip': '0', 'ip': '', 'dns': 'new_host', 'port': '10050', 'details': []}]"
        },
        "comment": "Host new_host updated.",
        "name": "new_host",
        "result": True,
    }

    mock_hostgroup_get = MagicMock(return_value=hostgroup_get_output)
    mock_host_exists = MagicMock(return_value=host_exists_output)
    mock_host_get = MagicMock(return_value=host_get_output)
    mock_hostinterface_get = MagicMock(return_value=hostinterface_get_output)
    mock_host_inventory_get = MagicMock(return_value=host_inventory_get_output)
    mock_hostinterface_update = MagicMock(
        return_value=hostinterface_update_output)
    with patch.dict(
            zabbix_host.__salt__,
        {
            "zabbix.hostgroup_get": mock_hostgroup_get,
            "zabbix.host_exists": mock_host_exists,
            "zabbix.host_get": mock_host_get,
            "zabbix.hostinterface_get": mock_hostinterface_get,
            "zabbix.host_inventory_get": mock_host_inventory_get,
            "zabbix.hostinterface_update": mock_hostinterface_update,
        },
    ):
        # Blame Python 3.5 support for all this black magic
        host_present_ret = zabbix_host.present(host, groups, interfaces,
                                               **kwargs)
        host_present_changes = ast.literal_eval(
            host_present_ret["changes"]["interfaces"])
        assert host_present_changes == ast.literal_eval(
            ret["changes"]["interfaces"])
        assert host_present_ret["comment"] == "Host new_host updated."
        assert host_present_ret["name"] == "new_host"
        assert host_present_ret["result"] is True
        # When Python 3.5 is gone, the following line does the job:
        # assert zabbix_host.present(host, groups, interfaces, **kwargs) == ret
        mock_hostinterface_update.assert_called_with(
            interfaceid="29",
            ip="",
            dns="new_host",
            useip="0",
            type="1",
            main="1",
            port="10050",
            details=[],
            _connection_password="******",
            _connection_url="http://XXXXXXXXX/zabbix/api_jsonrpc.php",
            _connection_user="******",
        )
Exemplo n.º 27
0
    def test_dns_exists(self):
        """
            Test to configure the DNS server list in the specified interface
        """
        ret = {"name": "salt", "changes": {}, "result": False, "comment": ""}
        with patch.dict(win_dns_client.__opts__, {"test": False}):
            ret.update(
                {
                    "changes": {
                        "Servers Added": [],
                        "Servers Removed": [],
                        "Servers Reordered": [],
                    },
                    "comment": "servers entry is not a list !",
                }
            )
            self.assertDictEqual(win_dns_client.dns_exists("salt"), ret)

            mock = MagicMock(return_value=[2, "salt"])
            with patch.dict(
                win_dns_client.__salt__, {"win_dns_client.get_dns_servers": mock}
            ):
                ret.update(
                    {
                        "changes": {},
                        "comment": repr([2, "salt"]) + " are already" " configured",
                        "result": True,
                    }
                )
                self.assertDictEqual(
                    win_dns_client.dns_exists("salt", [2, "salt"]), ret
                )

                mock = MagicMock(side_effect=[False, True, True])
                with patch.dict(
                    win_dns_client.__salt__, {"win_dns_client.add_dns": mock}
                ):
                    ret.update(
                        {
                            "comment": "Failed to add 1 as DNS" " server number 1",
                            "result": False,
                        }
                    )
                    self.assertDictEqual(
                        win_dns_client.dns_exists("salt", [1, "salt"]), ret
                    )

                    mock = MagicMock(return_value=False)
                    with patch.dict(
                        win_dns_client.__salt__, {"win_dns_client.rm_dns": mock}
                    ):
                        ret.update(
                            {
                                "changes": {
                                    "Servers Added": ["a"],
                                    "Servers Removed": [],
                                    "Servers Reordered": [],
                                },
                                "comment": "Failed to remove 2 from DNS" " server list",
                            }
                        )
                        self.assertDictEqual(
                            win_dns_client.dns_exists("salt", ["a"], "a", 1), ret
                        )

                    ret.update(
                        {"comment": "DNS Servers have been updated", "result": True}
                    )
                    self.assertDictEqual(win_dns_client.dns_exists("salt", ["a"]), ret)
Exemplo n.º 28
0
    def test_list_pkgs_homebrew_cask_pakages(self):
        """
        Tests if pkg.list_pkgs list properly homebrew cask packages
        """
        def custom_call_brew(cmd, failhard=True):
            result = dict()
            if cmd == "info --json=v1 --installed":
                result = {
                    "stdout":
                    '[{"name":"zsh","full_name":"zsh","oldname":null,'
                    '"aliases":[],"homepage":"https://www.zsh.org/",'
                    '"versions":{"stable":"5.7.1","devel":null,"head":"HEAD","bottle":true},'
                    '"installed":[{"version":"5.7.1","used_options":[],'
                    '"built_as_bottle":true,"poured_from_bottle":true,'
                    '"runtime_dependencies":[{"full_name":"ncurses","version":"6.1"},'
                    '{"full_name":"pcre","version":"8.42"}],'
                    '"installed_as_dependency":false,"installed_on_request":true}]}]',
                    "stderr":
                    "",
                    "retcode":
                    0,
                }
            elif cmd == "cask list --versions":
                result = {
                    "stdout": "macvim 8.1.151\nfont-firacode-nerd-font 2.0.0",
                    "stderr": "",
                    "retcode": 0,
                }
            elif cmd == "cask info macvim":
                result = {
                    "stdout":
                    "macvim: 8.1.1517,156 (auto_updates)\n"
                    "https://github.com/macvim-dev/macvim\n"
                    "/usr/local/Caskroom/macvim/8.1.151 (64B)\n"
                    "From: https://github.com/Homebrew/homebrew-cask/blob/master/Casks/macvim.rb\n"
                    "==> Name\n"
                    "MacVim",
                    "stderr":
                    "",
                    "retcode":
                    0,
                }
            elif cmd == "cask info font-firacode-nerd-font":
                result = {
                    "stdout":
                    "font-firacode-nerd-font: 2.0.0\n"
                    "https://github.com/ryanoasis/nerd-fonts\n"
                    "/usr/local/Caskroom/font-firacode-nerd-font/2.0.0 (35 files, 64.8MB)\n"
                    "From: https://github.com/Homebrew/homebrew-cask-fonts/blob/master/Casks/font-firacode-nerd-font.rb\n"
                    "==> Name\n"
                    "FuraCode Nerd Font (FiraCode)",
                    "stderr":
                    "",
                    "retcode":
                    "",
                }

            return result

        def custom_add_pkg(ret, name, newest_version):
            ret[name] = newest_version
            return ret

        expected_pkgs = {
            "zsh": "5.7.1",
            "homebrew/cask/macvim": "8.1.151",
            "homebrew/cask-fonts/font-firacode-nerd-font": "2.0.0",
        }

        with patch("salt.modules.mac_brew_pkg._call_brew",
                   custom_call_brew), patch.dict(
                       mac_brew.__salt__,
                       {
                           "pkg_resource.add_pkg": custom_add_pkg,
                           "pkg_resource.sort_pkglist": MagicMock(),
                       },
                   ):
            self.assertEqual(mac_brew.list_pkgs(versions_as_list=True),
                             expected_pkgs)
Exemplo n.º 29
0
def test_delete_key_with_passphrase_with_gpg_passphrase_in_pillar(gpghome):
    """
    Test gpg.delete_key with passphrase and gpg_passphrase pillar
    """

    _user_mock = {
        "shell": "/bin/bash",
        "workphone": "",
        "uid": 0,
        "passwd": "x",
        "roomnumber": "",
        "gid": 0,
        "groups": ["root"],
        "home": str(gpghome.path),
        "fullname": "root",
        "homephone": "",
        "name": "root",
    }

    _list_result = [{
        "dummy":
        "",
        "keyid":
        "xxxxxxxxxxxxxxxx",
        "expires":
        "2011188692",
        "sigs": [],
        "subkeys":
        [["xxxxxxxxxxxxxxxx", "e",
          "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"]],
        "length":
        "4096",
        "ownertrust":
        "-",
        "sig":
        "",
        "algo":
        "1",
        "fingerprint":
        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
        "date":
        "1506612692",
        "trust":
        "-",
        "type":
        "pub",
        "uids": ["GPG Person <*****@*****.**>"],
    }]

    _expected_result = {
        "res":
        True,
        "message":
        ("Secret key for xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx deleted\nPublic"
         " key for xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx deleted"),
    }

    mock_opt = MagicMock(return_value="root")
    pillar_mock = MagicMock(return_value=GPG_TEST_KEY_PASSPHRASE)
    with patch.dict(gpg.__salt__,
                    {"user.info": MagicMock(return_value=_user_mock)}):
        with patch.dict(gpg.__salt__, {"config.option": mock_opt}), patch.dict(
                gpg.__salt__, {"pillar.get": pillar_mock}):
            with patch.object(gpg, "_list_keys", return_value=_list_result):
                with patch(
                        "salt.modules.gpg.gnupg.GPG.delete_keys",
                        MagicMock(return_value="ok"),
                ) as gnupg_delete_keys:
                    ret = gpg.delete_key("xxxxxxxxxxxxxxxx",
                                         delete_secret=True)
                    assert ret == _expected_result
                    gnupg_delete_keys.assert_called_with(
                        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
                        False,
                        passphrase=GPG_TEST_KEY_PASSPHRASE,
                    )
Exemplo n.º 30
0
    def test_user_exists(self):
        """
        Test to see if mysql module properly forms the MySQL query to see if a user exists

        Do it before test_user_create_when_user_exists mocks the user_exists call
        """
        with patch.object(mysql, "version", return_value="8.0.10"):
            self._test_call(
                mysql.user_exists,
                {
                    "sql": ("SELECT User,Host FROM mysql.user WHERE "
                            "User = %(user)s AND Host = %(host)s AND "
                            "Password = PASSWORD(%(password)s)"),
                    "sql_args": {
                        "host": "localhost",
                        "password": "******",
                        "user": "******",
                    },
                },
                user="******",
                host="localhost",
                password="******",
            )

        with patch.object(mysql, "version", return_value="10.1.38-MariaDB"):
            self._test_call(
                mysql.user_exists,
                {
                    "sql": ("SELECT User,Host FROM mysql.user WHERE "
                            "User = %(user)s AND Host = %(host)s AND "
                            "Password = PASSWORD(%(password)s)"),
                    "sql_args": {
                        "host": "localhost",
                        "password": "******",
                        "user": "******",
                    },
                },
                user="******",
                host="localhost",
                password="******",
            )

        with patch.object(mysql, "version", return_value="8.0.11"):
            self._test_call(
                mysql.user_exists,
                {
                    "sql": ("SELECT User,Host FROM mysql.user WHERE "
                            "User = %(user)s AND Host = %(host)s"),
                    "sql_args": {
                        "host": "localhost",
                        "user": "******"
                    },
                },
                user="******",
                host="localhost",
                password="******",
            )

        with patch.object(mysql, "version", return_value="8.0.11"):
            with patch.object(
                    mysql,
                    "__get_auth_plugin",
                    MagicMock(return_value="mysql_native_password"),
            ):
                self._test_call(
                    mysql.user_exists,
                    {
                        "sql": ("SELECT User,Host FROM mysql.user WHERE "
                                "User = %(user)s AND Host = %(host)s AND "
                                "Password = %(password)s"),
                        "sql_args": {
                            "host": "%",
                            "password":
                            "******",
                            "user": "******",
                        },
                    },
                    user="******",
                    host="%",
                    password="******",
                )

        with patch.object(mysql, "version", return_value="10.2.21-MariaDB"):
            self._test_call(
                mysql.user_exists,
                {
                    "sql": ("SELECT User,Host FROM mysql.user WHERE "
                            "User = %(user)s AND Host = %(host)s AND "
                            "Password = PASSWORD(%(password)s)"),
                    "sql_args": {
                        "host": "localhost",
                        "password": "******",
                        "user": "******",
                    },
                },
                user="******",
                host="localhost",
                password="******",
            )

        # test_user_create_when_user_exists(self):
        # ensure we don't try to create a user when one already exists
        # mock the version of MySQL
        with patch.object(mysql, "version", return_value="8.0.10"):
            with patch.object(mysql, "user_exists",
                              MagicMock(return_value=True)):
                with patch.dict(mysql.__salt__,
                                {"config.option": MagicMock()}):
                    ret = mysql.user_create("testuser")
                    self.assertEqual(False, ret)

        # test_user_create_when_user_exists(self):
        # ensure we don't try to create a user when one already exists
        # mock the version of MySQL
        with patch.object(mysql, "version", return_value="8.0.11"):
            with patch.object(mysql, "user_exists",
                              MagicMock(return_value=True)):
                with patch.object(mysql, "verify_login",
                                  MagicMock(return_value=True)):
                    with patch.dict(mysql.__salt__,
                                    {"config.option": MagicMock()}):
                        ret = mysql.user_create("testuser")
                        self.assertEqual(False, ret)