Esempio n. 1
0
    def test_get_locale(self):
        '''
        Test for Get the current system locale
        '''
        with patch.dict(localemod.__context__, {'salt.utils.systemd.booted': True}):
            with patch.multiple(localemod,
                               _parse_dbus_locale=MagicMock(return_value={'LANG': 'A'}),
                               HAS_DBUS=True):
                self.assertEqual('A', localemod.get_locale())
                localemod._parse_dbus_locale.assert_called_once_with()

            with patch.multiple(localemod,
                               _parse_localectl=MagicMock(return_value={'LANG': 'A'}),
                               HAS_DBUS=False):
                self.assertEqual('A', localemod.get_locale())
                localemod._parse_localectl.assert_called_once_with()

        with patch.dict(localemod.__context__, {'salt.utils.systemd.booted': False}):
            with patch.dict(localemod.__grains__, {'os_family': ['Gentoo']}):
                with patch.dict(localemod.__salt__, {'cmd.run': MagicMock(return_value='A')}):
                    with patch.object(localemod,
                                      '_parse_localectl',
                                      return_value={'LANG': 'A'}):
                        self.assertEqual(localemod.get_locale(), 'A')

            with patch.dict(localemod.__grains__, {'os_family': ['RedHat']}):
                with patch.dict(localemod.__salt__, {'cmd.run': MagicMock(return_value='A=B')}):
                    with patch.object(localemod,
                                      '_parse_localectl',
                                      return_value={'LANG': 'B'}):
                        self.assertEqual(localemod.get_locale(), 'B')

            with patch.dict(localemod.__grains__, {'os_family': ['Unknown']}):
                with patch.dict(localemod.__salt__, {'cmd.run': MagicMock(return_value='A=B')}):
                    self.assertRaises(CommandExecutionError, localemod.get_locale)
    def test_present_from_scratch(self):
        mock_get = MagicMock(return_value={"result": None})

        with patch.multiple(
                boto_cloudfront,
                __salt__={"boto_cloudfront.get_distribution": mock_get},
                __opts__={"test": True},
        ):
            comment = "Distribution {0} set for creation.".format(self.name)
            self.assertDictEqual(
                boto_cloudfront.present(self.name, self.config, self.tags),
                self.base_ret_with({
                    "result": None,
                    "comment": comment,
                    "changes": {
                        "old": None,
                        "new": self.name
                    },
                }),
            )

        mock_create_failure = MagicMock(return_value={"error": "create error"})
        with patch.multiple(
                boto_cloudfront,
                __salt__={
                    "boto_cloudfront.get_distribution": mock_get,
                    "boto_cloudfront.create_distribution": mock_create_failure,
                },
                __opts__={"test": False},
        ):
            comment = "Error creating distribution {0}: create error"
            self.assertDictEqual(
                boto_cloudfront.present(self.name, self.config, self.tags),
                self.base_ret_with({
                    "result": False,
                    "comment": comment.format(self.name)
                }),
            )

        mock_create_success = MagicMock(return_value={"result": True})
        with patch.multiple(
                boto_cloudfront,
                __salt__={
                    "boto_cloudfront.get_distribution": mock_get,
                    "boto_cloudfront.create_distribution": mock_create_success,
                },
                __opts__={"test": False},
        ):
            comment = "Created distribution {0}."
            self.assertDictEqual(
                boto_cloudfront.present(self.name, self.config, self.tags),
                self.base_ret_with({
                    "result": True,
                    "comment": comment.format(self.name),
                    "changes": {
                        "old": None,
                        "new": self.name
                    },
                }),
            )
Esempio n. 3
0
    def test_present_from_scratch(self):
        mock_get = MagicMock(return_value={'result': None})

        with patch.multiple(
                boto_cloudfront,
                __salt__={'boto_cloudfront.get_distribution': mock_get},
                __opts__={'test': True},
        ):
            comment = 'Distribution {0} set for creation.'.format(self.name)
            self.assertDictEqual(
                boto_cloudfront.present(self.name, self.config, self.tags),
                self.base_ret_with({
                    'result': None,
                    'comment': comment,
                    'pchanges': {
                        'old': None,
                        'new': self.name
                    },
                }),
            )

        mock_create_failure = MagicMock(return_value={'error': 'create error'})
        with patch.multiple(
                boto_cloudfront,
                __salt__={
                    'boto_cloudfront.get_distribution': mock_get,
                    'boto_cloudfront.create_distribution': mock_create_failure,
                },
                __opts__={'test': False},
        ):
            comment = 'Error creating distribution {0}: create error'
            self.assertDictEqual(
                boto_cloudfront.present(self.name, self.config, self.tags),
                self.base_ret_with({
                    'result': False,
                    'comment': comment.format(self.name),
                }),
            )

        mock_create_success = MagicMock(return_value={'result': True})
        with patch.multiple(
                boto_cloudfront,
                __salt__={
                    'boto_cloudfront.get_distribution': mock_get,
                    'boto_cloudfront.create_distribution': mock_create_success,
                },
                __opts__={'test': False},
        ):
            comment = 'Created distribution {0}.'
            self.assertDictEqual(
                boto_cloudfront.present(self.name, self.config, self.tags),
                self.base_ret_with({
                    'result': True,
                    'comment': comment.format(self.name),
                    'changes': {
                        'old': None,
                        'new': self.name
                    },
                }),
            )
Esempio n. 4
0
    def setUp(self):
        loader_module = getattr(self, 'loader_module', None)
        if loader_module is not None:
            if NO_MOCK:
                self.skipTest(NO_MOCK_REASON)

            loader_module_name = loader_module.__name__
            loader_module_globals = getattr(self, 'loader_module_globals',
                                            None)
            loader_module_blacklisted_dunders = getattr(
                self, 'loader_module_blacklisted_dunders', ())
            if loader_module_globals is None:
                loader_module_globals = {}
            elif callable(loader_module_globals):
                loader_module_globals = loader_module_globals()
            else:
                loader_module_globals = copy.deepcopy(loader_module_globals)

            salt_dunders = (
                '__opts__',
                '__salt__',
                '__runner__',
                '__context__',
                '__utils__',
                '__ext_pillar__',
                '__thorium__',
                '__states__',
                '__serializers__',
                '__ret__',
                '__grains__',
                '__pillar__',
                '__sdb__',
                # Proxy is commented out on purpose since some code in salt expects a NameError
                # and is most of the time not a required dunder
                # '__proxy__'
            )
            for dunder_name in salt_dunders:
                if dunder_name not in loader_module_globals:
                    if dunder_name in loader_module_blacklisted_dunders:
                        continue
                    loader_module_globals[dunder_name] = {}

            for key in loader_module_globals:
                if not hasattr(loader_module, key):
                    if key in salt_dunders:
                        setattr(loader_module, key, {})
                    else:
                        setattr(loader_module, key, None)

            if loader_module_globals:
                patcher = patch.multiple(loader_module_name,
                                         **loader_module_globals)
                patcher.start()

                def cleanup(patcher, loader_module_globals):
                    patcher.stop()
                    del loader_module_globals

                self.addCleanup(cleanup, patcher, loader_module_globals)
        super(LoaderModuleMockMixin, self).setUp()
Esempio n. 5
0
    def setup_log(self):
        """
        Mock logger functions
        """
        testing_config = self.default_config.copy()
        testing_config["root_dir"] = self.root_dir
        for name in ("pki_dir", "cachedir"):
            testing_config[name] = name
        testing_config[self.logfile_config_setting_name] = getattr(
            self, self.logfile_config_setting_name, self.log_file)
        self.testing_config = testing_config
        self.addCleanup(setattr, self, "testing_config", None)

        self.log_impl = LogImplMock()
        self.addCleanup(self.log_impl._destroy)
        self.addCleanup(setattr, self, "log_impl", None)

        mocked_functions = {}
        for name in dir(self.log_impl):
            if name.startswith("_"):
                continue
            func = getattr(self.log_impl, name)
            if not callable(func):
                continue
            mocked_functions[name] = func
        patcher = patch.multiple(salt._logging, **mocked_functions)
        patcher.start()
        self.addCleanup(patcher.stop)
Esempio n. 6
0
    def test_cpustats_openbsd(self):
        """
        Test modules.status.cpustats function for OpenBSD
        """
        m = self._set_up_test_cpustats_openbsd()

        systat = (
            "\n"
            "\n"
            "   1 users Load 0.20 0.07 0.05                        salt.localdomain 09:42:42\n"
            "CPU                User           Nice        System     Interrupt          Idle\n"
            "0                  0.0%           0.0%          4.5%          0.5%         95.0%\n"
        )

        with patch.multiple(
                salt.utils.platform,
                is_linux=MagicMock(return_value=False),
                is_sunos=MagicMock(return_value=False),
                is_darwin=MagicMock(return_value=False),
                is_freebsd=MagicMock(return_value=False),
                is_openbsd=MagicMock(return_value=True),
                is_netbsd=MagicMock(return_value=False),
        ), patch("salt.utils.path.which",
                 MagicMock(return_value=True)), patch.dict(
                     status.__grains__, {"kernel": "OpenBSD"}), patch.dict(
                         status.__salt__,
                         {"cmd.run": MagicMock(return_value=systat)}):
            ret = status.cpustats()
            self.assertDictEqual(ret, m.ret)
Esempio n. 7
0
    def test_repo_noadd_mod_ref(self):
        '''
        Test mod_repo detects the repo already exists,
        calls modify to update 'autorefresh' and refreshes the repo with
            `zypper --gpg-auto-import-keys refresh <repo-name>`

        :return:
        '''
        url = self.new_repo_config['url']
        name = self.new_repo_config['name']
        self.zypper_patcher_config['_get_configured_repos'] = Mock(
            **{'return_value.sections.return_value': [name]}
        )
        zypper_patcher = patch.multiple(
            'salt.modules.zypper', **self.zypper_patcher_config)

        with zypper_patcher:
            zypper.mod_repo(
                name,
                **{'url': url, 'refresh': True, 'gpgautoimport': True}
            )
            self.assertEqual(
                zypper.__zypper__.xml.call.call_args_list,
                [call('--gpg-auto-import-keys', 'refresh', name)]
            )
            zypper.__zypper__.refreshable.xml.call.assert_called_once_with(
                '--gpg-auto-import-keys', 'mr', '--refresh', name
            )
Esempio n. 8
0
 def test_uptime_sunos(self):
     """
     Test modules.status.uptime function for SunOS
     """
     m = self._set_up_test_uptime()
     m2 = self._set_up_test_uptime_sunos()
     with patch.multiple(
             salt.utils.platform,
             is_linux=MagicMock(return_value=False),
             is_sunos=MagicMock(return_value=True),
             is_darwin=MagicMock(return_value=False),
             is_freebsd=MagicMock(return_value=False),
             is_openbsd=MagicMock(return_value=False),
             is_netbsd=MagicMock(return_value=False),
     ), patch("salt.utils.path.which",
              MagicMock(return_value=True)), patch.dict(
                  status.__salt__,
                  {
                      "cmd.run":
                      MagicMock(
                          return_value=os.linesep.join(["1", "2", "3"])),
                      "cmd.run_all":
                      MagicMock(return_value=m2.ret),
                  },
              ), patch("time.time", MagicMock(return_value=m.now)):
         ret = status.uptime()
         self.assertDictEqual(ret, m.ret)
Esempio n. 9
0
def test_present_correct_state():
    name = "my_distribution"
    base_ret = {"name": name, "changes": {}}
    # Most attributes elided since there are so many required ones
    config = {"Enabled": True, "HttpVersion": "http2"}
    tags = {"test_tag1": "value1"}

    mock_get = MagicMock(
        return_value={
            "result": {
                "distribution": {
                    "DistributionConfig": config
                },
                "tags": tags,
                "etag": "test etag",
            }
        })
    with patch.multiple(
            boto_cloudfront,
            __salt__={"boto_cloudfront.get_distribution": mock_get},
            __opts__={"test": False},
    ):
        comment = "Distribution {0} has correct config."
        assert boto_cloudfront.present(name, config, tags) == base_ret_with({
            "result":
            True,
            "comment":
            comment.format(name)
        })
Esempio n. 10
0
    def test_uptime_macos(self):
        '''
        Test modules.status.uptime function for macOS
        '''
        m = self._set_up_test_uptime()

        kern_boottime = (
            '{{ sec = {0}, usec = {1:0<6} }} Mon Oct 03 03:09:18.23 2016'
            ''.format(*str(m.now - m.ut).split('.')))
        with patch.multiple(salt.utils,
                            is_linux=MagicMock(return_value=False),
                            is_sunos=MagicMock(return_value=False),
                            is_darwin=MagicMock(return_value=True),
                            is_freebsd=MagicMock(return_value=False),
                            is_openbsd=MagicMock(return_value=False),
                            is_netbsd=MagicMock(return_value=False)):
            with patch.dict(
                    status.__salt__, {
                        'cmd.run': MagicMock(return_value="1\n2\n3"),
                        'sysctl.get': MagicMock(return_value=kern_boottime)
                    }):
                with patch('time.time', MagicMock(return_value=m.now)):
                    ret = status.uptime()
                    self.assertDictEqual(ret, m.ret)

            with patch.dict(status.__salt__,
                            {'sysctl.get': MagicMock(return_value='')}):
                with self.assertRaises(CommandExecutionError):
                    status.uptime()
Esempio n. 11
0
 def test_remove_noaction(self):
     """
     Test - Remove packages.
     """
     with patch(
             "salt.modules.opkg.list_pkgs",
             MagicMock(side_effect=[self.packages, self.packages]),
     ):
         std_out = "\nRemoving vim (7.4) from root...\n"
         ret_value = {"retcode": 0, "stdout": std_out}
         mock = MagicMock(return_value=ret_value)
         patch_kwargs = {
             "__salt__": {
                 "cmd.run_all":
                 mock,
                 "pkg_resource.parse_targets":
                 MagicMock(return_value=({
                     "vim": "7.4"
                 }, "repository")),
                 "restartcheck.restartcheck":
                 MagicMock(
                     return_value="No packages seem to need to be restarted"
                 ),
             }
         }
         with patch.multiple(opkg, **patch_kwargs):
             self.assertEqual(opkg.remove("vim:7.4", test=True),
                              self.removed)
Esempio n. 12
0
    def test_upgrade_downloadonly(self):
        '''
        Tests the download-only options for upgrade.
        '''
        with patch('salt.utils.pkg.clear_rtag', MagicMock()):
            with patch('salt.modules.aptpkg.list_pkgs',
                       MagicMock(return_value=UNINSTALL)):
                mock_cmd = MagicMock(return_value={
                    'retcode': 0,
                    'stdout': UPGRADE
                })
                patch_kwargs = {
                    '__salt__': {
                        'config.get': MagicMock(return_value=True),
                        'cmd.run_all': mock_cmd
                    },
                }
                with patch.multiple(aptpkg, **patch_kwargs):
                    aptpkg.upgrade()
                    args_matching = [True for args in patch_kwargs['__salt__']['cmd.run_all'].call_args[0] if "--download-only" in args]
                    # Here we shouldn't see the parameter and args_matching should be empty.
                    self.assertFalse(any(args_matching))

                    aptpkg.upgrade(downloadonly=True)
                    args_matching = [True for args in patch_kwargs['__salt__']['cmd.run_all'].call_args[0] if "--download-only" in args]
                    # --download-only should be in the args list and we should have at least on True in the list.
                    self.assertTrue(any(args_matching))

                    aptpkg.upgrade(download_only=True)
                    args_matching = [True for args in patch_kwargs['__salt__']['cmd.run_all'].call_args[0] if "--download-only" in args]
                    # --download-only should be in the args list and we should have at least on True in the list.
                    self.assertTrue(any(args_matching))
Esempio n. 13
0
    def test_repo_add_mod_ref(self):
        '''
        Test mod_repo adds the new repo,
        calls modify to update 'autorefresh' and refreshes the repo with
            `zypper --gpg-auto-import-keys refresh <repo-name>`

        :return:
        '''
        zypper_patcher = patch.multiple(
            'salt.modules.zypper', **self.zypper_patcher_config)

        url = self.new_repo_config['url']
        name = self.new_repo_config['name']
        with zypper_patcher:
            zypper.mod_repo(
                name,
                **{'url': url, 'refresh': True, 'gpgautoimport': True}
            )
            self.assertEqual(
                zypper.__zypper__.xml.call.call_args_list,
                [
                    call('ar', url, name),
                    call('--gpg-auto-import-keys', 'refresh', name)
                ]
            )
            zypper.__zypper__.refreshable.xml.call.assert_called_once_with(
                '--gpg-auto-import-keys', 'mr', '--refresh', name
            )
Esempio n. 14
0
 def test_install_noaction(self):
     """
     Test - Install packages.
     """
     with patch("salt.modules.opkg.list_pkgs",
                MagicMock(side_effect=({}, {}))):
         std_out = "Downloading http://feedserver/feeds/test/vim_7.4_arch.ipk.\n\nInstalling vim (7.4) on root\n"
         ret_value = {"retcode": 0, "stdout": std_out}
         mock = MagicMock(return_value=ret_value)
         patch_kwargs = {
             "__salt__": {
                 "cmd.run_all":
                 mock,
                 "pkg_resource.parse_targets":
                 MagicMock(return_value=({
                     "vim": "7.4"
                 }, "repository")),
                 "restartcheck.restartcheck":
                 MagicMock(
                     return_value="No packages seem to need to be restarted"
                 ),
             }
         }
         with patch.multiple(opkg, **patch_kwargs):
             self.assertEqual(opkg.install("vim:7.4", test=True),
                              self.installed)
Esempio n. 15
0
 def test_push(self):
     '''
     Test if push works with good posix path.
     '''
     filename = '/saltines/test.file'
     with patch('salt.modules.cp.os.path',
                MagicMock(isfile=Mock(return_value=True), wraps=cp.os.path)), \
             patch.multiple('salt.modules.cp',
                            _auth=MagicMock(**{'return_value.gen_token.return_value': 'token'}),
                            __opts__={'id': 'abc', 'file_buffer_size': 10}), \
             patch('salt.utils.files.fopen', mock_open(read_data=b'content')) as m_open, \
             patch('salt.transport.Channel.factory', MagicMock()):
         response = cp.push(filename)
         assert response, response
         num_opens = len(m_open.filehandles[filename])
         assert num_opens == 1, num_opens
         fh_ = m_open.filehandles[filename][0]
         assert fh_.read.call_count == 2, fh_.read.call_count
         salt.transport.Channel.factory({}).send.assert_called_once_with(
             dict(
                 loc=fh_.tell(),  # pylint: disable=resource-leakage
                 cmd='_file_recv',
                 tok='token',
                 path=['saltines', 'test.file'],
                 data=
                 b'',  # data is empty here because load['data'] is overwritten
                 id='abc'))
Esempio n. 16
0
    def test_uptime_linux(self):
        """
        Test modules.status.uptime function for Linux
        """
        m = self._set_up_test_uptime()

        with patch.multiple(
                salt.utils.platform,
                is_linux=MagicMock(return_value=True),
                is_sunos=MagicMock(return_value=False),
                is_darwin=MagicMock(return_value=False),
                is_freebsd=MagicMock(return_value=False),
                is_openbsd=MagicMock(return_value=False),
                is_netbsd=MagicMock(return_value=False),
        ), patch("salt.utils.path.which",
                 MagicMock(return_value=True)), patch.dict(
                     status.__salt__,
                     {
                         "cmd.run":
                         MagicMock(
                             return_value=os.linesep.join(["1", "2", "3"]))
                     },
                 ), patch("time.time", MagicMock(return_value=m.now)), patch(
                     "os.path.exists", MagicMock(return_value=True)):
            proc_uptime = salt.utils.stringutils.to_str("{} {}".format(
                m.ut, m.idle))

            with patch("salt.utils.files.fopen",
                       mock_open(read_data=proc_uptime)):
                ret = status.uptime()
                self.assertDictEqual(ret, m.ret)
            with patch("os.path.exists", MagicMock(return_value=False)):
                with self.assertRaises(CommandExecutionError):
                    status.uptime()
Esempio n. 17
0
    def test_repo_noadd_modbaseurl_ref(self):
        '''
        Test mod_repo detects the repo already exists,
        no modification was requested and no refresh requested either

        :return:
        '''
        url = self.new_repo_config['url']
        name = self.new_repo_config['name']
        self.zypper_patcher_config['_get_configured_repos'] = Mock(
            **{'return_value.sections.side_effect': [[name], [], [], [name]]}
        )
        zypper_patcher = patch.multiple(
            'salt.modules.zypper', **self.zypper_patcher_config)

        with zypper_patcher:
            params = {'baseurl': url + "-changed", 'enabled': False}
            zypper.mod_repo(name, **params)
            expected_params = {
                'alias': 'mock-repo-name',
                'autorefresh': True,
                'baseurl': 'http://repo.url/some/path-changed',
                'enabled': False,
                'priority': 1,
                'cache': False,
                'keeppackages': False,
                'type': 'rpm-md'}
            self.assertTrue(zypper.mod_repo.call_count == 2)
            self.assertTrue(zypper.mod_repo.mock_calls[1] == call(name, **expected_params))
Esempio n. 18
0
def test_upgrade_allow_downgrades(uninstall_var, upgrade_var):
    """
    Tests the allow_downgrades option for upgrade.
    """
    with patch("salt.utils.pkg.clear_rtag", MagicMock()):
        with patch("salt.modules.aptpkg.list_pkgs",
                   MagicMock(return_value=uninstall_var)):
            mock_cmd = MagicMock(return_value={
                "retcode": 0,
                "stdout": upgrade_var
            })
            patch_kwargs = {
                "__salt__": {
                    "config.get": MagicMock(return_value=True),
                    "cmd.run_all": mock_cmd,
                },
            }
            with patch.multiple(aptpkg, **patch_kwargs):
                aptpkg.upgrade()
                args_matching = [
                    True for args in patch_kwargs["__salt__"]
                    ["cmd.run_all"].call_args[0]
                    if "--allow-downgrades" in args
                ]
                # Here we shouldn't see the parameter and args_matching should be empty.
                assert any(args_matching) is False

                aptpkg.upgrade(allow_downgrades=True)
                args_matching = [
                    True for args in patch_kwargs["__salt__"]
                    ["cmd.run_all"].call_args[0]
                    if "--allow-downgrades" in args
                ]
                # --allow-downgrades should be in the args list and we should have at least on True in the list.
                assert any(args_matching) is True
Esempio n. 19
0
 def setup_log(self):
     """
     Mock logger functions
     """
     testing_config = self.default_config.copy()
     testing_config["root_dir"] = self.root_dir
     for name in ("pki_dir", "cachedir"):
         testing_config[name] = name
     testing_config[self.logfile_config_setting_name] = getattr(
         self, self.logfile_config_setting_name, self.log_file)
     self.testing_config = testing_config
     self.addCleanup(setattr, self, "testing_config", None)
     self.log_setup = LogSetupMock()
     patcher = patch.multiple(
         log,
         setup_console_logger=self.log_setup.setup_console_logger,
         setup_extended_logging=self.log_setup.setup_extended_logging,
         setup_logfile_logger=self.log_setup.setup_logfile_logger,
         get_multiprocessing_logging_queue=self.log_setup.
         get_multiprocessing_logging_queue,
         setup_multiprocessing_logging_listener=self.log_setup.
         setup_multiprocessing_logging_listener,
         setup_temp_logger=self.log_setup.setup_temp_logger,
     )
     patcher.start()
     self.addCleanup(patcher.stop)
     self.addCleanup(setattr, self, "log_setup", None)
Esempio n. 20
0
 def setup_log(self):
     '''
     Mock logger functions
     '''
     testing_config = self.default_config.copy()
     testing_config['root_dir'] = self.root_dir
     for name in ('pki_dir', 'cachedir'):
         testing_config[name] = name
     testing_config[self.logfile_config_setting_name] = getattr(
         self, self.logfile_config_setting_name, self.log_file)
     self.testing_config = testing_config
     self.addCleanup(setattr, self, 'testing_config', None)
     self.log_setup = LogSetupMock()
     patcher = patch.multiple(
         log,
         setup_console_logger=self.log_setup.setup_console_logger,
         setup_extended_logging=self.log_setup.setup_extended_logging,
         setup_logfile_logger=self.log_setup.setup_logfile_logger,
         get_multiprocessing_logging_queue=self.log_setup.
         get_multiprocessing_logging_queue,
         setup_multiprocessing_logging_listener=self.log_setup.
         setup_multiprocessing_logging_listener,
         setup_temp_logger=self.log_setup.setup_temp_logger)
     patcher.start()
     self.addCleanup(patcher.stop)
     self.addCleanup(setattr, self, 'log_setup', None)
Esempio n. 21
0
    def test_uptime_linux(self):
        '''
        Test modules.status.uptime function for Linux
        '''
        m = self._set_up_test_uptime()

        with patch.multiple(salt.utils,
                            is_linux=MagicMock(return_value=True),
                            is_sunos=MagicMock(return_value=False),
                            is_darwin=MagicMock(return_value=False),
                            is_freebsd=MagicMock(return_value=False),
                            is_openbsd=MagicMock(return_value=False),
                            is_netbsd=MagicMock(return_value=False)):
            with patch.dict(status.__salt__,
                            {'cmd.run': MagicMock(return_value="1\n2\n3")}):
                with patch('time.time', MagicMock(return_value=m.now)):
                    with patch('os.path.exists', MagicMock(return_value=True)):
                        proc_uptime = '{0} {1}'.format(m.ut, m.idle)
                        with patch('salt.utils.fopen',
                                   mock_open(read_data=proc_uptime)):
                            ret = status.uptime()
                            self.assertDictEqual(ret, m.ret)

                    with patch('os.path.exists',
                               MagicMock(return_value=False)):
                        with self.assertRaises(CommandExecutionError):
                            status.uptime()
Esempio n. 22
0
def test_previous_and_next_releases():
    with patch.multiple(
        SaltVersionsInfo,
        _previous_release=None,
        _next_release=None,
        _current_release=SaltVersionsInfo.CALIFORNIUM,
    ):
        assert SaltVersionsInfo.current_release() == SaltVersionsInfo.CALIFORNIUM
        assert SaltVersionsInfo.next_release() == SaltVersionsInfo.EINSTEINIUM
        assert SaltVersionsInfo.previous_release() == SaltVersionsInfo.BERKELIUM

    with patch.multiple(
        SaltVersionsInfo,
        _previous_release=None,
        _next_release=None,
        _current_release=SaltVersionsInfo.NEPTUNIUM,
    ):
        assert SaltVersionsInfo.current_release() == SaltVersionsInfo.NEPTUNIUM
        assert SaltVersionsInfo.next_release() == SaltVersionsInfo.PLUTONIUM
        assert SaltVersionsInfo.previous_release() == SaltVersionsInfo.URANIUM
Esempio n. 23
0
 def test_zip(self):
     with patch('glob.glob', lambda pathname: [pathname]):
         with patch.multiple(os.path, **{'isdir': MagicMock(return_value=False),
                                         'exists': MagicMock(return_value=True)}):
             with patch('zipfile.ZipFile', MagicMock()):
                 ret = archive.zip_(
                     '/tmp/salt.{{grains.id}}.zip',
                     '/tmp/tmpePe8yO,/tmp/tmpLeSw1A',
                     template='jinja'
                 )
                 self.assertEqual(['tmp/tmpePe8yO', 'tmp/tmpLeSw1A'], ret)
Esempio n. 24
0
 def test_upgrade(self):
     '''
     Test - Upgrades all packages.
     '''
     mock_cmd = MagicMock(return_value={'retcode': 0, 'stdout': UPGRADE})
     patch_kwargs = {
         '__salt__': {
             'config.get': MagicMock(return_value=True),
             'cmd.run_all': mock_cmd
         }
     }
     with patch.multiple(aptpkg, **patch_kwargs):
         self.assertEqual(aptpkg.upgrade(), dict())
Esempio n. 25
0
    def __init__(self, stdout=None, stderr=None):
        # Late import
        import salt.utils
        if stdout is None:
            stdout = salt.utils.fopen(os.devnull, 'w')  # pylint: disable=resource-leakage
        if stderr is None:
            stderr = salt.utils.fopen(os.devnull, 'w')  # pylint: disable=resource-leakage

        self.__stdout = stdout
        self.__stderr = stderr
        self.__redirected = False
        self.patcher = patch.multiple(sys,
                                      stderr=self.__stderr,
                                      stdout=self.__stdout)
Esempio n. 26
0
 def test_gen_keys(self):
     with patch.multiple(os, umask=MagicMock(), chmod=MagicMock(),
                         access=MagicMock(return_value=True)):
         with patch('salt.utils.files.fopen', mock_open()):
             open_priv_wb = call('/keydir{0}keyname.pem'.format(os.sep), 'wb+')
             open_pub_wb = call('/keydir{0}keyname.pub'.format(os.sep), 'wb+')
             with patch('os.path.isfile', return_value=True):
                 self.assertEqual(crypt.gen_keys('/keydir', 'keyname', 2048), '/keydir{0}keyname.pem'.format(os.sep))
                 self.assertNotIn(open_priv_wb, salt.utils.files.fopen.mock_calls)
                 self.assertNotIn(open_pub_wb, salt.utils.files.fopen.mock_calls)
             with patch('os.path.isfile', return_value=False):
                 with patch('salt.utils.files.fopen', mock_open()):
                     crypt.gen_keys('/keydir', 'keyname', 2048)
                     salt.utils.files.fopen.assert_has_calls([open_priv_wb, open_pub_wb], any_order=True)
 def test_present_distribution_retrieval_error(self):
     """
     Test for boto_cloudfront.present when we cannot get the distribution.
     """
     mock_get = MagicMock(return_value={"error": "get_distribution error"})
     with patch.multiple(
         boto_cloudfront,
         __salt__={"boto_cloudfront.get_distribution": mock_get},
         __opts__={"test": False},
     ):
         comment = "Error checking distribution {0}: get_distribution error"
         assert boto_cloudfront.present(self.name, self.config, self.tags) == self.base_ret_with(
             {"result": False, "comment": comment.format(self.name)}
         )
Esempio n. 28
0
 def test_uptime_return_success_not_supported(self):
     '''
     Test modules.status.uptime function for other platforms
     '''
     with patch.multiple(salt.utils,
                         is_linux=MagicMock(return_value=False),
                         is_sunos=MagicMock(return_value=False),
                         is_darwin=MagicMock(return_value=False),
                         is_freebsd=MagicMock(return_value=False),
                         is_openbsd=MagicMock(return_value=False),
                         is_netbsd=MagicMock(return_value=False)):
         exc_mock = MagicMock(side_effect=CommandExecutionError)
         with self.assertRaises(CommandExecutionError):
             with patch.dict(status.__salt__, {'cmd.run': exc_mock}):
                 status.uptime()
Esempio n. 29
0
 def test_autoremove(self):
     '''
     Test - Remove packages not required by another package.
     '''
     patch_kwargs = {
         '__salt__': {
             'config.get': MagicMock(return_value=True),
             'cmd.run': MagicMock(return_value=AUTOREMOVE)
         }
     }
     with patch.multiple(aptpkg, **patch_kwargs):
         self.assertEqual(aptpkg.autoremove(), dict())
         self.assertEqual(aptpkg.autoremove(purge=True), dict())
         self.assertEqual(aptpkg.autoremove(list_only=True), list())
         self.assertEqual(aptpkg.autoremove(list_only=True, purge=True),
                          list())
Esempio n. 30
0
 def test_remove(self):
     '''
     Test - Remove packages.
     '''
     with patch('salt.modules.opkg.list_pkgs', MagicMock(side_effect=[PACKAGES, {}])):
         ret_value = {'retcode': 0}
         mock = MagicMock(return_value=ret_value)
         patch_kwargs = {
             '__salt__': {
                 'cmd.run_all': mock,
                 'pkg_resource.parse_targets': MagicMock(return_value=({'vim': '7.4'}, 'repository')),
                 'restartcheck.restartcheck': MagicMock(return_value='No packages seem to need to be restarted')
             }
         }
         with patch.multiple(opkg, **patch_kwargs):
             self.assertEqual(opkg.remove('vim'), REMOVED)