Ejemplo n.º 1
0
 def test_reboot_with_delay(self):
     '''
     Test to reboot the system using shutdown -r with a delay
     '''
     cmd_mock = MagicMock(return_value='A')
     with patch.dict(system.__salt__, {'cmd.run': cmd_mock}):
         self.assertEqual(system.reboot(at_time=5), 'A')
     cmd_mock.assert_called_with(['shutdown', '-r', '5'], python_shell=False)
Ejemplo n.º 2
0
 def test_saltify_reboot(self):
     mm_cmd = MagicMock(return_value=True)
     lcl = salt.client.LocalClient()
     lcl.cmd = mm_cmd
     with patch('salt.client.LocalClient', return_value=lcl):
         result = saltify.reboot('nodeS1', 'action')
         mm_cmd.assert_called_with('nodeS1', 'system.reboot')
         self.assertTrue(result)
Ejemplo n.º 3
0
 def test_reboot(self):
     '''
     Test to reboot the system with shutdown -r
     '''
     cmd_mock = MagicMock(return_value='A')
     with patch.dict(system.__salt__, {'cmd.run': cmd_mock}):
         self.assertEqual(system.reboot(), 'A')
     cmd_mock.assert_called_with(['shutdown', '-r', 'now'], python_shell=False)
Ejemplo n.º 4
0
 def test_reboot_with_delay(self):
     """
     Test to reboot the system using shutdown -r with a delay
     """
     cmd_mock = MagicMock(return_value="A")
     with patch.dict(system.__salt__, {"cmd.run": cmd_mock}):
         self.assertEqual(system.reboot(at_time=5), "A")
     cmd_mock.assert_called_with(["shutdown", "-r", "5"], python_shell=False)
Ejemplo n.º 5
0
 def test_reboot(self):
     """
     Test to reboot the system with shutdown -r
     """
     cmd_mock = MagicMock(return_value="A")
     with patch.dict(system.__salt__, {"cmd.run": cmd_mock}):
         self.assertEqual(system.reboot(), "A")
     cmd_mock.assert_called_with(["shutdown", "-r", "now"], python_shell=False)
Ejemplo n.º 6
0
 def test_saltify_reboot(self):
     mm_cmd = MagicMock(return_value=True)
     lcl = salt.client.LocalClient()
     lcl.cmd = mm_cmd
     with patch("salt.client.LocalClient", return_value=lcl):
         result = saltify.reboot("nodeS1", "action")
         mm_cmd.assert_called_with("nodeS1", "system.reboot")
         self.assertTrue(result)
Ejemplo n.º 7
0
 def test_get_saved_rules(self):
     """
     Test if it return a data structure of the rules in the conf file
     """
     mock = MagicMock(return_value=False)
     with patch.object(iptables, "_parse_conf", mock):
         self.assertFalse(iptables.get_saved_rules())
         mock.assert_called_with(conf_file=None, family="ipv4")
Ejemplo n.º 8
0
 def test_get_rules(self):
     """
     Test if it return a data structure of the current, in-memory rules
     """
     mock = MagicMock(return_value=False)
     with patch.object(iptables, "_parse_conf", mock):
         self.assertFalse(iptables.get_rules())
         mock.assert_called_with(in_mem=True, family="ipv4")
Ejemplo n.º 9
0
    def test_extracted_tar(self):
        '''
        archive.extracted tar options
        '''

        source = '/tmp/foo.tar.gz'
        tmp_dir = '/tmp/test_extracted_tar'
        test_tar_opts = [
            '--no-anchored foo',
            'v -p --opt',
            '-v -p',
            '--long-opt -z',
            'z -v -weird-long-opt arg',
        ]
        ret_tar_opts = [
            ['tar', 'x', '--no-anchored', 'foo', '-f'],
            ['tar', 'xv', '-p', '--opt', '-f'],
            ['tar', 'x', '-v', '-p', '-f'],
            ['tar', 'x', '--long-opt', '-z', '-f'],
            ['tar', 'xz', '-v', '-weird-long-opt', 'arg', '-f'],
        ]

        mock_true = MagicMock(return_value=True)
        mock_false = MagicMock(return_value=False)
        ret = {'stdout': ['cheese', 'ham', 'saltines'], 'stderr': 'biscuits', 'retcode': '31337', 'pid': '1337'}
        mock_run = MagicMock(return_value=ret)
        mock_source_list = MagicMock(return_value=(source, None))
        state_single_mock = MagicMock(return_value={'local': {'result': True}})
        list_mock = MagicMock(return_value={
            'dirs': [],
            'files': ['cheese', 'saltines'],
            'links': ['ham'],
            'top_level_dirs': [],
            'top_level_files': ['cheese', 'saltines'],
            'top_level_links': ['ham'],
        })
        isfile_mock = MagicMock(side_effect=_isfile_side_effect)

        with patch.dict(archive.__opts__, {'test': False,
                                           'cachedir': tmp_dir,
                                           'hash_type': 'sha256'}):
            with patch.dict(archive.__salt__, {'file.directory_exists': mock_false,
                                               'file.file_exists': mock_false,
                                               'state.single': state_single_mock,
                                               'file.makedirs': mock_true,
                                               'cmd.run_all': mock_run,
                                               'archive.list': list_mock,
                                               'file.source_list': mock_source_list}):
                with patch.object(os.path, 'isfile', isfile_mock):
                    for test_opts, ret_opts in zip(test_tar_opts, ret_tar_opts):
                        ret = archive.extracted(tmp_dir,
                                                source,
                                                options=test_opts,
                                                enforce_toplevel=False)
                        ret_opts.append(source)
                        mock_run.assert_called_with(ret_opts,
                                                    cwd=tmp_dir + os.sep,
                                                    python_shell=False)
Ejemplo n.º 10
0
def test_list_upgrades_present():
    """
    Test pkgng.list_upgrades with upgrades available
    """
    pkg_cmd = MagicMock(
        return_value=textwrap.dedent(
            """
        The following 6 package(s) will be affected (of 0 checked):

        Installed packages to be UPGRADED:
                pkga: 1.0 -> 1.1
                pkgb: 2.0 -> 2.1 [FreeBSD]
                pkgc: 3.0 -> 3.1 [FreeBSD] (dependency changed)
                pkgd: 4.0 -> 4.1 (dependency changed)

        New packages to be INSTALLED:
                pkge: 1.0
                pkgf: 2.0 [FreeBSD]
                pkgg: 3.0 [FreeBSD] (dependency changed)
                pkgh: 4.0 (dependency changed)

        Installed packages to be REINSTALLED:
                pkgi-1.0
                pkgj-2.0 [FreeBSD]
                pkgk-3.0 [FreeBSD] (direct dependency changed: pkga)
                pkgl-4.0 (direct dependency changed: pkgb)

        Installed packages to be DOWNGRADED:
                pkgm: 1.1 -> 1.0
                pkgn: 2.1 -> 2.0 [FreeBSD]
                pkgo: 3.1 -> 3.0 [FreeBSD] (dependency changed)
                pkgp: 4.1 -> 4.0 (dependency changed)

        Installed packages to be REMOVED:
                pkgq-1.0
                pkgr-2.0 [FreeBSD]
                pkgs-3.0 [FreeBSD] (direct dependency changed: pkga)
                pkgt-4.0 (direct dependency changed: pkgb)

        Number of packages to be upgraded: 2
        Number of packages to be reinstalled: 2

        The process will require 14 MiB more space.
        22 MiB to be downloaded.
        """
        )
    )

    with patch.dict(pkgng.__salt__, {"cmd.run_stdout": pkg_cmd}):

        result = pkgng.list_upgrades(refresh=False)
        assert result == {"pkga": "1.1", "pkgb": "2.1", "pkgc": "3.1", "pkgd": "4.1"}
        pkg_cmd.assert_called_with(
            ["pkg", "upgrade", "--dry-run", "--quiet", "--no-repo-update"],
            output_loglevel="trace",
            python_shell=False,
            ignore_retcode=True,
        )
Ejemplo n.º 11
0
    def test_list_upgrades_present(self):
        '''
        Test pkgng.list_upgrades with upgrades available
        '''
        pkg_cmd = MagicMock(return_value=textwrap.dedent("""
            The following 6 package(s) will be affected (of 0 checked):

            Installed packages to be UPGRADED:
                    pkga: 1.0 -> 1.1
                    pkgb: 2.0 -> 2.1 [FreeBSD]
                    pkgc: 3.0 -> 3.1 [FreeBSD] (dependency changed)
                    pkgd: 4.0 -> 4.1 (dependency changed)

            New packages to be INSTALLED:
                    pkge: 1.0
                    pkgf: 2.0 [FreeBSD]
                    pkgg: 3.0 [FreeBSD] (dependency changed)
                    pkgh: 4.0 (dependency changed)

            Installed packages to be REINSTALLED:
                    pkgi-1.0
                    pkgj-2.0 [FreeBSD]
                    pkgk-3.0 [FreeBSD] (direct dependency changed: pkga)
                    pkgl-4.0 (direct dependency changed: pkgb)

            Installed packages to be DOWNGRADED:
                    pkgm: 1.1 -> 1.0
                    pkgn: 2.1 -> 2.0 [FreeBSD]
                    pkgo: 3.1 -> 3.0 [FreeBSD] (dependency changed)
                    pkgp: 4.1 -> 4.0 (dependency changed)

            Installed packages to be REMOVED:
                    pkgq-1.0
                    pkgr-2.0 [FreeBSD]
                    pkgs-3.0 [FreeBSD] (direct dependency changed: pkga)
                    pkgt-4.0 (direct dependency changed: pkgb)

            Number of packages to be upgraded: 2
            Number of packages to be reinstalled: 2

            The process will require 14 MiB more space.
            22 MiB to be downloaded.
            """))

        with patch.dict(pkgng.__salt__, {'cmd.run_stdout': pkg_cmd}):

            result = pkgng.list_upgrades(refresh=False)
            self.assertDictEqual(result, {
                'pkga': '1.1',
                'pkgb': '2.1',
                'pkgc': '3.1',
                'pkgd': '4.1'
            })
            pkg_cmd.assert_called_with(
                ['pkg', 'upgrade', '--dry-run', '--quiet', '--no-repo-update'],
                output_loglevel='trace',
                python_shell=False,
                ignore_retcode=True)
Ejemplo n.º 12
0
 def test_examine_quiet(self):
     '''
     Test for mdadm_raid.examine
     '''
     mock = MagicMock(return_value='')
     with patch.dict(mdadm.__salt__, {'cmd.run_stdout': mock}):
         self.assertEqual(mdadm.examine('/dev/md0', quiet=True), {})
         mock.assert_called_with('mdadm -Y -E /dev/md0', ignore_retcode=True,
                                 python_shell=False)
Ejemplo n.º 13
0
    def test_get_virtualenv_version_from_shell(self):
        with ForceImportErrorOn('virtualenv'):

            # ----- virtualenv binary not available ------------------------->
            mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
            with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
                self.assertRaises(
                    CommandExecutionError,
                    virtualenv_mod.create,
                    '/tmp/foo',
                )
            # <---- virtualenv binary not available --------------------------

            # ----- virtualenv binary present but > 0 exit code ------------->
            mock = MagicMock(side_effect=[
                {'retcode': 1, 'stdout': '', 'stderr': 'This is an error'},
                {'retcode': 0, 'stdout': ''}
            ])
            with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
                self.assertRaises(
                    CommandExecutionError,
                    virtualenv_mod.create,
                    '/tmp/foo',
                    venv_bin='virtualenv',
                )
            # <---- virtualenv binary present but > 0 exit code --------------

            # ----- virtualenv binary returns 1.9.1 as its version --------->
            mock = MagicMock(side_effect=[
                {'retcode': 0, 'stdout': '1.9.1'},
                {'retcode': 0, 'stdout': ''}
            ])
            with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
                virtualenv_mod.create(
                    '/tmp/foo', never_download=True
                )
                mock.assert_called_with(
                    ['virtualenv', '--never-download', '/tmp/foo'],
                    runas=None,
                    python_shell=False
                )
            # <---- virtualenv binary returns 1.9.1 as its version ----------

            # ----- virtualenv binary returns 1.10rc1 as its version ------->
            mock = MagicMock(side_effect=[
                {'retcode': 0, 'stdout': '1.10rc1'},
                {'retcode': 0, 'stdout': ''}
            ])
            with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
                virtualenv_mod.create(
                    '/tmp/foo', never_download=True
                )
                mock.assert_called_with(
                    ['virtualenv', '/tmp/foo'],
                    runas=None,
                    python_shell=False
                )
Ejemplo n.º 14
0
    def test_pvdisplay(self):
        """
        Tests information about the physical volume(s)
        """
        mock = MagicMock(return_value={"retcode": 1})
        with patch.dict(linux_lvm.__salt__, {"cmd.run_all": mock}):
            self.assertDictEqual(linux_lvm.pvdisplay(), {})

        mock = MagicMock(return_value={"retcode": 1})
        with patch.dict(linux_lvm.__salt__, {"cmd.run_all": mock}):
            self.assertDictEqual(linux_lvm.pvdisplay(quiet=True), {})
            mock.assert_called_with(
                ["pvdisplay", "-c"], ignore_retcode=True, python_shell=False
            )

        mock = MagicMock(return_value={"retcode": 0, "stdout": "A:B:C:D:E:F:G:H:I:J:K"})
        with patch.dict(linux_lvm.__salt__, {"cmd.run_all": mock}):
            self.assertDictEqual(
                linux_lvm.pvdisplay(),
                {
                    "A": {
                        "Allocated Physical Extents": "K",
                        "Current Logical Volumes Here": "G",
                        "Free Physical Extents": "J",
                        "Internal Physical Volume Number": "D",
                        "Physical Extent Size (kB)": "H",
                        "Physical Volume (not) Allocatable": "F",
                        "Physical Volume Device": "A",
                        "Physical Volume Size (kB)": "C",
                        "Physical Volume Status": "E",
                        "Total Physical Extents": "I",
                        "Volume Group Name": "B",
                    }
                },
            )

            mockpath = MagicMock(return_value="Z")
            with patch.object(os.path, "realpath", mockpath):
                self.assertDictEqual(
                    linux_lvm.pvdisplay(real=True),
                    {
                        "Z": {
                            "Allocated Physical Extents": "K",
                            "Current Logical Volumes Here": "G",
                            "Free Physical Extents": "J",
                            "Internal Physical Volume Number": "D",
                            "Physical Extent Size (kB)": "H",
                            "Physical Volume (not) Allocatable": "F",
                            "Physical Volume Device": "A",
                            "Physical Volume Size (kB)": "C",
                            "Physical Volume Status": "E",
                            "Real Physical Volume Device": "Z",
                            "Total Physical Extents": "I",
                            "Volume Group Name": "B",
                        }
                    },
                )
Ejemplo n.º 15
0
def test_defined_update_error(test):
    """
    defined state test, with error during the update.
    """
    with patch.dict(virt.__opts__, {"test": test}):
        init_mock = MagicMock(return_value=True)
        update_mock = MagicMock(return_value={
            "definition": True,
            "cpu": False,
            "errors": ["some error"]
        })
        with patch.dict(
                virt.__salt__,
            {
                "virt.list_domains": MagicMock(return_value=["myvm"]),
                "virt.update": update_mock,
                "virt.init": init_mock,
            },
        ):
            assert virt.defined("myvm", cpu=2, boot_dev="cdrom hd") == {
                "name": "myvm",
                "changes": {
                    "myvm": {
                        "definition": True,
                        "cpu": False,
                        "errors": ["some error"],
                    }
                },
                "result": True if not test else None,
                "comment": "Domain myvm updated with live update(s) failures",
            }
            init_mock.assert_not_called()
            update_mock.assert_called_with(
                "myvm",
                cpu=2,
                boot_dev="cdrom hd",
                mem=None,
                disk_profile=None,
                disks=None,
                nic_profile=None,
                interfaces=None,
                graphics=None,
                live=True,
                connection=None,
                username=None,
                password=None,
                boot=None,
                numatune=None,
                test=test,
                hypervisor_features=None,
                clock=None,
                serials=None,
                consoles=None,
                stop_on_reboot=False,
                host_devices=None,
            )
Ejemplo n.º 16
0
def test_update_an_existent_host_proxy(basic_host_configuration,
                                       existing_host_responses):
    """
    Tests if the proxy of a host is updated to a new one.
    This also tests if a proxy can be added, as a host without a proxy
    have the proxy_hostid property equals zero.
    """
    host, groups, interfaces, kwargs, _ = basic_host_configuration
    (
        host_get_output,
        hostgroup_get_output,
        hostinterface_get_output,
        host_inventory_get_output,
    ) = existing_host_responses

    kwargs["proxy_host"] = 10356
    host_exists_output = True
    host_update_output = "31337"
    run_query_output = [{"proxyid": "10356"}]

    ret = {
        "changes": {
            "proxy_hostid": "10356"
        },
        "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)
    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_get": mock_host_get,
            "zabbix.hostinterface_get": mock_hostinterface_get,
            "zabbix.host_inventory_get": mock_host_inventory_get,
            "zabbix.host_update": mock_host_update,
            "zabbix.run_query": mock_run_query,
        },
    ):
        assert zabbix_host.present(host, groups, interfaces, **kwargs) == ret
        mock_host_update.assert_called_with(
            "31337",
            proxy_hostid="10356",
            _connection_password="******",
            _connection_url="http://XXXXXXXXX/zabbix/api_jsonrpc.php",
            _connection_user="******",
        )
Ejemplo n.º 17
0
    def test_pvdisplay(self):
        '''
        Tests information about the physical volume(s)
        '''
        mock = MagicMock(return_value={'retcode': 1})
        with patch.dict(linux_lvm.__salt__, {'cmd.run_all': mock}):
            self.assertDictEqual(linux_lvm.pvdisplay(), {})

        mock = MagicMock(return_value={'retcode': 1})
        with patch.dict(linux_lvm.__salt__, {'cmd.run_all': mock}):
            self.assertDictEqual(linux_lvm.pvdisplay(quiet=True), {})
            mock.assert_called_with(['pvdisplay', '-c'],
                                    ignore_retcode=True,
                                    python_shell=False)

        mock = MagicMock(return_value={
            'retcode': 0,
            'stdout': 'A:B:C:D:E:F:G:H:I:J:K'
        })
        with patch.dict(linux_lvm.__salt__, {'cmd.run_all': mock}):
            self.assertDictEqual(
                linux_lvm.pvdisplay(), {
                    'A': {
                        'Allocated Physical Extents': 'K',
                        'Current Logical Volumes Here': 'G',
                        'Free Physical Extents': 'J',
                        'Internal Physical Volume Number': 'D',
                        'Physical Extent Size (kB)': 'H',
                        'Physical Volume (not) Allocatable': 'F',
                        'Physical Volume Device': 'A',
                        'Physical Volume Size (kB)': 'C',
                        'Physical Volume Status': 'E',
                        'Total Physical Extents': 'I',
                        'Volume Group Name': 'B'
                    }
                })

            mockpath = MagicMock(return_value='Z')
            with patch.object(os.path, 'realpath', mockpath):
                self.assertDictEqual(
                    linux_lvm.pvdisplay(real=True), {
                        'Z': {
                            'Allocated Physical Extents': 'K',
                            'Current Logical Volumes Here': 'G',
                            'Free Physical Extents': 'J',
                            'Internal Physical Volume Number': 'D',
                            'Physical Extent Size (kB)': 'H',
                            'Physical Volume (not) Allocatable': 'F',
                            'Physical Volume Device': 'A',
                            'Physical Volume Size (kB)': 'C',
                            'Physical Volume Status': 'E',
                            'Real Physical Volume Device': 'Z',
                            'Total Physical Extents': 'I',
                            'Volume Group Name': 'B'
                        }
                    })
Ejemplo n.º 18
0
 def test_examine_quiet(self):
     """
     Test for mdadm_raid.examine
     """
     mock = MagicMock(return_value="")
     with patch.dict(mdadm.__salt__, {"cmd.run_stdout": mock}):
         self.assertEqual(mdadm.examine("/dev/md0", quiet=True), {})
         mock.assert_called_with("mdadm -Y -E /dev/md0",
                                 ignore_retcode=True,
                                 python_shell=False)
Ejemplo n.º 19
0
def test_create_a_new_host_with_multiple_groups(basic_host_configuration):
    """
    This test creates a host with multiple groups, mixing names and IDs.
    """
    host, _, interfaces, kwargs, ret = basic_host_configuration
    groups = ["Testing Group", 15, "Tested Group"]

    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
        mock_host_create.assert_called_with(
            "new_host",
            [16, 15, 17],
            [{
                "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="0",
            visible_name=None,
        )
Ejemplo n.º 20
0
def test_create_a_new_host_with_additional_parameters(
        basic_host_configuration):
    """
    Tests if additional parameters, like "description" or "inventory_mode"
    are being properly passed to host_create. Also, checks if invalid
    parameters are filtered out.
    """
    host, groups, interfaces, kwargs, ret = basic_host_configuration
    kwargs["visible_name"] = "Visible Name"
    kwargs["description"] = "An amazing test host entry"
    kwargs["not_valid_property"] = "This should be removed"
    kwargs["inventory_mode"] = "0"

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

    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)
    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
        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="******",
            description="An amazing test host entry",
            inventory={},
            inventory_mode="0",
            proxy_hostid="0",
            visible_name="Visible Name",
        )
Ejemplo n.º 21
0
def test_network_running_stopped(test):
    """
    network_running state test cases, network stopped case.
    """
    with patch.dict(virt.__opts__, {"test": test}):
        define_mock = MagicMock(return_value=True)
        start_mock = MagicMock(return_value=True)
        update_mock = MagicMock(return_value=False)
        with patch.dict(
            virt.__salt__,
            {  # pylint: disable=no-member
                "virt.network_info": MagicMock(
                    return_value={"mynet": {"active": False, "autostart": True}}
                ),
                "virt.network_start": start_mock,
                "virt.network_define": define_mock,
                "virt.network_update": update_mock,
            },
        ):
            assert virt.network_running(
                "mynet",
                "br2",
                "bridge",
                connection="myconnection",
                username="******",
                password="******",
            ) == {
                "name": "mynet",
                "changes": {
                    "mynet": "Network started"
                },
                "comment": "Network mynet unchanged and started",
                "result": None if test else True,
            }
            assert update_mock.call_args_list == [
                network_update_call(
                    "mynet",
                    "br2",
                    "bridge",
                    connection="myconnection",
                    username="******",
                    password="******",
                    test=True,
                )
            ]
            if not test:
                start_mock.assert_called_with(
                    "mynet",
                    connection="myconnection",
                    username="******",
                    password="******",
                )
            else:
                start_mock.assert_not_called()
Ejemplo n.º 22
0
def test_running_update_error():
    """
    running state test, update an existing guest raising an error
    """
    with patch.dict(virt.__opts__, {"test": False}):
        update_mock = MagicMock(return_value={
            "definition": True,
            "cpu": False,
            "errors": ["some error"]
        })
        with patch.dict(
                virt.__salt__,
            {
                "virt.vm_state": MagicMock(return_value={"myvm": "running"}),
                "virt.update": update_mock,
                "virt.list_domains": MagicMock(return_value=["myvm"]),
            },
        ):
            assert virt.running("myvm", cpu=2) == {
                "name": "myvm",
                "changes": {
                    "myvm": {
                        "definition": True,
                        "cpu": False,
                        "errors": ["some error"],
                    }
                },
                "result": True,
                "comment": "Domain myvm updated with live update(s) failures",
            }
            update_mock.assert_called_with(
                "myvm",
                cpu=2,
                mem=None,
                disk_profile=None,
                disks=None,
                nic_profile=None,
                interfaces=None,
                graphics=None,
                live=True,
                connection=None,
                username=None,
                password=None,
                boot=None,
                numatune=None,
                test=False,
                boot_dev=None,
                hypervisor_features=None,
                clock=None,
                serials=None,
                consoles=None,
                stop_on_reboot=False,
                host_devices=None,
            )
Ejemplo n.º 23
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="******",
        )
Ejemplo n.º 24
0
 def test_shutdown_openbsd(self):
     """
     Test to shutdown a running OpenBSD system
     """
     cmd_mock = MagicMock(return_value="A")
     with patch.dict(system.__salt__, {"cmd.run": cmd_mock}), patch(
         "salt.utils.platform.is_freebsd", MagicMock(return_value=False)
     ), patch("salt.utils.platform.is_netbsd", MagicMock(return_value=False)), patch(
         "salt.utils.platform.is_openbsd", MagicMock(return_value=True)
     ):
         self.assertEqual(system.shutdown(), "A")
     cmd_mock.assert_called_with(["shutdown", "-p", "now"], python_shell=False)
Ejemplo n.º 25
0
def test_check_checklibs():
    """
    Test pkgng.check to regenerate the library dependency metadata
    """
    pkg_cmd = MagicMock(return_value="")

    with patch.dict(pkgng.__salt__, {"cmd.run": pkg_cmd}):
        result = pkgng.check(checklibs=True)
        assert result == ""
        pkg_cmd.assert_called_with(
            ["pkg", "check", "-B"], output_loglevel="trace", python_shell=False,
        )
Ejemplo n.º 26
0
def test_autoremove_with_dryrun():
    """
    Test pkgng.autoremove with dryrun argument
    """
    pkg_cmd = MagicMock(return_value="")

    with patch.dict(pkgng.__salt__, {"cmd.run": pkg_cmd}):
        result = pkgng.autoremove(dryrun=True)
        assert result == ""
        pkg_cmd.assert_called_with(
            ["pkg", "autoremove", "-n"], output_loglevel="trace", python_shell=False,
        )
Ejemplo n.º 27
0
def test_show_current():
    mock = MagicMock(return_value="/etc/alternatives/salt")
    with patch("salt.utils.path.readlink", mock):
        ret = alternatives.show_current("better-world")
        assert "/etc/alternatives/salt" == ret
        mock.assert_called_once_with("/etc/alternatives/better-world")

        with TstSuiteLoggingHandler() as handler:
            mock.side_effect = OSError("Hell was not found!!!")
            assert not alternatives.show_current("hell")
            mock.assert_called_with("/etc/alternatives/hell")
            assert "ERROR:alternative: hell does not exist" in handler.messages
Ejemplo n.º 28
0
 def test_get_tok_with_expire_before_current_time_should_remove_token(self):
     fake_get_token = MagicMock(return_value={"expire": time.time() - 1})
     patch_opts = patch.dict(self.lauth.opts, {"eauth_tokens": "testfs"})
     patch_get_token = patch.dict(
         self.lauth.tokens, {"testfs.get_token": fake_get_token},
     )
     mock_rm_token = MagicMock()
     patch_rm_token = patch.object(self.lauth, "rm_token", mock_rm_token)
     with patch_opts, patch_get_token, patch_rm_token:
         expected_token = "fnord"
         self.lauth.get_tok(expected_token)
         mock_rm_token.assert_called_with(expected_token)
Ejemplo n.º 29
0
 def test_get_tok_with_no_expiration_should_remove_bad_token(self):
     fake_get_token = MagicMock(return_value={"no_expire_here": "Nope"})
     patch_opts = patch.dict(self.lauth.opts, {"eauth_tokens": "testfs"})
     patch_get_token = patch.dict(
         self.lauth.tokens, {"testfs.get_token": fake_get_token},
     )
     mock_rm_token = MagicMock()
     patch_rm_token = patch.object(self.lauth, "rm_token", mock_rm_token)
     with patch_opts, patch_get_token, patch_rm_token:
         expected_token = "fnord"
         self.lauth.get_tok(expected_token)
         mock_rm_token.assert_called_with(expected_token)
Ejemplo n.º 30
0
 def test_get_tok_with_broken_file_will_remove_bad_token(self):
     fake_get_token = MagicMock(side_effect=SaltDeserializationError("hi"))
     patch_opts = patch.dict(self.lauth.opts, {"eauth_tokens": "testfs"})
     patch_get_token = patch.dict(
         self.lauth.tokens, {"testfs.get_token": fake_get_token},
     )
     mock_rm_token = MagicMock()
     patch_rm_token = patch.object(self.lauth, "rm_token", mock_rm_token)
     with patch_opts, patch_get_token, patch_rm_token:
         expected_token = "fnord"
         self.lauth.get_tok(expected_token)
         mock_rm_token.assert_called_with(expected_token)