Ejemplo n.º 1
0
    def test_unhold(self):
        """
        Test for put message(s) on hold from the mail queue
        """
        with patch.object(postfix, "show_queue", return_value={}):
            self.assertDictEqual(
                postfix.unhold("queue_id"),
                {
                    "result": False,
                    "message": "No message in queue with ID queue_id"
                },
            )

        with patch.dict(
                postfix.__salt__,
            {"cmd.run_all": MagicMock(return_value={"retcode": 0})}):
            self.assertDictEqual(
                postfix.unhold("ALL"),
                {
                    "result": True,
                    "message": "Successfully set all message as unheld"
                },
            )
Ejemplo n.º 2
0
    def test_install_with_options(self):
        parse_targets = MagicMock(return_value=({'foo': None}, 'repository'))
        with patch.object(yumpkg, 'list_pkgs', MagicMock(return_value={})), \
                patch.object(yumpkg, 'list_holds', MagicMock(return_value=[])), \
                patch.dict(yumpkg.__salt__, {'pkg_resource.parse_targets': parse_targets}), \
             patch('salt.utils.systemd.has_scope', MagicMock(return_value=False)):

            # with fromrepo
            cmd = MagicMock(return_value={'retcode': 0})
            with patch.dict(yumpkg.__salt__, {'cmd.run_all': cmd}):
                yumpkg.install(refresh=False,
                               fromrepo='good',
                               branch='foo',
                               setopt='obsoletes=0,plugins=0')
                cmd.assert_called_once_with([
                    'yum', '-y', '--disablerepo=*', '--enablerepo=good',
                    '--branch=foo', '--setopt', 'obsoletes=0', '--setopt',
                    'plugins=0', 'install', 'foo'
                ],
                                            env={},
                                            output_loglevel='trace',
                                            python_shell=False,
                                            ignore_retcode=False,
                                            redirect_stderr=True)

            # without fromrepo
            cmd = MagicMock(return_value={'retcode': 0})
            with patch.dict(yumpkg.__salt__, {'cmd.run_all': cmd}):
                yumpkg.install(refresh=False,
                               enablerepo='good',
                               disablerepo='bad',
                               branch='foo',
                               setopt='obsoletes=0,plugins=0')
                cmd.assert_called_once_with(
                    [
                        'yum', '-y', '--disablerepo=bad', '--enablerepo=good',
                        '--branch=foo', '--setopt', 'obsoletes=0', '--setopt',
                        'plugins=0', 'install', 'foo'
                    ],
                    env={},
                    output_loglevel='trace',
                    python_shell=False,
                    ignore_retcode=False,
                    redirect_stderr=True,
                )
Ejemplo n.º 3
0
 def test_hook_can_handle_get_parameters(self):
     with patch('salt.utils.event.get_event') as get_event:
         with patch.dict(self._app.mod_opts, {'webhook_disable_auth': True}):
             event = MagicMock()
             event.fire_event.return_value = True
             get_event.return_value = event
             response = self.fetch('/hook/my_service/?param=1&param=2',
                                   body=salt.utils.json.dumps({}),
                                   method='POST',
                                   headers={'Content-Type': self.content_type_map['json']})
             self.assertEqual(response.code, 200, response.body)
             host = urlparse(response.effective_url).netloc
             event.fire_event.assert_called_once_with(
                 {'headers': {'Content-Length': '2',
                              'Connection': 'close',
                              'Content-Type': 'application/json',
                              'Host': host,
                              'Accept-Encoding': 'gzip'},
                  'post': {},
                  'get': {'param': ['1', '2']}
                  },
                 'salt/netapi/hook/my_service/',
             )
Ejemplo n.º 4
0
 def test_examine(self):
     """
     Test for mdadm_raid.examine
     """
     mock = MagicMock(
         return_value=(
             "ARRAY /dev/md/pool metadata=1.2"
             " UUID=567da122:fb8e445e:55b853e0:81bd0a3e name=positron:pool"
         )
     )
     with patch.dict(mdadm.__salt__, {"cmd.run_stdout": mock}):
         self.assertEqual(
             mdadm.examine("/dev/md0"),
             {
                 "ARRAY /dev/md/pool metadata": (
                     "1.2 UUID=567da122:fb8e445e:55b853e0:81bd0a3e"
                     " name=positron:pool"
                 )
             },
         )
         mock.assert_called_with(
             "mdadm -Y -E /dev/md0", ignore_retcode=False, python_shell=False
         )
Ejemplo n.º 5
0
 def test_source_address(self):
     '''
     test when source_address is set
     '''
     interfaces = {'bond0.1234': {'hwaddr': '01:01:01:d0:d0:d0',
                                  'up': False, 'inet':
                                  [{'broadcast': '111.1.111.255',
                                  'netmask': '111.1.0.0',
                                  'label': 'bond0',
                                  'address': '111.1.0.1'}]}}
     with patch.dict(__opts__, {'ipv6': False, 'master': '127.0.0.1',
                                'master_port': '4555', 'file_client': 'local',
                                'source_interface_name': '',
                                'source_address': '111.1.0.1',
                                'source_ret_port': 49017,
                                'source_publish_port': 49018}), \
         patch('salt.utils.network.interfaces',
               MagicMock(return_value=interfaces)):
         assert salt.minion.resolve_dns(__opts__) == {'source_publish_port': 49018,
                                                      'source_ret_port': 49017,
                                                      'master_uri': 'tcp://127.0.0.1:4555',
                                                      'source_ip': '111.1.0.1',
                                                      'master_ip': '127.0.0.1'}
Ejemplo n.º 6
0
 def test_present_nocreation(self):
     with patch.dict(
             postgres_schema.__salt__,
         {
             'postgres.schema_get':
             Mock(return_value={'foo': {
                 'acl': '',
                 'owner': 'postgres'
             }}),
             'postgres.schema_create':
             MagicMock()
         }):
         ret = postgres_schema.present('dbname', 'foo')
         self.assertEqual(
             ret, {
                 'comment': 'Schema foo already exists in database dbname',
                 'changes': {},
                 'dbname': 'dbname',
                 'name': 'foo',
                 'result': True
             })
         self.assertEqual(
             self.salt_stub['postgres.schema_create'].call_count, 0)
Ejemplo n.º 7
0
 def test_get_success(self):
     '''
     Tests zfs get success
     '''
     res = OrderedDict([
         ('myzpool',
          OrderedDict([
              ('used', OrderedDict([
                  ('value', 906238099456),
              ])),
          ])),
     ])
     ret = {
         'pid': 562,
         'retcode': 0,
         'stderr': '',
         'stdout': 'myzpool\tused\t906238099456'
     }
     mock_cmd = MagicMock(return_value=ret)
     with patch.dict(zfs.__salt__, {'cmd.run_all': mock_cmd}), \
          patch.dict(zfs.__utils__, utils_patch):
         self.assertEqual(
             res, zfs.get('myzpool', properties='used', fields='value'))
Ejemplo n.º 8
0
    def test_eval_cron(self):
        '''
        verify that scheduled job runs
        '''
        job = {
            'schedule': {
                'job1': {
                    'function': 'test.ping',
                    'cron': '0 16 29 11 *'
                }
            }
        }

        # Add the job to the scheduler
        self.schedule.opts.update(job)

        run_time = dateutil_parser.parse('11/29/2017 4:00pm')
        with patch('croniter.croniter.get_next',
                   MagicMock(return_value=run_time)):
            self.schedule.eval(now=run_time)

        ret = self.schedule.job_status('job1')
        self.assertEqual(ret['_last_run'], run_time)
Ejemplo n.º 9
0
    def test_list_snapshots(self):
        '''
        Test parallels.list_snapshots
        '''
        name = 'macvm'
        guid_str = textwrap.dedent('''
            PARENT_SNAPSHOT_ID                      SNAPSHOT_ID
                                                    {a5b8999f-5d95-4aff-82de-e515b0101b66}
            {a5b8999f-5d95-4aff-82de-e515b0101b66} *{a7345be5-ab66-478c-946e-a6c2caf14909}
            {a5b8999f-5d95-4aff-82de-e515b0101b66}  {5da9faef-cb0e-466d-9b41-e5571b62ac2a}
        ''')

        # Validate listing all snapshots for the VM
        mock_prlctl = MagicMock(return_value=guid_str)
        with patch.object(parallels, 'prlctl', mock_prlctl):
            parallels.list_snapshots(name)
            mock_prlctl.assert_called_once_with('snapshot-list', [name], runas=None)

        # Validate listing all snapshots in tree mode
        mock_prlctl = MagicMock(return_value=guid_str)
        with patch.object(parallels, 'prlctl', mock_prlctl):
            parallels.list_snapshots(name, tree=True)
            mock_prlctl.assert_called_once_with('snapshot-list', [name, '--tree'], runas=None)

        # Validate listing a single snapshot
        snap_name = 'muon'
        mock_snap_name = MagicMock(return_value=snap_name)
        with patch.object(parallels, '_validate_snap_name', mock_snap_name):
            mock_prlctl = MagicMock(return_value=guid_str)
            with patch.object(parallels, 'prlctl', mock_prlctl):
                parallels.list_snapshots(name, snap_name)
                mock_prlctl.assert_called_once_with('snapshot-list',
                                                    [name, '--id', snap_name],
                                                    runas=None)

        # Validate listing snapshot ID and name pairs
        snap_names = ['electron', 'muon', 'tauon']
        mock_snap_name = MagicMock(side_effect=snap_names)
        with patch.object(parallels, 'snapshot_id_to_name', mock_snap_name):
            mock_prlctl = MagicMock(return_value=guid_str)
            with patch.object(parallels, 'prlctl', mock_prlctl):
                ret = parallels.list_snapshots(name, names=True)
                for snap_name in snap_names:
                    self.assertIn(snap_name, ret)
                mock_prlctl.assert_called_once_with('snapshot-list', [name], runas=None)
Ejemplo n.º 10
0
    def test_macro_additional_log_syntaxerror(self):
        '''
        If  we failed in a macro, get more output from trace.
        '''
        expected = r'''Jinja syntax error: expected token .*end.*got '-'.*
.*/macroerror\(2\):
---
# macro
\{% macro mymacro\(greeting, greetee='world'\) -\} <-- error is here    <======================
\{\{ greeting ~ ' ' ~ greetee \}\} !
\{%- endmacro %\}
---.*'''
        filename = os.path.join(TEMPLATES_DIR,
                                'files', 'test', 'hello_import_error')
        fc = MockFileClient()
        with patch.object(SaltCacheLoader, 'file_client', MagicMock(return_value=fc)):
            with salt.utils.fopen(filename) as fp_:
                self.assertRaisesRegex(
                    SaltRenderError,
                    expected,
                    render_jinja_tmpl,
                    fp_.read(),
                    dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
Ejemplo n.º 11
0
    def test_rename_set(self):
        '''
        Test for Delete ipset set.
        '''
        self.assertEqual(ipset.rename_set(),
                         'Error: Set needs to be specified')

        self.assertEqual(ipset.rename_set('s'),
                         'Error: New name for set needs to be specified')

        with patch.object(ipset, '_find_set_type', return_value=False):
            self.assertEqual(ipset.rename_set('s', 'd'),
                             'Error: Set does not exist')

        with patch.object(ipset, '_find_set_type', return_value=True):
            self.assertEqual(ipset.rename_set('s', 'd'),
                             'Error: New Set already exists')

        with patch.object(ipset, '_find_set_type', side_effect=[True, False]):
            with patch.object(ipset, '_ipset_cmd', return_value='A'):
                mock = MagicMock(return_value=True)
                with patch.dict(ipset.__salt__, {'cmd.run': mock}):
                    self.assertTrue(ipset.rename_set('set', 'new_set'))
Ejemplo n.º 12
0
    def test_macro_additional_log_for_undefined(self):
        '''
        If we failed in a macro because of undefined variables, get
        more output from trace.
        '''
        expected = r'''Jinja variable 'b' is undefined
.*/macroundefined\(2\):
---
\{% macro mymacro\(\) -%\}
\{\{b.greetee\}\} <-- error is here    <======================
\{%- endmacro %\}
---'''
        filename = os.path.join(TEMPLATES_DIR,
                                'files', 'test', 'hello_import_undefined')
        fc = MockFileClient()
        with patch.object(SaltCacheLoader, 'file_client', MagicMock(return_value=fc)):
            with salt.utils.fopen(filename) as fp_:
                self.assertRaisesRegex(
                    SaltRenderError,
                    expected,
                    render_jinja_tmpl,
                    fp_.read(),
                    dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
Ejemplo n.º 13
0
    def test_macro_additional_log_for_generalexc(self):
        '''
        If we failed in a macro because of e.g. a TypeError, get
        more output from trace.
        '''
        expected = r'''Jinja error:.*division.*
.*/macrogeneral\(2\):
---
\{% macro mymacro\(\) -%\}
\{\{ 1/0 \}\}    <======================
\{%- endmacro %\}
---.*'''
        filename = os.path.join(TEMPLATES_DIR,
                                'files', 'test', 'hello_import_generalerror')
        fc = MockFileClient()
        with patch.object(SaltCacheLoader, 'file_client', MagicMock(return_value=fc)):
            with salt.utils.fopen(filename) as fp_:
                self.assertRaisesRegex(
                    SaltRenderError,
                    expected,
                    render_jinja_tmpl,
                    fp_.read(),
                    dict(opts=self.local_opts, saltenv='test', salt=self.local_salt))
Ejemplo n.º 14
0
    def test_delete(self):
        """
        Test for delete message(s) from the mail queue
        """
        with patch.object(postfix, "show_queue", return_value={}):
            self.assertDictEqual(
                postfix.delete("queue_id"),
                {
                    "result": False,
                    "message": "No message in queue with ID queue_id"
                },
            )

        with patch.dict(
                postfix.__salt__,
            {"cmd.run_all": MagicMock(return_value={"retcode": 0})}):
            self.assertDictEqual(
                postfix.delete("ALL"),
                {
                    "result": True,
                    "message": "Successfully removed all messages"
                },
            )
Ejemplo n.º 15
0
 def test_get_policies_for_nonexisting_minions(self):
     minion_id = "salt_master"
     # For non-existing minions, or the master-minion, grains will be None
     cases = {
         "no-tokens-to-replace": ["no-tokens-to-replace"],
         "single-dict:{minion}": ["single-dict:{0}".format(minion_id)],
         "single-list:{grains[roles]}": [],
     }
     with patch(
         "salt.utils.minions.get_minion_data",
         MagicMock(return_value=(None, None, None)),
     ):
         for case, correct_output in six.iteritems(cases):
             test_config = {"policies": [case]}
             output = vault._get_policies(
                 minion_id, test_config
             )  # pylint: disable=protected-access
             diff = set(output).symmetric_difference(set(correct_output))
             if diff:
                 log.debug("Test %s failed", case)
                 log.debug("Expected:\n\t%s\nGot\n\t%s", output, correct_output)
                 log.debug("Difference:\n\t%s", diff)
             self.assertEqual(output, correct_output)
Ejemplo n.º 16
0
    def test_send_msg(self):
        '''
            Test to send a message to an XMPP user
        '''
        ret = {'name': 'salt', 'changes': {}, 'result': None, 'comment': ''}
        with patch.dict(xmpp.__opts__, {"test": True}):
            ret.update({'comment': 'Need to send message to myaccount: salt'})
            self.assertDictEqual(
                xmpp.send_msg('salt', 'myaccount', '*****@*****.**'), ret)

        with patch.dict(xmpp.__opts__, {"test": False}):
            mock = MagicMock(return_value=True)
            with patch.dict(xmpp.__salt__, {
                    'xmpp.send_msg': mock,
                    'xmpp.send_msg_multi': mock
            }):
                ret.update({
                    'result': True,
                    'comment': 'Sent message to myaccount: salt'
                })
                self.assertDictEqual(
                    xmpp.send_msg('salt', 'myaccount', '*****@*****.**'),
                    ret)
Ejemplo n.º 17
0
    def test_created_startup(self):
        '''
        Test with one vm and startup_create_event
        '''
        # NOTE: this should yield 1 created event + one state event
        with patch.dict(vmadm.VMADM_STATE, MOCK_CLEAN_STATE), \
             patch.dict(vmadm.__salt__, {'vmadm.list': MagicMock(return_value=MOCK_VM_ONE)}):

            config = [{'startup_create_event': True}]

            ret = vmadm.validate(config)
            self.assertEqual(ret, (True, 'Valid beacon configuration'))

            ret = vmadm.beacon(config)
            res = [{'alias': 'vm1',
                    'tag': 'created/00000000-0000-0000-0000-000000000001',
                    'hostname': 'vm1',
                    'dns_domain': 'example.org'},
                   {'alias': 'vm1',
                    'tag': 'running/00000000-0000-0000-0000-000000000001',
                    'hostname': 'vm1',
                    'dns_domain': 'example.org'}]
            self.assertEqual(ret, res)
Ejemplo n.º 18
0
 def test_nothing_to_be_done_test_mode(self):
     with patch.dict(esxdatacenter.__opts__, {"test": True}):
         with patch.dict(
                 esxdatacenter.__salt__,
             {
                 "vsphere.get_proxy_type":
                 MagicMock(return_value="different_proxy")
             },
         ):
             res = esxdatacenter.datacenter_configured("fake_dc")
     self.assertDictEqual(
         res,
         {
             "name":
             "fake_dc",
             "changes": {},
             "result":
             True,
             "comment":
             "Datacenter 'fake_dc' already "
             "exists. Nothing to be done.",
         },
     )
Ejemplo n.º 19
0
 def test_diff(self):
     '''
     Tests zfs diff
     '''
     res = [
         "1517063879.144517494\tM\t\t/data/test/",
         "1517063875.296592355\t+\t\t/data/test/world",
         "1517063879.274438467\t+\t\t/data/test/hello",
     ]
     ret = {}
     ret['retcode'] = 0
     ret['stdout'] = "\n".join([
         "1517063879.144517494\tM\t\t/data/test/",
         "1517063875.296592355\t+\t\t/data/test/world",
         "1517063879.274438467\t+\t\t/data/test/hello",
     ])
     ret['stderr'] = ''
     mock_cmd = MagicMock(return_value=ret)
     with patch.dict(zfs.__salt__, {'cmd.run_all': mock_cmd}), \
          patch.dict(zfs.__utils__, utils_patch):
         self.assertEqual(
             res,
             zfs.diff('myzpool/mydataset@yesterday', 'myzpool/mydataset'))
Ejemplo n.º 20
0
    def test_log_created(self):
        """
        Tests that log file is created
        """
        args = self.args
        log_file = self.log_file
        log_file_name = self.logfile_config_setting_name
        opts = self.testing_config.copy()
        opts.update({"log_file": log_file})
        if log_file_name != "log_file":
            opts.update({log_file_name: getattr(self, log_file_name)})

        if log_file_name == "key_logfile":
            self.skipTest("salt-key creates log file outside of parse_args.")

        parser = self.parser()
        with patch(self.config_func, MagicMock(return_value=opts)):
            parser.parse_args(args)

        if log_file_name == "log_file":
            self.assertEqual(os.path.getsize(log_file), 0)
        else:
            self.assertEqual(os.path.getsize(getattr(self, log_file_name)), 0)
Ejemplo n.º 21
0
 def test_recv_known_hosts_hashed_shoud_be_findable_by_ssh_keygen(self):
     hostname = 'example.com'
     port = 12345
     with tempfile.NamedTemporaryFile(mode='w+', delete=False) as temp_file:
         with patch.dict(ssh.__salt__, {'cmd.run': MagicMock(side_effect=_mock_ssh_keyscan)}):
             entries = ssh.recv_known_host_entries(
                 hostname=hostname,
                 port=port,
                 hash_known_hosts=True,
             )
             for entry in entries:
                 print(
                     '{0[hostname]} {0[enc]} {0[key]}'.format(entry),
                     file=temp_file,
                 )
             temp_file.flush()
             result = subprocess.check_output([
                 'ssh-keygen',
                 '-f',
                 temp_file.name,
                 '-F',
                 '[{hostname}]:{port}'.format(hostname=hostname, port=port),
             ])
Ejemplo n.º 22
0
    def test_match_index_versions(self):
        """
        Test to verifies that the master and the slave versions are in sync by
        comparing the index version.
        """
        err = 'solr.match_index_versions can only be called by "slave" minions'
        with patch.object(solr, "_get_return_dict", return_value={"A": "a"}):
            with patch.object(solr, "_is_master", side_effect=[True, False]):

                self.assertIsNone(solr.match_index_versions())

                with patch.object(solr, "_get_none_or_value", return_value=None):
                    with patch.object(solr, "_check_for_cores", return_value=True):
                        with patch.dict(
                            solr.__opts__, {"solr.cores": MagicMock(return_value="A")}
                        ):
                            with patch.object(
                                solr, "_replication_request", return_value="A"
                            ):
                                self.assertDictEqual(
                                    solr.match_index_versions(),
                                    {"A": "a", "errors": [err], "success": False},
                                )
Ejemplo n.º 23
0
    def test_log_created(self):
        '''
        Tests that log file is created
        '''
        args = self.args
        log_file = self.log_file
        log_file_name = self.logfile_config_setting_name
        opts = self.default_config.copy()
        opts.update({'log_file': log_file})
        if log_file_name != 'log_file':
            opts.update({log_file_name: getattr(self, log_file_name)})

        if log_file_name == 'key_logfile':
            self.skipTest('salt-key creates log file outside of parse_args.')

        parser = self.parser()
        with patch(self.config_func, MagicMock(return_value=opts)):
            parser.parse_args(args)

        if log_file_name == 'log_file':
            self.assertEqual(os.path.getsize(log_file), 0)
        else:
            self.assertEqual(os.path.getsize(getattr(self, log_file_name)), 0)
Ejemplo n.º 24
0
 def test_set_replication_enabled(self):
     """
     Test to sets the master to ignore poll requests from the slaves.
     """
     with patch.object(solr, "_is_master", side_effect=[False, True, True, True]):
         with patch.object(
             solr, "_get_none_or_value", side_effect=[None, None, True, True, True]
         ):
             with patch.object(
                 solr, "_get_return_dict", side_effect=[{"A": "a"}, {}]
             ):
                 with patch.object(solr, "_replication_request", return_value="A"):
                     self.assertDictEqual(
                         solr.set_replication_enabled("s"), {"A": "a"}
                     )
                     with patch.object(solr, "_check_for_cores", return_value=True):
                         with patch.dict(
                             solr.__opts__,
                             {"solr.cores": MagicMock(return_value="n")},
                         ):
                             self.assertEqual(solr.set_replication_enabled("s"), {})
                     self.assertEqual(solr.set_replication_enabled("s"), "A")
                     self.assertEqual(solr.set_replication_enabled(False), "A")
Ejemplo n.º 25
0
    def test_service_present(self):
        '''
        Test to ensure service present in Keystone catalog
        '''
        name = 'nova'
        service_type = 'compute'

        ret = {'name': name,
               'changes': {},
               'result': True,
               'comment': 'Service "{0}" already exists'.format(name)}

        mock_lst = MagicMock(side_effect=[[], ['Error']])
        with patch.dict(keystone.__salt__, {'keystone.service_get': mock_lst}):
            self.assertDictEqual(keystone.service_present(name, service_type),
                                 ret)

            with patch.dict(keystone.__opts__, {'test': True}):
                comt = ('Service "{0}" will be added'.format(name))
                ret.update({'comment': comt, 'result': None})
                self.assertDictEqual(keystone.service_present(name,
                                                              service_type),
                                     ret)
Ejemplo n.º 26
0
 def test_reload_core(self):
     """
     Test to load a new core from the same configuration as
     an existing registered core.
     """
     error = ['solr.reload_core can only be called by "multi-core" minions']
     with patch.object(
         solr, "_check_for_cores", side_effect=[False, True, True, True]
     ):
         with patch.object(solr, "_get_none_or_value", side_effect=[None, True]):
             with patch.object(solr, "_get_return_dict", return_value={"A": "a"}):
                 with patch.object(solr, "_format_url", return_value="A"):
                     with patch.object(solr, "_http_request", return_value="A"):
                         with patch.dict(
                             solr.__opts__,
                             {"solr.cores": MagicMock(return_value="n")},
                         ):
                             self.assertIsNone(solr.reload_core())
                             self.assertDictEqual(
                                 solr.reload_core(),
                                 {"A": "a", "errors": error, "success": False},
                             )
                             self.assertEqual(solr.reload_core(), "A")
Ejemplo n.º 27
0
 def setUp(self):
     self.name = "zabbix"
     self.context = "/files/etc/services"
     self.changes = [
         "ins service-name after service-name[last()]",
         "set service-name[last()] zabbix-agent",
     ]
     self.fp_changes = [
         "ins service-name after /files/etc/services/service-name[last()]",
         "set /files/etc/services/service-name[last()] zabbix-agent",
     ]
     self.ret = {"name": self.name, "result": False, "changes": {}, "comment": ""}
     method_map = {
         "set": "set",
         "setm": "setm",
         "mv": "move",
         "move": "move",
         "ins": "insert",
         "insert": "insert",
         "rm": "remove",
         "remove": "remove",
     }
     self.mock_method_map = MagicMock(return_value=method_map)
Ejemplo n.º 28
0
 def test_absent_test_mode(self):
     """
     Test to ensure that named action is absent in test mode
     """
     name = "Auto registration Databases"
     ret = {"name": name, "result": False, "comment": "", "changes": {}}
     with patch.dict(zabbix_action.__opts__, {"test": True}):
         with patch.dict(
                 zabbix_action.__salt__,
             {"zabbix.get_object_id_by_params": MagicMock(return_value=11)},
         ):
             ret["result"] = True
             ret["comment"] = 'Zabbix Action "{0}" would be deleted.'.format(
                 name)
             ret["changes"] = {
                 name: {
                     "old":
                     'Zabbix Action "{0}" exists.'.format(name),
                     "new":
                     'Zabbix Action "{0}" would be deleted.'.format(name),
                 }
             }
             self.assertDictEqual(zabbix_action.absent(name), ret)
Ejemplo n.º 29
0
    def test_rebooted(self):
        '''
        rebooted state test cases.
        '''
        ret = {'name': 'myvm',
               'changes': {},
               'result': True}

        reboot_mock = MagicMock(return_value=True)
        with patch.dict(virt.__salt__, {  # pylint: disable=no-member
                    'virt.list_domains': MagicMock(return_value=['myvm', 'vm1']),
                    'virt.reboot': reboot_mock
                }):
            ret.update({'changes': {
                            'rebooted': [{'domain': 'myvm', 'reboot': True}]
                        },
                        'comment': 'Machine has been rebooted'})
            self.assertDictEqual(virt.rebooted('myvm'), ret)
            reboot_mock.assert_called_with('myvm', connection=None, username=None, password=None)

        with patch.dict(virt.__salt__, {  # pylint: disable=no-member
                    'virt.list_domains': MagicMock(return_value=['myvm', 'vm1']),
                    'virt.reboot': reboot_mock,
                }):
            self.assertDictEqual(virt.rebooted('myvm',
                                               connection='myconnection',
                                               username='******',
                                               password='******'), ret)
            reboot_mock.assert_called_with('myvm',
                                           connection='myconnection',
                                           username='******',
                                           password='******')

        with patch.dict(virt.__salt__, {  # pylint: disable=no-member
                    'virt.list_domains': MagicMock(return_value=['myvm', 'vm1']),
                    'virt.reboot': MagicMock(side_effect=self.mock_libvirt.libvirtError('Some error'))
                }):
            ret.update({'changes': {'ignored': [{'domain': 'myvm', 'issue': 'Some error'}]},
                        'result': False,
                        'comment': 'No changes had happened'})
            self.assertDictEqual(virt.rebooted('myvm'), ret)

        with patch.dict(virt.__salt__, {'virt.list_domains': MagicMock(return_value=[])}):  # pylint: disable=no-member
            ret.update({'changes': {}, 'result': False, 'comment': 'No changes had happened'})
            self.assertDictEqual(virt.rebooted('myvm'), ret)
Ejemplo n.º 30
0
    def test_user_chpass(self):
        """
        Test changing a MySQL user password in mysql exec module
        """
        connect_mock = MagicMock()
        with patch.object(mysql, "_connect", connect_mock):
            with patch.object(mysql, "version", return_value="8.0.10"):
                with patch.object(mysql, "user_exists",
                                  MagicMock(return_value=True)):
                    with patch.dict(mysql.__salt__,
                                    {"config.option": MagicMock()}):
                        mysql.user_chpass("testuser", password="******")
                        calls = (
                            call().cursor().execute(
                                "UPDATE mysql.user SET Password=PASSWORD(%(password)s) WHERE User=%(user)s AND Host = %(host)s;",
                                {
                                    "password": "******",
                                    "user": "******",
                                    "host": "localhost",
                                },
                            ),
                            call().cursor().execute("FLUSH PRIVILEGES;"),
                        )
                        connect_mock.assert_has_calls(calls, any_order=True)

        connect_mock = MagicMock()
        with patch.object(mysql, "_connect", connect_mock):
            with patch.object(mysql, "version", return_value="8.0.11"):
                with patch.object(mysql, "user_exists",
                                  MagicMock(return_value=True)):
                    with patch.dict(mysql.__salt__,
                                    {"config.option": MagicMock()}):
                        mysql.user_chpass("testuser", password="******")
                        calls = (
                            call().cursor().execute(
                                "ALTER USER %(user)s@%(host)s IDENTIFIED BY %(password)s;",
                                {
                                    "password": "******",
                                    "user": "******",
                                    "host": "localhost",
                                },
                            ),
                            call().cursor().execute("FLUSH PRIVILEGES;"),
                        )
                        connect_mock.assert_has_calls(calls, any_order=True)