Exemple #1
0
 def test_get_hostname(self):
     """
     Test for Get hostname
     """
     with patch.object(socket, "gethostname", return_value="A"):
         self.assertEqual(network.get_hostname(), "A")
def has_not_spwd():
    with patch.object(solaris_shadow, "HAS_SPWD", False):
        yield
Exemple #3
0
    def test_get_rule_handle(self):
        """
        Test if it get the handle for a particular rule
        """
        self.assertEqual(
            nftables.get_rule_handle(),
            {
                "result": False,
                "comment": "Chain needs to be specified"
            },
        )

        self.assertEqual(
            nftables.get_rule_handle(chain="input"),
            {
                "result": False,
                "comment": "Rule needs to be specified"
            },
        )

        _ru = "input tcp dport 22 log accept"
        ret = {
            "result": False,
            "comment": "Table filter in family ipv4 does not exist"
        }
        mock = MagicMock(return_value="")
        with patch.dict(nftables.__salt__, {"cmd.run": mock}):
            self.assertEqual(nftables.get_rule_handle(chain="input", rule=_ru),
                             ret)

        ret = {
            "result": False,
            "comment":
            "Chain input in table filter in family ipv4 does not exist",
        }
        mock = MagicMock(return_value="table ip filter")
        with patch.dict(nftables.__salt__, {"cmd.run": mock}):
            self.assertEqual(nftables.get_rule_handle(chain="input", rule=_ru),
                             ret)

        ret = {
            "result":
            False,
            "comment":
            ("Rule input tcp dport 22 log accept chain"
             " input in table filter in family ipv4 does not exist"),
        }
        ret1 = {
            "result": False,
            "comment": "Could not find rule input tcp dport 22 log accept",
        }
        with patch.object(
                nftables,
                "check_table",
                MagicMock(return_value={
                    "result": True,
                    "comment": ""
                }),
        ):
            with patch.object(
                    nftables,
                    "check_chain",
                    MagicMock(return_value={
                        "result": True,
                        "comment": ""
                    }),
            ):
                _ret1 = {
                    "result":
                    False,
                    "comment": ("Rule input tcp dport 22 log accept"
                                " chain input in table filter in"
                                " family ipv4 does not exist"),
                }
                _ret2 = {"result": True, "comment": ""}
                with patch.object(nftables, "check",
                                  MagicMock(side_effect=[_ret1, _ret2])):
                    self.assertEqual(
                        nftables.get_rule_handle(chain="input", rule=_ru), ret)

                    _ru = "input tcp dport 22 log accept"
                    mock = MagicMock(return_value="")
                    with patch.dict(nftables.__salt__, {"cmd.run": mock}):
                        self.assertEqual(
                            nftables.get_rule_handle(chain="input", rule=_ru),
                            ret1)
Exemple #4
0
    def test_build_interface(self):
        '''
        Test to build an interface script for a network interface.
        '''
        with patch.dict(rh_ip.__grains__, {
                'os': 'Fedora',
                'osmajorrelease': 26
        }):
            with patch.object(rh_ip, '_raise_error_iface', return_value=None):
                self.assertRaises(AttributeError, rh_ip.build_interface,
                                  'iface', 'slave', True)

                with patch.dict(rh_ip.__salt__,
                                {'network.interfaces': lambda: {
                                    'eth': True
                                }}):
                    self.assertRaises(AttributeError,
                                      rh_ip.build_interface,
                                      'iface',
                                      'eth',
                                      True,
                                      netmask='255.255.255.255',
                                      prefix=32,
                                      test=True)
                    self.assertRaises(AttributeError,
                                      rh_ip.build_interface,
                                      'iface',
                                      'eth',
                                      True,
                                      ipaddrs=['A'],
                                      test=True)
                    self.assertRaises(AttributeError,
                                      rh_ip.build_interface,
                                      'iface',
                                      'eth',
                                      True,
                                      ipv6addrs=['A'],
                                      test=True)

        for osrelease in range(5, 8):
            with patch.dict(rh_ip.__grains__, {
                    'os': 'RedHat',
                    'osrelease': six.text_type(osrelease)
            }):
                with patch.object(rh_ip,
                                  '_raise_error_iface',
                                  return_value=None):
                    with patch.object(rh_ip, '_parse_settings_bond',
                                      MagicMock()):
                        mock = jinja2.exceptions.TemplateNotFound('foo')
                        with patch.object(jinja2.Environment, 'get_template',
                                          MagicMock(side_effect=mock)):
                            self.assertEqual(
                                rh_ip.build_interface('iface', 'vlan', True),
                                '')

                        with patch.object(rh_ip,
                                          '_read_temp',
                                          return_value='A'):
                            with patch.object(jinja2.Environment,
                                              'get_template', MagicMock()):
                                self.assertEqual(
                                    rh_ip.build_interface('iface',
                                                          'vlan',
                                                          True,
                                                          test='A'), 'A')

                                with patch.object(rh_ip,
                                                  '_write_file_iface',
                                                  return_value=None):
                                    with patch.object(os.path,
                                                      'join',
                                                      return_value='A'):
                                        with patch.object(rh_ip,
                                                          '_read_file',
                                                          return_value='A'):
                                            self.assertEqual(
                                                rh_ip.build_interface(
                                                    'iface', 'vlan', True),
                                                'A')
                                            if osrelease > 6:
                                                with patch.dict(
                                                        rh_ip.__salt__,
                                                    {
                                                        'network.interfaces':
                                                        lambda: {
                                                            'eth': True
                                                        }
                                                    }):
                                                    self.assertEqual(
                                                        rh_ip.build_interface(
                                                            'iface',
                                                            'eth',
                                                            True,
                                                            ipaddrs=[
                                                                '127.0.0.1/8'
                                                            ]), 'A')
                                                    self.assertEqual(
                                                        rh_ip.build_interface(
                                                            'iface',
                                                            'eth',
                                                            True,
                                                            ipv6addrs=[
                                                                'fc00::1/128'
                                                            ]), 'A')
    def _mask_unmask(self, action, runtime):
        '''
        Common code for mask/unmask tests
        '''
        # We want the traceback if the function name can't be found in the
        # systemd execution module, so don't provide a fallback value for the
        # call to getattr() here.
        func = getattr(systemd, action)
        # Remove trailing _ in "unmask_"
        action = action.rstrip('_').replace('_', '-')
        systemctl_command = ['systemctl', action]
        if runtime:
            systemctl_command.append('--runtime')
        systemctl_command.append(self.unit_name + '.service')
        scope_prefix = ['systemd-run', '--scope']

        args = [self.unit_name, runtime]

        masked_mock = self.mock_true if action == 'unmask' else self.mock_false

        with patch.object(systemd, '_check_for_unit_changes', self.mock_none):
            if action == 'unmask':
                mock_not_run = MagicMock(return_value={'retcode': 0,
                                                       'stdout': '',
                                                       'stderr': '',
                                                       'pid': 12345})
                with patch.dict(systemd.__salt__, {'cmd.run_all': mock_not_run}):
                    with patch.object(systemd, 'masked', self.mock_false):
                        # Test not masked (should take no action and return True)
                        self.assertTrue(systemd.unmask_(self.unit_name))
                        # Also should not have called cmd.run_all
                        self.assertTrue(mock_not_run.call_count == 0)

            with patch.object(systemd, 'masked', masked_mock):

                # Has scopes available
                with patch.object(salt.utils.systemd, 'has_scope', self.mock_true):

                    # Scope enabled, successful
                    with patch.dict(
                            systemd.__salt__,
                            {'config.get': self.mock_true,
                             'cmd.run_all': self.mock_run_all_success}):
                        ret = func(*args)
                        self.assertTrue(ret)
                        self.mock_run_all_success.assert_called_with(
                            scope_prefix + systemctl_command,
                            python_shell=False,
                            redirect_stderr=True)

                    # Scope enabled, failed
                    with patch.dict(
                            systemd.__salt__,
                            {'config.get': self.mock_true,
                             'cmd.run_all': self.mock_run_all_failure}):
                        self.assertRaises(
                            CommandExecutionError,
                            func, *args)
                        self.mock_run_all_failure.assert_called_with(
                            scope_prefix + systemctl_command,
                            python_shell=False,
                            redirect_stderr=True)

                    # Scope disabled, successful
                    with patch.dict(
                            systemd.__salt__,
                            {'config.get': self.mock_false,
                             'cmd.run_all': self.mock_run_all_success}):
                        ret = func(*args)
                        self.assertTrue(ret)
                        self.mock_run_all_success.assert_called_with(
                            systemctl_command,
                            python_shell=False,
                            redirect_stderr=True)

                    # Scope disabled, failed
                    with patch.dict(
                            systemd.__salt__,
                            {'config.get': self.mock_false,
                             'cmd.run_all': self.mock_run_all_failure}):
                        self.assertRaises(
                            CommandExecutionError,
                            func, *args)
                        self.mock_run_all_failure.assert_called_with(
                            systemctl_command,
                            python_shell=False,
                            redirect_stderr=True)

                # Does not have scopes available
                with patch.object(salt.utils.systemd, 'has_scope', self.mock_false):

                    # The results should be the same irrespective of
                    # whether or not scope is enabled, since scope is not
                    # available, so we repeat the below tests with it both
                    # enabled and disabled.
                    for scope_mock in (self.mock_true, self.mock_false):

                        # Successful
                        with patch.dict(
                                systemd.__salt__,
                                {'config.get': scope_mock,
                                 'cmd.run_all': self.mock_run_all_success}):
                            ret = func(*args)
                            self.assertTrue(ret)
                            self.mock_run_all_success.assert_called_with(
                                systemctl_command,
                                python_shell=False,
                                redirect_stderr=True)

                        # Failed
                        with patch.dict(
                                systemd.__salt__,
                                {'config.get': scope_mock,
                                 'cmd.run_all': self.mock_run_all_failure}):
                            self.assertRaises(
                                CommandExecutionError,
                                func, *args)
                            self.mock_run_all_failure.assert_called_with(
                                systemctl_command,
                                python_shell=False,
                                redirect_stderr=True)
Exemple #6
0
    def test_set_policy(self):
        """
            Test to sets the default policy for iptables firewall tables
        """
        ret = {"name": "salt", "changes": {}, "result": True, "comment": ""}

        mock = MagicMock(return_value=[])
        with patch.object(iptables, "_STATE_INTERNAL_KEYWORDS", mock):
            mock = MagicMock(return_value="stack")
            with patch.dict(iptables.__salt__, {"iptables.get_policy": mock}):
                ret.update({
                    "comment":
                    "iptables default policy for chain"
                    "  on table  for ipv4 already set to stack"
                })
                self.assertDictEqual(
                    iptables.set_policy("salt",
                                        table="",
                                        chain="",
                                        policy="stack"), ret)

                with patch.dict(iptables.__opts__, {"test": True}):
                    ret.update({
                        "comment":
                        "iptables default policy for chain"
                        "  on table  for ipv4 needs to be set"
                        " to sal",
                        "result":
                        None,
                    })
                    self.assertDictEqual(
                        iptables.set_policy("salt",
                                            table="",
                                            chain="",
                                            policy="sal"),
                        ret,
                    )

                with patch.dict(iptables.__opts__, {"test": False}):
                    mock = MagicMock(side_effect=[False, True])
                    with patch.dict(iptables.__salt__,
                                    {"iptables.set_policy": mock}):
                        ret.update({
                            "changes": {
                                "locale": "salt"
                            },
                            "comment": "Set default policy for"
                            "  to sal family ipv4",
                            "result": True,
                        })
                        self.assertDictEqual(
                            iptables.set_policy("salt",
                                                table="",
                                                chain="",
                                                policy="sal"),
                            ret,
                        )

                        ret.update({
                            "comment": "Failed to set iptables"
                            " default policy",
                            "result": False,
                            "changes": {},
                        })
                        self.assertDictEqual(
                            iptables.set_policy("salt",
                                                table="",
                                                chain="",
                                                policy="sal"),
                            ret,
                        )
def test_serialize_into_managed_file():
    """
    Test to serializes dataset and store it into managed file.
    """
    name = "/etc/dummy/package.json"

    ret = {"name": name, "result": False, "comment": "", "changes": {}}

    comt = "Must provide name to file.serialize"
    ret.update({"comment": comt, "name": ""})
    assert filestate.serialize("") == ret

    mock_t = MagicMock(return_value=True)
    mock_f = MagicMock(return_value=False)
    with patch.object(os.path, "isfile", mock_f):
        comt = "File {} is not present and is not set for creation".format(
            name)
        ret.update({"comment": comt, "name": name, "result": True})
        assert filestate.serialize(name, create=False) == ret

    comt = "Only one of 'dataset' and 'dataset_pillar' is permitted"
    ret.update({"comment": comt, "result": False})
    assert filestate.serialize(name, dataset=True, dataset_pillar=True) == ret

    comt = "Neither 'dataset' nor 'dataset_pillar' was defined"
    ret.update({"comment": comt, "result": False})
    assert filestate.serialize(name) == ret

    with patch.object(os.path, "isfile", mock_t):
        comt = "merge_if_exists is not supported for the python serializer"
        ret.update({"comment": comt, "result": False})
        assert (filestate.serialize(name,
                                    dataset=True,
                                    merge_if_exists=True,
                                    formatter="python") == ret)

    comt = ("The a serializer could not be found. "
            "It either does not exist or its prerequisites are not installed.")
    ret.update({"comment": comt, "result": False})
    assert filestate.serialize(name, dataset=True, formatter="A") == ret
    mock_changes = MagicMock(return_value=True)
    mock_no_changes = MagicMock(return_value=False)

    # __opts__['test']=True with changes
    with patch.dict(filestate.__salt__,
                    {"file.check_managed_changes": mock_changes}):
        with patch.dict(filestate.__opts__, {"test": True}):
            comt = "Dataset will be serialized and stored into {}".format(name)
            ret.update({"comment": comt, "result": None, "changes": True})
            assert filestate.serialize(name, dataset=True,
                                       formatter="python") == ret

    # __opts__['test']=True without changes
    with patch.dict(filestate.__salt__,
                    {"file.check_managed_changes": mock_no_changes}):
        with patch.dict(filestate.__opts__, {"test": True}):
            comt = "The file {} is in the correct state".format(name)
            ret.update({"comment": comt, "result": True, "changes": False})
            assert filestate.serialize(name, dataset=True,
                                       formatter="python") == ret

    mock = MagicMock(return_value=ret)
    with patch.dict(filestate.__opts__, {"test": False}):
        with patch.dict(filestate.__salt__, {"file.manage_file": mock}):
            comt = "Dataset will be serialized and stored into {}".format(name)
            ret.update({"comment": comt, "result": None})
            assert filestate.serialize(name, dataset=True,
                                       formatter="python") == ret
Exemple #8
0
    def test_watch(self):
        with patch('etcd.Client', autospec=True) as client_mock:
            client = etcd_util.EtcdClient({})

            with patch.object(client, 'read', autospec=True) as mock:
                mock.return_value = MagicMock(value='stack',
                                              key='/some-key',
                                              modifiedIndex=1,
                                              dir=False)
                self.assertDictEqual(
                    client.watch('/some-key'), {
                        'value': 'stack',
                        'key': '/some-key',
                        'mIndex': 1,
                        'changed': True,
                        'dir': False
                    })
                mock.assert_called_with('/some-key',
                                        wait=True,
                                        recursive=False,
                                        timeout=0,
                                        waitIndex=None)

                mock.side_effect = iter(
                    [etcd_util.EtcdUtilWatchTimeout, mock.return_value])
                self.assertDictEqual(
                    client.watch('/some-key'), {
                        'value': 'stack',
                        'changed': False,
                        'mIndex': 1,
                        'key': '/some-key',
                        'dir': False
                    })

                mock.side_effect = iter(
                    [etcd_util.EtcdUtilWatchTimeout, etcd.EtcdKeyNotFound])
                self.assertEqual(
                    client.watch('/some-key'), {
                        'value': None,
                        'changed': False,
                        'mIndex': 0,
                        'key': '/some-key',
                        'dir': False
                    })

                mock.side_effect = iter(
                    [etcd_util.EtcdUtilWatchTimeout, ValueError])
                self.assertEqual(client.watch('/some-key'), {})

                mock.side_effect = None
                mock.return_value = MagicMock(value='stack',
                                              key='/some-key',
                                              modifiedIndex=1,
                                              dir=True)
                self.assertDictEqual(
                    client.watch('/some-dir',
                                 recurse=True,
                                 timeout=5,
                                 index=10), {
                                     'value': 'stack',
                                     'key': '/some-key',
                                     'mIndex': 1,
                                     'changed': True,
                                     'dir': True
                                 })
                mock.assert_called_with('/some-dir',
                                        wait=True,
                                        recursive=True,
                                        timeout=5,
                                        waitIndex=10)

                # iter(list(Exception)) works correctly with both mock<1.1 and mock>=1.1
                mock.side_effect = iter([MaxRetryError(None, None)])
                self.assertEqual(client.watch('/some-key'), {})

                mock.side_effect = iter([etcd.EtcdConnectionFailed()])
                self.assertEqual(client.watch('/some-key'), {})

                mock.side_effect = None
                mock.return_value = None
                self.assertEqual(client.watch('/some-key'), {})
Exemple #9
0
def test_present():
    """
    Test to ensure that the named user is present with
    the specified properties
    """
    ret = {"name": "salt", "changes": {}, "result": False, "comment": ""}
    mock_false = MagicMock(return_value=False)
    mock_empty_list = MagicMock(return_value=[])
    with patch.dict(user.__grains__, {"kernel": "Linux"}):
        with patch.dict(
                user.__salt__,
            {
                "group.info": mock_false,
                "user.info": mock_empty_list,
                "user.chkey": mock_empty_list,
                "user.add": mock_false,
            },
        ):
            ret.update(
                {"comment": "The following group(s) are not present: salt"})
            assert user.present("salt", groups=["salt"]) == ret

            mock_false = MagicMock(side_effect=[
                {
                    "key": "value"
                },
                {
                    "key": "value"
                },
                {
                    "key": "value"
                },
                False,
                False,
            ])
            with patch.object(user, "_changes", mock_false):
                with patch.dict(user.__opts__, {"test": True}):
                    ret.update({
                        "comment":
                        ("The following user attributes are set to be changed:\n"
                         "key: value\n"),
                        "result":
                        None,
                    })
                    assert user.present("salt") == ret

                with patch.dict(user.__opts__, {"test": False}):
                    comment = "These values could not be changed: {!r}".format(
                        {"key": "value"})
                    ret.update({"comment": comment, "result": False})
                    assert user.present("salt") == ret

                    with patch.dict(user.__opts__, {"test": True}):
                        ret.update({
                            "comment": "User salt set to be added",
                            "result": None
                        })
                        assert user.present("salt") == ret

                    with patch.dict(user.__opts__, {"test": False}):
                        ret.update({
                            "comment": "Failed to create new user salt",
                            "result": False,
                        })
                        assert user.present("salt") == ret
Exemple #10
0
    def test_usergroup_list(self):
        """
        query_submitted = {"params": {"output": "extend"}, "jsonrpc": "2.0", "id": 0,
        "auth": "4bc366bc7803c07e80f15b1bc14dc61f", "method": "usergroup.get"}
        """

        module_return = [
            {
                "usrgrpid": "7",
                "gui_access": "0",
                "debug_mode": "0",
                "name": "Zabbix administrators",
                "users_status": "0",
            },
            {
                "usrgrpid": "8",
                "gui_access": "0",
                "debug_mode": "0",
                "name": "Guests",
                "users_status": "0",
            },
            {
                "usrgrpid": "9",
                "gui_access": "0",
                "debug_mode": "0",
                "name": "Disabled",
                "users_status": "1",
            },
            {
                "usrgrpid": "11",
                "gui_access": "0",
                "debug_mode": "1",
                "name": "Enabled debug mode",
                "users_status": "0",
            },
            {
                "usrgrpid": "12",
                "gui_access": "2",
                "debug_mode": "0",
                "name": "No access to the frontend",
                "users_status": "0",
            },
            {
                "usrgrpid": "13",
                "gui_access": "0",
                "debug_mode": "0",
                "name": "testgroup",
                "users_status": "0",
            },
        ]
        # pylint: disable=E8128
        query_return = {
            "jsonrpc": "2.0",
            "result": [
                {
                    "usrgrpid": "7",
                    "name": "Zabbix administrators",
                    "gui_access": "0",
                    "users_status": "0",
                    "debug_mode": "0",
                },
                {
                    "usrgrpid": "8",
                    "name": "Guests",
                    "gui_access": "0",
                    "users_status": "0",
                    "debug_mode": "0",
                },
                {
                    "usrgrpid": "9",
                    "name": "Disabled",
                    "gui_access": "0",
                    "users_status": "1",
                    "debug_mode": "0",
                },
                {
                    "usrgrpid": "11",
                    "name": "Enabled debug mode",
                    "gui_access": "0",
                    "users_status": "0",
                    "debug_mode": "1",
                },
                {
                    "usrgrpid": "12",
                    "name": "No access to the frontend",
                    "gui_access": "2",
                    "users_status": "0",
                    "debug_mode": "0",
                },
                {
                    "usrgrpid": "13",
                    "name": "testgroup",
                    "gui_access": "0",
                    "users_status": "0",
                    "debug_mode": "0",
                },
            ],
            "id": 0,
        }

        with patch.object(zabbix, "_query", return_value=query_return):
            with patch.object(zabbix, "_login", return_value=CONN_ARGS):
                self.assertEqual(zabbix.usergroup_list(**CONN_ARGS), module_return)
Exemple #11
0
    def test_host_inventory_get(self):
        """
        test host_inventory_get
        """
        module_return = {
            "poc_2_email": "",
            "poc_2_phone_b": "",
            "site_country": "",
            "poc_2_screen": "",
            "poc_2_notes": "",
            "poc_1_screen": "",
            "hardware": "",
            "software_app_a": "",
            "software_app_b": "",
            "software_app_c": "",
            "software_app_d": "",
            "os_short": "",
            "site_zip": "",
            "poc_2_name": "",
            "os_full": "",
            "host_netmask": "",
            "host_router": "",
            "url_c": "",
            "date_hw_install": "",
            "poc_1_phone_b": "",
            "poc_1_phone_a": "",
            "poc_1_cell": "",
            "type_full": "",
            "location_lat": "",
            "vendor": "",
            "contact": "",
            "site_rack": "",
            "location": "",
            "poc_2_cell": "",
            "date_hw_expiry": "",
            "installer_name": "",
            "type": "",
            "contract_number": "",
            "deployment_status": "",
            "site_notes": "",
            "inventory_mode": "0",
            "oob_ip": "",
            "host_networks": "",
            "hardware_full": "",
            "poc_2_phone_a": "",
            "poc_1_name": "",
            "site_state": "",
            "chassis": "",
            "software_app_e": "",
            "site_address_b": "",
            "site_address_a": "",
            "date_hw_decomm": "",
            "date_hw_purchase": "",
            "location_lon": "",
            "hw_arch": "",
            "software_full": "",
            "asset_tag": "",
            "oob_router": "",
            "hostid": "10258",
            "poc_1_email": "",
            "name": "",
            "poc_1_notes": "",
            "serialno_b": "",
            "notes": "",
            "oob_netmask": "",
            "alias": "other thing",
            "tag": "",
            "macaddress_b": "",
            "macaddress_a": "",
            "site_city": "",
            "site_address_c": "",
            "model": "",
            "serialno_a": "",
            "os": "some",
            "url_b": "",
            "url_a": "",
            "software": "",
        }
        query_return = {
            "jsonrpc": "2.0",
            "result": [
                {
                    "hostid": "10258",
                    "proxy_hostid": "0",
                    "host": "master",
                    "status": "0",
                    "disable_until": "1517766661",
                    "error": (
                        "Get value from agent failed: cannot connect to"
                        " [[10.0.2.15]:10050]: [111] Connection refused"
                    ),
                    "available": "2",
                    "errors_from": "1516087871",
                    "lastaccess": "0",
                    "ipmi_authtype": "-1",
                    "ipmi_privilege": "2",
                    "ipmi_username": "",
                    "ipmi_password": "",
                    "ipmi_disable_until": "0",
                    "ipmi_available": "0",
                    "snmp_disable_until": "0",
                    "snmp_available": "0",
                    "maintenanceid": "0",
                    "maintenance_status": "0",
                    "maintenance_type": "0",
                    "maintenance_from": "0",
                    "ipmi_errors_from": "0",
                    "snmp_errors_from": "0",
                    "ipmi_error": "",
                    "snmp_error": "",
                    "jmx_disable_until": "0",
                    "jmx_available": "0",
                    "jmx_errors_from": "0",
                    "jmx_error": "",
                    "name": "master",
                    "flags": "0",
                    "templateid": "0",
                    "description": "",
                    "tls_connect": "1",
                    "tls_accept": "1",
                    "tls_issuer": "",
                    "tls_subject": "",
                    "tls_psk_identity": "",
                    "tls_psk": "",
                    "inventory": {
                        "hostid": "10258",
                        "inventory_mode": "0",
                        "type": "",
                        "type_full": "",
                        "name": "",
                        "alias": "other thing",
                        "os": "some",
                        "os_full": "",
                        "os_short": "",
                        "serialno_a": "",
                        "serialno_b": "",
                        "tag": "",
                        "asset_tag": "",
                        "macaddress_a": "",
                        "macaddress_b": "",
                        "hardware": "",
                        "hardware_full": "",
                        "software": "",
                        "software_full": "",
                        "software_app_a": "",
                        "software_app_b": "",
                        "software_app_c": "",
                        "software_app_d": "",
                        "software_app_e": "",
                        "contact": "",
                        "location": "",
                        "location_lat": "",
                        "location_lon": "",
                        "notes": "",
                        "chassis": "",
                        "model": "",
                        "hw_arch": "",
                        "vendor": "",
                        "contract_number": "",
                        "installer_name": "",
                        "deployment_status": "",
                        "url_a": "",
                        "url_b": "",
                        "url_c": "",
                        "host_networks": "",
                        "host_netmask": "",
                        "host_router": "",
                        "oob_ip": "",
                        "oob_netmask": "",
                        "oob_router": "",
                        "date_hw_purchase": "",
                        "date_hw_install": "",
                        "date_hw_expiry": "",
                        "date_hw_decomm": "",
                        "site_address_a": "",
                        "site_address_b": "",
                        "site_address_c": "",
                        "site_city": "",
                        "site_state": "",
                        "site_country": "",
                        "site_zip": "",
                        "site_rack": "",
                        "site_notes": "",
                        "poc_1_name": "",
                        "poc_1_email": "",
                        "poc_1_phone_a": "",
                        "poc_1_phone_b": "",
                        "poc_1_cell": "",
                        "poc_1_screen": "",
                        "poc_1_notes": "",
                        "poc_2_name": "",
                        "poc_2_email": "",
                        "poc_2_phone_a": "",
                        "poc_2_phone_b": "",
                        "poc_2_cell": "",
                        "poc_2_screen": "",
                        "poc_2_notes": "",
                    },
                }
            ],
            "id": 1,
        }

        with patch.object(zabbix, "_query", return_value=query_return):
            with patch.object(zabbix, "_login", return_value=CONN_ARGS):
                self.assertEqual(
                    zabbix.host_inventory_get("12345", **CONN_ARGS), module_return
                )
Exemple #12
0
    def test_user_list(self):
        """
        query_submitted = {"params": {"output": "extend"}, "jsonrpc": "2.0", "id": 0,
        "auth": "54d67b63c37e690cf06972678f1e9720", "method": "user.get"}
        """

        module_return = [
            {
                "lang": "en_GB",
                "rows_per_page": "50",
                "surname": "Administrator",
                "name": "Zabbix",
                "url": "",
                "attempt_clock": "1515922072",
                "userid": "1",
                "autologin": "******",
                "refresh": "30s",
                "attempt_failed": "0",
                "alias": "Admin",
                "theme": "default",
                "autologout": "0",
                "attempt_ip": "10.0.2.2",
                "type": "3",
            },
            {
                "lang": "en_GB",
                "rows_per_page": "50",
                "surname": "",
                "name": "",
                "url": "",
                "attempt_clock": "0",
                "userid": "2",
                "autologin": "******",
                "refresh": "30s",
                "attempt_failed": "0",
                "alias": "guest",
                "theme": "default",
                "autologout": "15m",
                "attempt_ip": "",
                "type": "1",
            },
            {
                "lang": "en_GB",
                "rows_per_page": "50",
                "surname": "",
                "name": "James Brown",
                "url": "",
                "attempt_clock": "0",
                "userid": "5",
                "autologin": "******",
                "refresh": "30s",
                "attempt_failed": "0",
                "alias": "james",
                "theme": "default",
                "autologout": "15m",
                "attempt_ip": "",
                "type": "1",
            },
        ]
        # pylint: disable=E8128
        query_return = {
            "jsonrpc": "2.0",
            "result": [
                {
                    "userid": "1",
                    "alias": "Admin",
                    "name": "Zabbix",
                    "surname": "Administrator",
                    "url": "",
                    "autologin": "******",
                    "autologout": "0",
                    "lang": "en_GB",
                    "refresh": "30s",
                    "type": "3",
                    "theme": "default",
                    "attempt_failed": "0",
                    "attempt_ip": "10.0.2.2",
                    "attempt_clock": "1515922072",
                    "rows_per_page": "50",
                },
                {
                    "userid": "2",
                    "alias": "guest",
                    "name": "",
                    "surname": "",
                    "url": "",
                    "autologin": "******",
                    "autologout": "15m",
                    "lang": "en_GB",
                    "refresh": "30s",
                    "type": "1",
                    "theme": "default",
                    "attempt_failed": "0",
                    "attempt_ip": "",
                    "attempt_clock": "0",
                    "rows_per_page": "50",
                },
                {
                    "userid": "5",
                    "alias": "james",
                    "name": "James Brown",
                    "surname": "",
                    "url": "",
                    "autologin": "******",
                    "autologout": "15m",
                    "lang": "en_GB",
                    "refresh": "30s",
                    "type": "1",
                    "theme": "default",
                    "attempt_failed": "0",
                    "attempt_ip": "",
                    "attempt_clock": "0",
                    "rows_per_page": "50",
                },
            ],
            "id": 0,
        }

        with patch.object(zabbix, "_query", return_value=query_return):
            with patch.object(zabbix, "_login", return_value=CONN_ARGS):
                self.assertEqual(zabbix.user_list(**CONN_ARGS), module_return)
def test_rename(tmp_path):
    """
    Test if the source file exists on the system,
    rename it to the named file.
    """
    name = str(tmp_path / "salt")
    source = str(tmp_path / "salt" / "salt")

    ret = {"name": name, "result": False, "comment": "", "changes": {}}

    comt = "Must provide name to file.rename"
    ret.update({"comment": comt, "name": ""})
    assert filestate.rename("", source) == ret

    mock_t = MagicMock(return_value=True)
    mock_f = MagicMock(return_value=False)

    mock_lex = MagicMock(side_effect=[False, True, True])
    with patch.object(os.path, "isabs", mock_f):
        comt = "Specified file {} is not an absolute path".format(name)
        ret.update({"comment": comt, "name": name})
        assert filestate.rename(name, source) == ret

    mock_lex = MagicMock(return_value=False)
    with patch.object(os.path, "isabs", mock_t):
        with patch.object(os.path, "lexists", mock_lex):
            comt = 'Source file "{}" has already been moved out of place'.format(
                source)
            ret.update({"comment": comt, "result": True})
            assert filestate.rename(name, source) == ret

    mock_lex = MagicMock(side_effect=[True, True, True])
    with patch.object(os.path, "isabs", mock_t):
        with patch.object(os.path, "lexists", mock_lex):
            comt = 'The target file "{}" exists and will not be overwritten'.format(
                name)
            ret.update({"comment": comt, "result": True})
            assert filestate.rename(name, source) == ret

    mock_lex = MagicMock(side_effect=[True, True, True])
    mock_rem = MagicMock(side_effect=IOError)
    with patch.object(os.path, "isabs", mock_t):
        with patch.object(os.path, "lexists", mock_lex):
            with patch.dict(filestate.__opts__, {"test": False}):
                comt = 'Failed to delete "{}" in preparation for forced move'.format(
                    name)
                with patch.dict(filestate.__salt__, {"file.remove": mock_rem}):
                    ret.update({
                        "name": name,
                        "comment": comt,
                        "result": False
                    })
                    assert filestate.rename(name, source, force=True) == ret

    mock_lex = MagicMock(side_effect=[True, False, False])
    with patch.object(os.path, "isabs", mock_t):
        with patch.object(os.path, "lexists", mock_lex):
            with patch.dict(filestate.__opts__, {"test": True}):
                comt = 'File "{}" is set to be moved to "{}"'.format(
                    source, name)
                ret.update({"name": name, "comment": comt, "result": None})
                assert filestate.rename(name, source) == ret

    mock_lex = MagicMock(side_effect=[True, False, False])
    with patch.object(os.path, "isabs", mock_t):
        with patch.object(os.path, "lexists", mock_lex):
            with patch.object(os.path, "isdir", mock_f):
                with patch.dict(filestate.__opts__, {"test": False}):
                    comt = "The target directory {} is not present".format(
                        tmp_path)
                    ret.update({
                        "name": name,
                        "comment": comt,
                        "result": False
                    })
                    assert filestate.rename(name, source) == ret

    mock_lex = MagicMock(side_effect=[True, False, False])
    with patch.object(os.path, "isabs", mock_t):
        with patch.object(os.path, "lexists", mock_lex):
            with patch.object(os.path, "isdir", mock_t):
                with patch.object(os.path, "islink", mock_f):
                    with patch.dict(filestate.__opts__, {"test": False}):
                        with patch.object(shutil, "move",
                                          MagicMock(side_effect=IOError)):
                            comt = 'Failed to move "{}" to "{}"'.format(
                                source, name)
                            ret.update({
                                "name": name,
                                "comment": comt,
                                "result": False
                            })
                            assert filestate.rename(name, source) == ret

    mock_lex = MagicMock(side_effect=[True, False, False])
    with patch.object(os.path, "isabs", mock_t):
        with patch.object(os.path, "lexists", mock_lex):
            with patch.object(os.path, "isdir", mock_t):
                with patch.object(os.path, "islink", mock_f):
                    with patch.dict(filestate.__opts__, {"test": False}):
                        with patch.object(shutil, "move", MagicMock()):
                            comt = 'Moved "{}" to "{}"'.format(source, name)
                            ret.update({
                                "name": name,
                                "comment": comt,
                                "result": True,
                                "changes": {
                                    name: source
                                },
                            })
                            assert filestate.rename(name, source) == ret
Exemple #14
0
    def test_connect(self):
        """
        Test for Test connectivity to a host using a particular
        port from the minion.
        """
        with patch("socket.socket") as mock_socket:
            self.assertDictEqual(
                network.connect(False, "port"),
                {
                    "comment": "Required argument, host, is missing.",
                    "result": False
                },
            )

            self.assertDictEqual(
                network.connect("host", False),
                {
                    "comment": "Required argument, port, is missing.",
                    "result": False
                },
            )

            ret = "Unable to connect to host (0) on tcp port port"
            mock_socket.side_effect = Exception("foo")
            with patch.dict(
                    network.__utils__,
                {"network.sanitize_host": MagicMock(return_value="A")},
            ):
                with patch.object(
                        socket,
                        "getaddrinfo",
                        return_value=[["ipv4", "A", 6, "B", "0.0.0.0"]],
                ):
                    self.assertDictEqual(
                        network.connect("host", "port"),
                        {
                            "comment": ret,
                            "result": False
                        },
                    )

            ret = "Successfully connected to host (0) on tcp port port"
            mock_socket.side_effect = MagicMock()
            mock_socket.settimeout().return_value = None
            mock_socket.connect().return_value = None
            mock_socket.shutdown().return_value = None
            with patch.dict(
                    network.__utils__,
                {"network.sanitize_host": MagicMock(return_value="A")},
            ):
                with patch.object(
                        socket,
                        "getaddrinfo",
                        return_value=[["ipv4", "A", 6, "B", "0.0.0.0"]],
                ):
                    self.assertDictEqual(
                        network.connect("host", "port"),
                        {
                            "comment": ret,
                            "result": True
                        },
                    )
Exemple #15
0
    def test_append(self):
        """
            Test to append a rule to a chain
        """
        ret = {"name": "salt", "changes": {}, "result": None, "comment": ""}

        self.assertDictEqual(iptables.append("salt", rules=[]), ret)

        mock = MagicMock(return_value=[])
        with patch.object(iptables, "_STATE_INTERNAL_KEYWORDS", mock):
            mock = MagicMock(return_value="a")
            with patch.dict(iptables.__salt__, {"iptables.build_rule": mock}):
                mock = MagicMock(side_effect=[True, False, False, False])
                with patch.dict(iptables.__salt__, {"iptables.check": mock}):
                    ret.update({
                        "comment": "iptables rule for salt"
                        " already set (a) for ipv4",
                        "result": True,
                    })
                    self.assertDictEqual(
                        iptables.append("salt", table="", chain=""), ret)

                    with patch.dict(iptables.__opts__, {"test": True}):
                        ret.update({
                            "result":
                            None,
                            "comment":
                            "iptables rule for salt"
                            " needs to be set (a) for ipv4",
                        })
                        self.assertDictEqual(
                            iptables.append("salt", table="", chain=""), ret)

                    with patch.dict(iptables.__opts__, {"test": False}):
                        mock = MagicMock(side_effect=[True, False])
                        with patch.dict(iptables.__salt__,
                                        {"iptables.append": mock}):
                            ret.update({
                                "changes": {
                                    "locale": "salt"
                                },
                                "result":
                                True,
                                "comment":
                                "Set iptables rule"
                                " for salt to: a for ipv4",
                            })
                            self.assertDictEqual(
                                iptables.append("salt", table="", chain=""),
                                ret)

                            ret.update({
                                "changes": {},
                                "result":
                                False,
                                "comment":
                                "Failed to set iptables"
                                " rule for salt.\nAttempted rule was"
                                " a for ipv4",
                            })
                            self.assertDictEqual(
                                iptables.append("salt", table="", chain=""),
                                ret)
Exemple #16
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')
Exemple #17
0
    def test_delete(self):
        """
            Test to delete a rule to a chain
        """
        ret = {"name": "salt", "changes": {}, "result": None, "comment": ""}

        self.assertDictEqual(iptables.delete("salt", rules=[]), ret)

        mock = MagicMock(return_value=[])
        with patch.object(iptables, "_STATE_INTERNAL_KEYWORDS", mock):
            mock = MagicMock(return_value="a")
            with patch.dict(iptables.__salt__, {"iptables.build_rule": mock}):
                mock = MagicMock(side_effect=[False, True, True, True])
                with patch.dict(iptables.__salt__, {"iptables.check": mock}):
                    ret.update({
                        "comment": "iptables rule for salt"
                        " already absent for ipv4 (a)",
                        "result": True,
                    })
                    self.assertDictEqual(
                        iptables.delete("salt", table="", chain=""), ret)

                    with patch.dict(iptables.__opts__, {"test": True}):
                        ret.update({
                            "result":
                            None,
                            "comment":
                            "iptables rule for salt needs"
                            " to be deleted for ipv4 (a)",
                        })
                        self.assertDictEqual(
                            iptables.delete("salt", table="", chain=""), ret)

                    with patch.dict(iptables.__opts__, {"test": False}):
                        mock = MagicMock(side_effect=[False, True])
                        with patch.dict(iptables.__salt__,
                                        {"iptables.delete": mock}):
                            ret.update({
                                "result":
                                True,
                                "changes": {
                                    "locale": "salt"
                                },
                                "comment":
                                "Delete iptables rule"
                                " for salt a",
                            })
                            self.assertDictEqual(
                                iptables.delete("salt",
                                                table="",
                                                chain="",
                                                position=""),
                                ret,
                            )

                            ret.update({
                                "result":
                                False,
                                "changes": {},
                                "comment":
                                "Failed to delete iptables"
                                " rule for salt.\nAttempted rule was a",
                            })
                            self.assertDictEqual(
                                iptables.delete("salt",
                                                table="",
                                                chain="",
                                                position=""),
                                ret,
                            )
Exemple #18
0
    def _run_os_grains_tests(self, os_release_filename, os_release_map,
                             expectation):
        path_isfile_mock = MagicMock(
            side_effect=lambda x: x in os_release_map.get('files', []))
        empty_mock = MagicMock(return_value={})
        osarch_mock = MagicMock(return_value="amd64")
        if os_release_filename:
            os_release_data = core._parse_os_release(
                os.path.join(OS_RELEASE_DIR, os_release_filename))
        else:
            os_release_data = os_release_map.get('os_release_file', {})
        os_release_mock = MagicMock(return_value=os_release_data)

        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)

        suse_release_file = os_release_map.get('suse_release_file')

        file_contents = {'/proc/1/cmdline': ''}
        if suse_release_file:
            file_contents['/etc/SuSE-release'] = suse_release_file

        # - 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
        distro_mock = MagicMock(
            return_value=os_release_map['linux_distribution'])
        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_isfile_mock), \
                patch('{0}.__import__'.format(built_in), side_effect=_import_mock), \
                patch.object(os.path, 'isfile', path_isfile_mock), \
                patch.object(core, '_parse_os_release', os_release_mock), \
                patch.object(core, '_parse_lsb_release', empty_mock), \
                patch('salt.utils.files.fopen', mock_open(read_data=file_contents)), \
                patch.object(core, 'linux_distribution', distro_mock), \
                patch.object(core, '_linux_gpu_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()

        grains = {
            k: v
            for k, v in os_grains.items() if k in set([
                "os", "os_family", "osfullname", "oscodename", "osfinger",
                "osrelease", "osrelease_info", "osmajorrelease"
            ])
        }
        self.assertEqual(grains, expectation)
def test_recurse():
    """
    Test to recurse through a subdirectory on the master
    and copy said subdirectory over to the specified path.
    """
    name = "/opt/code/flask"
    source = "salt://code/flask"
    user = "******"
    group = "saltstack"
    if salt.utils.platform.is_windows():
        name = name.replace("/", "\\")

    ret = {"name": name, "result": False, "comment": "", "changes": {}}

    comt = ("'mode' is not allowed in 'file.recurse'."
            " Please use 'file_mode' and 'dir_mode'.")
    ret.update({"comment": comt})
    assert filestate.recurse(name, source, mode="W") == ret

    mock_t = MagicMock(return_value=True)
    mock_f = MagicMock(return_value=False)
    mock_uid = MagicMock(return_value="")
    mock_gid = MagicMock(return_value="")
    mock_l = MagicMock(return_value=[])
    mock_emt = MagicMock(side_effect=[[], ["code/flask"], ["code/flask"]])
    mock_lst = MagicMock(side_effect=[
        CommandExecutionError, (source, ""), (source, ""), (source, "")
    ])
    with patch.dict(
            filestate.__salt__,
        {
            "config.manage_mode": mock_t,
            "file.user_to_uid": mock_uid,
            "file.group_to_gid": mock_gid,
            "file.source_list": mock_lst,
            "cp.list_master_dirs": mock_emt,
            "cp.list_master": mock_l,
        },
    ):

        # Group argument is ignored on Windows systems. Group is set to user
        if salt.utils.platform.is_windows():
            comt = "User salt is not available Group salt is not available"
        else:
            comt = "User salt is not available Group saltstack is not available"
        ret.update({"comment": comt})
        assert filestate.recurse(name, source, user=user, group=group) == ret

        with patch.object(os.path, "isabs", mock_f):
            comt = "Specified file {} is not an absolute path".format(name)
            ret.update({"comment": comt})
            assert filestate.recurse(name, source) == ret

        with patch.object(os.path, "isabs", mock_t):
            comt = "Invalid source '1' (must be a salt:// URI)"
            ret.update({"comment": comt})
            assert filestate.recurse(name, 1) == ret

            comt = "Invalid source '//code/flask' (must be a salt:// URI)"
            ret.update({"comment": comt})
            assert filestate.recurse(name, "//code/flask") == ret

            comt = "Recurse failed: "
            ret.update({"comment": comt})
            assert filestate.recurse(name, source) == ret

            comt = ("The directory 'code/flask' does not exist"
                    " on the salt fileserver in saltenv 'base'")
            ret.update({"comment": comt})
            assert filestate.recurse(name, source) == ret

            with patch.object(os.path, "isdir", mock_f):
                with patch.object(os.path, "exists", mock_t):
                    comt = "The path {} exists and is not a directory".format(
                        name)
                    ret.update({"comment": comt})
                    assert filestate.recurse(name, source) == ret

            with patch.object(os.path, "isdir", mock_t):
                comt = "The directory {} is in the correct state".format(name)
                ret.update({"comment": comt, "result": True})
                assert filestate.recurse(name, source) == ret
Exemple #20
0
 def _check_solaris_sparc_productname_grains(self, prtdata, expectation):
     '''
     verify product grains on solaris sparc
     '''
     import platform
     path_isfile_mock = MagicMock(
         side_effect=lambda x: x in ['/etc/release'])
     with salt.utils.files.fopen(
             os.path.join(OS_RELEASE_DIR,
                          "solaris-11.3")) as os_release_file:
         os_release_content = os_release_file.readlines()
     uname_mock = MagicMock(return_value=('SunOS', 'testsystem', '5.11',
                                          '11.3', 'sunv4', 'sparc'))
     with patch.object(platform, 'uname', uname_mock), \
             patch.object(salt.utils.platform, 'is_proxy',
                          MagicMock(return_value=False)), \
             patch.object(salt.utils.platform, 'is_linux',
                          MagicMock(return_value=False)), \
             patch.object(salt.utils.platform, 'is_windows',
                          MagicMock(return_value=False)), \
             patch.object(salt.utils.platform, 'is_smartos',
                          MagicMock(return_value=False)), \
             patch.object(salt.utils.path, 'which_bin',
                          MagicMock(return_value=None)), \
             patch.object(os.path, 'isfile', path_isfile_mock), \
             patch('salt.utils.files.fopen',
                   mock_open(read_data=os_release_content)) as os_release_file, \
             patch.object(core, '_sunos_cpudata',
                          MagicMock(return_value={
                              'cpuarch': 'sparcv9',
                              'num_cpus': '1',
                              'cpu_model': 'MOCK_CPU_MODEL',
                              'cpu_flags': []})), \
             patch.object(core, '_memdata',
                          MagicMock(return_value={'mem_total': 16384})), \
             patch.object(core, '_virtual',
                          MagicMock(return_value={})), \
             patch.object(core, '_ps', MagicMock(return_value={})), \
             patch.object(salt.utils.path, 'which',
                          MagicMock(return_value=True)), \
             patch.dict(core.__salt__,
                        {'cmd.run': MagicMock(return_value=prtdata)}):
         os_grains = core.os_data()
     grains = {
         k: v
         for k, v in os_grains.items()
         if k in set(['product', 'productname'])
     }
     self.assertEqual(grains, expectation)
Exemple #21
0
 def test_get_network_settings(self):
     '''
     Test to return the contents of the global network script.
     '''
     with patch.object(rh_ip, '_read_file', return_value='A'):
         self.assertEqual(rh_ip.get_network_settings(), 'A')
Exemple #22
0
    def test_active(self):
        """
        List the active mounts.
        """
        with patch.dict(mount.__grains__, {
                "os": "FreeBSD",
                "kernel": "FreeBSD"
        }):
            # uid=user1 tests the improbable case where a OS returns a name
            # instead of a numeric id, for #25293
            mock = MagicMock(return_value="A B C D,E,F,uid=user1,gid=grp1")
            mock_user = MagicMock(return_value={"uid": "100"})
            mock_group = MagicMock(return_value={"gid": "100"})
            with patch.dict(
                    mount.__mods__,
                {
                    "cmd.run_stdout": mock,
                    "user.info": mock_user,
                    "group.info": mock_group,
                },
            ):
                self.assertEqual(
                    mount.active(),
                    {
                        "B": {
                            "device": "A",
                            "opts": ["D", "E", "F", "uid=100", "gid=100"],
                            "fstype": "C",
                        }
                    },
                )

        with patch.dict(mount.__grains__, {
                "os": "Solaris",
                "kernel": "SunOS"
        }):
            mock = MagicMock(return_value="A * B * C D/E/F")
            with patch.dict(mount.__mods__, {"cmd.run_stdout": mock}):
                self.assertEqual(
                    mount.active(),
                    {
                        "B": {
                            "device": "A",
                            "opts": ["D", "E", "F"],
                            "fstype": "C"
                        }
                    },
                )

        with patch.dict(mount.__grains__, {"os": "AIX", "kernel": "AIX"}):
            mock = MagicMock(return_value="A * B * C D/E/F")
            with patch.dict(mount.__mods__, {"cmd.run_stdout": mock}):
                self.assertEqual(
                    mount.active(),
                    {"B": {
                        "node": "A",
                        "device": "*",
                        "fstype": "*"
                    }})

        with patch.dict(mount.__grains__, {
                "os": "OpenBSD",
                "kernel": "OpenBSD"
        }):
            mock = MagicMock(return_value={})
            with patch.object(mount, "_active_mounts_openbsd", mock):
                self.assertEqual(mount.active(), {})

        with patch.dict(mount.__grains__, {"os": "MacOS", "kernel": "Darwin"}):
            mock = MagicMock(return_value={})
            with patch.object(mount, "_active_mounts_darwin", mock):
                self.assertEqual(mount.active(), {})

        with patch.dict(mount.__grains__, {"os": "MacOS", "kernel": "Darwin"}):
            mock = MagicMock(return_value={})
            with patch.object(mount, "_active_mountinfo", mock):
                with patch.object(mount, "_active_mounts_darwin", mock):
                    self.assertEqual(mount.active(extended=True), {})

        with patch.dict(mount.__grains__, {"os": "AIX", "kernel": "AIX"}):
            mock = MagicMock(return_value={})
            with patch.object(mount, "_active_mounts_aix", mock):
                self.assertEqual(mount.active(), {})
    def _change_state(self, action, no_block=False):
        '''
        Common code for start/stop/restart/reload/force_reload tests
        '''
        # We want the traceback if the function name can't be found in the
        # systemd execution module.
        func = getattr(systemd, action)
        # Remove trailing _ in "reload_"
        action = action.rstrip('_').replace('_', '-')
        systemctl_command = ['systemctl']
        if no_block:
            systemctl_command.append('--no-block')
        systemctl_command.extend([action, self.unit_name + '.service'])
        scope_prefix = ['systemd-run', '--scope']

        assert_kwargs = {'python_shell': False}
        if action in ('enable', 'disable'):
            assert_kwargs['ignore_retcode'] = True

        with patch.object(systemd, '_check_for_unit_changes', self.mock_none):
            with patch.object(systemd, '_unit_file_changed', self.mock_none):
                with patch.object(systemd, '_check_unmask', self.mock_none):
                    with patch.object(systemd, '_get_sysv_services', self.mock_empty_list):

                        # Has scopes available
                        with patch.object(salt.utils.systemd, 'has_scope', self.mock_true):

                            # Scope enabled, successful
                            with patch.dict(
                                    systemd.__salt__,
                                    {'config.get': self.mock_true,
                                     'cmd.run_all': self.mock_run_all_success}):
                                ret = func(self.unit_name, no_block=no_block)
                                self.assertTrue(ret)
                                self.mock_run_all_success.assert_called_with(
                                    scope_prefix + systemctl_command,
                                    **assert_kwargs)

                            # Scope enabled, failed
                            with patch.dict(
                                    systemd.__salt__,
                                    {'config.get': self.mock_true,
                                     'cmd.run_all': self.mock_run_all_failure}):
                                if action in ('stop', 'disable'):
                                    ret = func(self.unit_name, no_block=no_block)
                                    self.assertFalse(ret)
                                else:
                                    self.assertRaises(
                                        CommandExecutionError,
                                        func,
                                        self.unit_name,
                                        no_block=no_block)
                                self.mock_run_all_failure.assert_called_with(
                                    scope_prefix + systemctl_command,
                                    **assert_kwargs)

                            # Scope disabled, successful
                            with patch.dict(
                                    systemd.__salt__,
                                    {'config.get': self.mock_false,
                                     'cmd.run_all': self.mock_run_all_success}):
                                ret = func(self.unit_name, no_block=no_block)
                                self.assertTrue(ret)
                                self.mock_run_all_success.assert_called_with(
                                    systemctl_command,
                                    **assert_kwargs)

                            # Scope disabled, failed
                            with patch.dict(
                                    systemd.__salt__,
                                    {'config.get': self.mock_false,
                                     'cmd.run_all': self.mock_run_all_failure}):
                                if action in ('stop', 'disable'):
                                    ret = func(self.unit_name, no_block=no_block)
                                    self.assertFalse(ret)
                                else:
                                    self.assertRaises(
                                        CommandExecutionError,
                                        func,
                                        self.unit_name,
                                        no_block=no_block)
                                self.mock_run_all_failure.assert_called_with(
                                    systemctl_command,
                                    **assert_kwargs)

                        # Does not have scopes available
                        with patch.object(salt.utils.systemd, 'has_scope', self.mock_false):

                            # The results should be the same irrespective of
                            # whether or not scope is enabled, since scope is not
                            # available, so we repeat the below tests with it both
                            # enabled and disabled.
                            for scope_mock in (self.mock_true, self.mock_false):

                                # Successful
                                with patch.dict(
                                        systemd.__salt__,
                                        {'config.get': scope_mock,
                                         'cmd.run_all': self.mock_run_all_success}):
                                    ret = func(self.unit_name, no_block=no_block)
                                    self.assertTrue(ret)
                                    self.mock_run_all_success.assert_called_with(
                                        systemctl_command,
                                        **assert_kwargs)

                                # Failed
                                with patch.dict(
                                        systemd.__salt__,
                                        {'config.get': scope_mock,
                                         'cmd.run_all': self.mock_run_all_failure}):
                                    if action in ('stop', 'disable'):
                                        ret = func(self.unit_name,
                                                   no_block=no_block)
                                        self.assertFalse(ret)
                                    else:
                                        self.assertRaises(
                                            CommandExecutionError,
                                            func,
                                            self.unit_name,
                                            no_block=no_block)
                                    self.mock_run_all_failure.assert_called_with(
                                        systemctl_command,
                                        **assert_kwargs)
Exemple #24
0
    def test_mount(self):
        """
        Mount a device
        """
        with patch.dict(mount.__grains__, {"os": "MacOS"}):
            mock = MagicMock(return_value=True)
            with patch.object(os.path, "exists", mock):
                mock = MagicMock(return_value=None)
                with patch.dict(mount.__mods__, {"file.mkdir": None}):
                    mock = MagicMock(return_value={
                        "retcode": True,
                        "stderr": True
                    })
                    with patch.dict(mount.__mods__, {"cmd.run_all": mock}):
                        self.assertTrue(mount.mount("name", "device"))
                        mock.assert_called_with("mount  device name ",
                                                python_shell=False,
                                                runas=None)

                    with patch.dict(mount.__mods__, {"cmd.run_all": mock}):
                        self.assertTrue(
                            mount.mount("name", "device", fstype="fstype"))
                        mock.assert_called_with(
                            "mount  -t fstype device name ",
                            python_shell=False,
                            runas=None,
                        )

                    mock = MagicMock(return_value={
                        "retcode": False,
                        "stderr": False
                    })
                    with patch.dict(mount.__mods__, {"cmd.run_all": mock}):
                        self.assertTrue(mount.mount("name", "device"))

        with patch.dict(mount.__grains__, {"os": "AIX"}):
            mock = MagicMock(return_value=True)
            with patch.object(os.path, "exists", mock):
                mock = MagicMock(return_value=None)
                with patch.dict(mount.__mods__, {"file.mkdir": None}):
                    mock = MagicMock(return_value={
                        "retcode": True,
                        "stderr": True
                    })
                    with patch.dict(mount.__mods__, {"cmd.run_all": mock}):
                        self.assertTrue(mount.mount("name", "device"))
                        mock.assert_called_with("mount  device name ",
                                                python_shell=False,
                                                runas=None)

                    with patch.dict(mount.__mods__, {"cmd.run_all": mock}):
                        self.assertTrue(
                            mount.mount("name", "device", fstype="fstype"))
                        mock.assert_called_with(
                            "mount  -v fstype device name ",
                            python_shell=False,
                            runas=None,
                        )

                    mock = MagicMock(return_value={
                        "retcode": False,
                        "stderr": False
                    })
                    with patch.dict(mount.__mods__, {"cmd.run_all": mock}):
                        self.assertTrue(mount.mount("name", "device"))

        with patch.dict(mount.__grains__, {"os": "Linux"}):
            mock = MagicMock(return_value=True)
            with patch.object(os.path, "exists", mock):
                mock = MagicMock(return_value=None)
                with patch.dict(mount.__mods__, {"file.mkdir": None}):
                    mock = MagicMock(return_value={
                        "retcode": True,
                        "stderr": True
                    })
                    with patch.dict(mount.__mods__, {"cmd.run_all": mock}):
                        self.assertTrue(mount.mount("name", "device"))
                        mock.assert_called_with(
                            "mount -o defaults device name ",
                            python_shell=False,
                            runas=None,
                        )

                    with patch.dict(mount.__mods__, {"cmd.run_all": mock}):
                        self.assertTrue(
                            mount.mount("name", "device", fstype="fstype"))
                        mock.assert_called_with(
                            "mount -o defaults -t fstype device name ",
                            python_shell=False,
                            runas=None,
                        )

                    mock = MagicMock(return_value={
                        "retcode": False,
                        "stderr": False
                    })
                    with patch.dict(mount.__mods__, {"cmd.run_all": mock}):
                        self.assertTrue(mount.mount("name", "device"))
def has_spwd():
    with patch.object(solaris_shadow, "HAS_SPWD", True):
        yield
Exemple #26
0
    def test_mounted(self):
        '''
        Test to verify that a device is mounted.
        '''
        name = os.path.realpath('/mnt/sdb')
        device = os.path.realpath('/dev/sdb5')
        fstype = 'xfs'

        name2 = os.path.realpath('/mnt/cifs')
        device2 = '//SERVER/SHARE/'
        fstype2 = 'cifs'
        opts2 = ['noowners']
        superopts2 = ['uid=510', 'gid=100', 'username=cifsuser',
                      'domain=cifsdomain']

        ret = {'name': name,
               'result': False,
               'comment': '',
               'changes': {}}

        mock = MagicMock(side_effect=['new', 'present', 'new', 'change',
                                      'bad config', 'salt', 'present'])
        mock_t = MagicMock(return_value=True)
        mock_f = MagicMock(return_value=False)
        mock_ret = MagicMock(return_value={'retcode': 1})
        mock_mnt = MagicMock(return_value={name: {'device': device, 'opts': [],
                                                  'superopts': []},
                                           name2: {'device': device2, 'opts': opts2,
                                                   'superopts': superopts2}})
        mock_emt = MagicMock(return_value={})
        mock_str = MagicMock(return_value='salt')
        mock_user = MagicMock(return_value={'uid': 510})
        mock_group = MagicMock(return_value={'gid': 100})
        mock_read_cache = MagicMock(return_value={})
        mock_write_cache = MagicMock(return_value=True)
        with patch.dict(mount.__grains__, {'os': 'Darwin'}):
            with patch.dict(mount.__salt__, {'mount.active': mock_mnt,
                                             'cmd.run_all': mock_ret,
                                             'mount.umount': mock_f}), \
                    patch('os.path.exists', MagicMock(return_value=True)):
                comt = ('Unable to find device with label /dev/sdb5.')
                ret.update({'comment': comt})
                self.assertDictEqual(mount.mounted(name, 'LABEL=/dev/sdb5',
                                                   fstype), ret)

                with patch.dict(mount.__opts__, {'test': True}):
                    comt = ('Remount would be forced because'
                            ' options (noowners) changed')
                    ret.update({'comment': comt, 'result': None})
                    self.assertDictEqual(mount.mounted(name, device, fstype),
                                         ret)

                with patch.dict(mount.__opts__, {'test': False}):
                    comt = ('Unable to unmount {0}: False.'.format(name))
                    umount = ('Forced unmount and mount because'
                              ' options (noowners) changed')
                    ret.update({'comment': comt, 'result': False,
                                'changes': {'umount': umount}})
                    self.assertDictEqual(mount.mounted(name, device, 'nfs'),
                                         ret)

                    umount1 = ("Forced unmount because devices don't match. "
                               "Wanted: {0}, current: {1}, {1}".format(os.path.realpath('/dev/sdb6'), device))
                    comt = ('Unable to unmount')
                    ret.update({'comment': comt, 'result': None,
                                'changes': {'umount': umount1}})
                    self.assertDictEqual(mount.mounted(name, os.path.realpath('/dev/sdb6'),
                                                       fstype, opts=[]), ret)

                with patch.dict(mount.__salt__, {'mount.active': mock_emt,
                                                 'mount.mount': mock_str,
                                                 'mount.set_automaster': mock}):
                    with patch.dict(mount.__opts__, {'test': True}), \
                            patch('os.path.exists', MagicMock(return_value=False)):
                        comt = ('{0} does not exist and would not be created'.format(name))
                        ret.update({'comment': comt, 'changes': {}})
                        self.assertDictEqual(mount.mounted(name, device,
                                                           fstype), ret)

                    with patch.dict(mount.__opts__, {'test': False}):
                        with patch.object(os.path, 'exists', mock_f):
                            comt = ('Mount directory is not present')
                            ret.update({'comment': comt, 'result': False})
                            self.assertDictEqual(mount.mounted(name, device,
                                                               fstype), ret)

                        with patch.object(os.path, 'exists', mock_t):
                            comt = ('Mount directory is not present')
                            ret.update({'comment': 'salt', 'result': False})
                            self.assertDictEqual(mount.mounted(name, device,
                                                               fstype), ret)

                    with patch.dict(mount.__opts__, {'test': True}), \
                            patch('os.path.exists', MagicMock(return_value=False)):
                        comt = ('{0} does not exist and would neither be created nor mounted. '
                                '{0} needs to be written to the fstab in order to be made persistent.'.format(name))
                        ret.update({'comment': comt, 'result': None})
                        self.assertDictEqual(mount.mounted(name, device, fstype,
                                                           mount=False), ret)

                    with patch.dict(mount.__opts__, {'test': False}), \
                            patch('os.path.exists', MagicMock(return_value=False)):
                        comt = ('{0} not present and not mounted. '
                                'Entry already exists in the fstab.'.format(name))
                        ret.update({'comment': comt, 'result': True})
                        self.assertDictEqual(mount.mounted(name, device, fstype,
                                                           mount=False), ret)

                        comt = ('{0} not present and not mounted. '
                                'Added new entry to the fstab.'.format(name))
                        ret.update({'comment': comt, 'result': True,
                                    'changes': {'persist': 'new'}})
                        self.assertDictEqual(mount.mounted(name, device, fstype,
                                                           mount=False), ret)

                        comt = ('{0} not present and not mounted. '
                                'Updated the entry in the fstab.'.format(name))
                        ret.update({'comment': comt, 'result': True,
                                    'changes': {'persist': 'update'}})
                        self.assertDictEqual(mount.mounted(name, device, fstype,
                                                           mount=False), ret)

                        comt = ('{0} not present and not mounted. '
                                'However, the fstab was not found.'.format(name))
                        ret.update({'comment': comt, 'result': False,
                                    'changes': {}})
                        self.assertDictEqual(mount.mounted(name, device, fstype,
                                                           mount=False), ret)

                        comt = ('{0} not present and not mounted'.format(name))
                        ret.update({'comment': comt, 'result': True,
                                    'changes': {}})
                        self.assertDictEqual(mount.mounted(name, device, fstype,
                                                           mount=False), ret)

        # Test no change for uid provided as a name #25293
        with patch.dict(mount.__grains__, {'os': 'CentOS'}):
            with patch.dict(mount.__salt__, {'mount.active': mock_mnt,
                                             'mount.mount': mock_str,
                                             'mount.umount': mock_f,
                                             'mount.read_mount_cache': mock_read_cache,
                                             'mount.write_mount_cache': mock_write_cache,
                                             'mount.set_fstab': mock,
                                             'user.info': mock_user,
                                             'group.info': mock_group}):
                with patch.dict(mount.__opts__, {'test': True}):
                    with patch.object(os.path, 'exists', mock_t):
                        comt = 'Target was already mounted. Entry already exists in the fstab.'
                        ret.update({'name': name2, 'result': True})
                        ret.update({'comment': comt, 'changes': {}})
                        self.assertDictEqual(mount.mounted(name2, device2,
                                                           fstype2,
                                                           opts=['uid=user1',
                                                                 'gid=group1']),
                                             ret)
Exemple #27
0
    def test_create_user(self):
        """
        Tests to create user accounts
        """
        self.assertFalse(
            drac.create_user("username", "password", "permissions",
                             {"username": None}))

        mock = MagicMock(return_value=False)
        with patch.object(drac, "__execute_cmd", mock):
            mock = MagicMock(return_value=None)
            with patch.object(drac, "delete_user", mock):
                self.assertFalse(
                    drac.create_user(
                        "username",
                        "password",
                        "permissions",
                        {"username1": {
                            "index": 1
                        }},
                    ))

        mock = MagicMock(return_value=True)
        with patch.object(drac, "__execute_cmd", mock):
            mock = MagicMock(return_value=False)
            with patch.object(drac, "set_permissions", mock):
                mock = MagicMock(return_value=None)
                with patch.object(drac, "delete_user", mock):
                    self.assertFalse(
                        drac.create_user(
                            "username",
                            "password",
                            "permissions",
                            {"username1": {
                                "index": 1
                            }},
                        ))

            mock = MagicMock(return_value=True)
            with patch.object(drac, "set_permissions", mock):
                mock = MagicMock(return_value=False)
                with patch.object(drac, "change_password", mock):
                    mock = MagicMock(return_value=None)
                    with patch.object(drac, "delete_user", mock):
                        self.assertFalse(
                            drac.create_user(
                                "username",
                                "password",
                                "permissions",
                                {"username1": {
                                    "index": 1
                                }},
                            ))

        mock = MagicMock(side_effect=[True, False])
        with patch.object(drac, "__execute_cmd", mock):
            mock = MagicMock(return_value=True)
            with patch.object(drac, "set_permissions", mock):
                mock = MagicMock(return_value=True)
                with patch.object(drac, "change_password", mock):
                    mock = MagicMock(return_value=None)
                    with patch.object(drac, "delete_user", mock):
                        self.assertFalse(
                            drac.create_user(
                                "username",
                                "password",
                                "permissions",
                                {"username1": {
                                    "index": 1
                                }},
                            ))

        mock = MagicMock(side_effect=[True, True])
        with patch.object(drac, "__execute_cmd", mock):
            mock = MagicMock(return_value=True)
            with patch.object(drac, "set_permissions", mock):
                mock = MagicMock(return_value=True)
                with patch.object(drac, "change_password", mock):
                    mock = MagicMock(return_value=None)
                    with patch.object(drac, "delete_user", mock):
                        self.assertTrue(
                            drac.create_user(
                                "username",
                                "password",
                                "permissions",
                                {"username1": {
                                    "index": 1
                                }},
                            ))
Exemple #28
0
def test_show():
    """
    Test that the pkg.show function properly parses apt-cache show output.
    This test uses an abridged output per package, for simplicity.
    """
    show_mock_success = MagicMock(
        return_value={
            "retcode":
            0,
            "pid":
            12345,
            "stderr":
            "",
            "stdout":
            textwrap.dedent("""\
            Package: foo1.0
            Architecture: amd64
            Version: 1.0.5-3ubuntu4
            Description: A silly package (1.0 release cycle)
            Provides: foo
            Suggests: foo-doc

            Package: foo1.0
            Architecture: amd64
            Version: 1.0.4-2ubuntu1
            Description: A silly package (1.0 release cycle)
            Provides: foo
            Suggests: foo-doc

            Package: foo-doc
            Architecture: all
            Version: 1.0.5-3ubuntu4
            Description: Silly documentation for a silly package (1.0 release cycle)

            Package: foo-doc
            Architecture: all
            Version: 1.0.4-2ubuntu1
            Description: Silly documentation for a silly package (1.0 release cycle)

            """),
        })

    show_mock_failure = MagicMock(
        return_value={
            "retcode":
            1,
            "pid":
            12345,
            "stderr":
            textwrap.dedent("""\
            N: Unable to locate package foo*
            N: Couldn't find any package by glob 'foo*'
            N: Couldn't find any package by regex 'foo*'
            E: No packages found
            """),
            "stdout":
            "",
        })

    refresh_mock = Mock()

    expected = {
        "foo1.0": {
            "1.0.5-3ubuntu4": {
                "Architecture": "amd64",
                "Description": "A silly package (1.0 release cycle)",
                "Provides": "foo",
                "Suggests": "foo-doc",
            },
            "1.0.4-2ubuntu1": {
                "Architecture": "amd64",
                "Description": "A silly package (1.0 release cycle)",
                "Provides": "foo",
                "Suggests": "foo-doc",
            },
        },
        "foo-doc": {
            "1.0.5-3ubuntu4": {
                "Architecture":
                "all",
                "Description":
                ("Silly documentation for a silly package (1.0 release cycle)"
                 ),
            },
            "1.0.4-2ubuntu1": {
                "Architecture":
                "all",
                "Description":
                ("Silly documentation for a silly package (1.0 release cycle)"
                 ),
            },
        },
    }

    # Make a copy of the above dict and strip out some keys to produce the
    # expected filtered result.
    filtered = copy.deepcopy(expected)
    for k1 in filtered:
        for k2 in filtered[k1]:
            # Using list() because we will modify the dict during iteration
            for k3 in list(filtered[k1][k2]):
                if k3 not in ("Description", "Provides"):
                    filtered[k1][k2].pop(k3)

    with patch.dict(aptpkg.__salt__,
                    {"cmd.run_all": show_mock_success}), patch.object(
                        aptpkg, "refresh_db", refresh_mock):

        # Test success (no refresh)
        assert aptpkg.show("foo*") == expected
        refresh_mock.assert_not_called()
        refresh_mock.reset_mock()

        # Test success (with refresh)
        assert aptpkg.show("foo*", refresh=True) == expected
        refresh_mock.assert_called_once()
        refresh_mock.reset_mock()

        # Test filtered return
        assert aptpkg.show("foo*", filter="description,provides") == filtered
        refresh_mock.assert_not_called()
        refresh_mock.reset_mock()

    with patch.dict(aptpkg.__salt__,
                    {"cmd.run_all": show_mock_failure}), patch.object(
                        aptpkg, "refresh_db", refresh_mock):

        # Test failure (no refresh)
        assert aptpkg.show("foo*") == {}
        refresh_mock.assert_not_called()
        refresh_mock.reset_mock()

        # Test failure (with refresh)
        assert aptpkg.show("foo*", refresh=True) == {}
        refresh_mock.assert_called_once()
        refresh_mock.reset_mock()
Exemple #29
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')
Exemple #30
0
 def test_versions(self):
     '''
     Test for list the installed versions of ruby.
     '''
     with patch.object(rbenv, '_rbenv_exec', return_value='A\nBC\nD'):
         self.assertListEqual(rbenv.versions(), ['A', 'BC', 'D'])