Beispiel #1
0
 def test_install_cached_requirements_used(self, get_cached_requirements):
     get_cached_requirements.return_value = "my_cached_reqs"
     mock = MagicMock(return_value={"retcode": 0, "stdout": ""})
     with patch.dict(pip.__salt__, {"cmd.run_all": mock}):
         pip.install(requirements="salt://requirements.txt")
         expected_cmd = "pip install --requirement='my_cached_reqs'"
         mock.assert_called_once_with(expected_cmd, saltenv="base", runas=None, cwd=None)
Beispiel #2
0
    def test_check_mine_cache_is_refreshed_on_container_change_event(self, _):
        '''
        Every command that might modify docker containers state.
        Should trig an update on ``mine.send``
        '''

        for command_name, args in (('create', ()),
                                   ('rm_', ()),
                                   ('kill', ()),
                                   ('pause', ()),
                                   ('signal_', ('KILL',)),
                                   ('start', ()),
                                   ('stop', ()),
                                   ('unpause', ()),
                                   ('_run', ('command',)),
                                   ('_script', ('command',)),
                                   ):
            mine_send = Mock()
            command = getattr(dockerng_mod, command_name)
            docker_client = MagicMock()
            docker_client.api_version = '1.12'
            with patch.dict(dockerng_mod.__salt__,
                            {'mine.send': mine_send,
                             'container_resource.run': MagicMock(),
                             'cp.cache_file': MagicMock(return_value=False)}):
                with patch.dict(dockerng_mod.__context__,
                                {'docker.client': docker_client}):
                    command('container', *args)
            mine_send.assert_called_with('dockerng.ps', verbose=True, all=True,
                                         host=True)
Beispiel #3
0
    def test_uninstall_log_argument_in_resulting_command(self, mock_path):
        pkg = 'pep8'
        log_path = '/tmp/pip-install.log'
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
            pip.uninstall(pkg, log=log_path)
            mock.assert_called_once_with(
                ['pip', 'uninstall', '-y', '--log', log_path, pkg],
                saltenv='base',
                runas=None,
                cwd=None,
                use_vt=False,
                python_shell=False,
            )

        # Let's fake a non-writable log file
        mock_path.exists.side_effect = IOError('Fooo!')
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
            self.assertRaises(
                IOError,
                pip.uninstall,
                pkg,
                log=log_path
            )
Beispiel #4
0
    def run_contents_pillar(self, pillar_value, expected):
        def returner(contents, *args, **kwargs):
            returner.returned = (contents, args, kwargs)
        returner.returned = None

        filestate.__salt__ = {
            'file.manage_file': returner
        }

        path = '/tmp/foo'
        pillar_path = 'foo:bar'

        # the values don't matter here
        filestate.__salt__['config.manage_mode'] = MagicMock()
        filestate.__salt__['file.source_list'] = MagicMock(return_value=[None, None])
        filestate.__salt__['file.get_managed'] = MagicMock(return_value=[None, None, None])

        # pillar.get should return the pillar_value
        pillar_mock = MagicMock(return_value=pillar_value)
        filestate.__salt__['pillar.get'] = pillar_mock

        ret = filestate.managed(path, contents_pillar=pillar_path)

        # make sure the pillar_mock is called with the given path
        pillar_mock.assert_called_once_with(pillar_path)

        # make sure no errors are returned
        self.assertEquals(None, ret)

        # make sure the value is correct
        self.assertEquals(expected, returner.returned[1][-1])
Beispiel #5
0
    def run_contents_pillar(self, pillar_value, expected):
        returner = MagicMock(return_value=None)

        filestate.__salt__ = {"file.manage_file": returner}

        path = "/tmp/foo"
        pillar_path = "foo:bar"

        # the values don't matter here
        filestate.__salt__["config.manage_mode"] = MagicMock()
        filestate.__salt__["file.source_list"] = MagicMock(return_value=[None, None])
        filestate.__salt__["file.get_managed"] = MagicMock(return_value=[None, None, None])

        # pillar.get should return the pillar_value
        pillar_mock = MagicMock(return_value=pillar_value)
        filestate.__salt__["pillar.get"] = pillar_mock

        ret = filestate.managed(path, contents_pillar=pillar_path)

        # make sure the pillar_mock is called with the given path
        pillar_mock.assert_called_once_with(pillar_path)

        # make sure no errors are returned
        self.assertEqual(None, ret)

        # make sure the value is correct
        self.assertEqual(expected, returner.call_args[0][-2])
Beispiel #6
0
 def test_get_managed_object_name(self):
     mock_get_managed_object_name = MagicMock()
     with patch('salt.utils.vmware.get_managed_object_name',
                mock_get_managed_object_name):
         vmware.create_cluster(self.mock_dc, 'fake_cluster',
                               self.mock_cluster_spec)
     mock_get_managed_object_name.assert_called_once_with(self.mock_dc)
Beispiel #7
0
 def test_uwsgi_stats(self):
     socket = "127.0.0.1:5050"
     mock = MagicMock(return_value='{"a": 1, "b": 2}')
     with patch.dict(uwsgi.__salt__, {"cmd.run": mock}):
         result = uwsgi.stats(socket)
         mock.assert_called_once_with(["uwsgi", "--connect-and-read", "{0}".format(socket)], python_shell=False)
         self.assertEqual(result, {"a": 1, "b": 2})
    def test_freeze_command(self):
        eggs = [
            'M2Crypto==0.21.1',
            '-e [email protected]:s0undt3ch/salt-testing.git@9ed81aa2f918d59d3706e56b18f0782d1ea43bf8#egg=SaltTesting-dev',
            'bbfreeze==1.1.0',
            'bbfreeze-loader==1.1.0',
            'pycrypto==2.6'
        ]
        mock = MagicMock(
            return_value={
                'retcode': 0,
                'stdout': '\n'.join(eggs)
            }
        )
        with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
            ret = pip.freeze()
            mock.assert_called_once_with(
                'pip freeze',
                runas=None,
                cwd=None,
                python_shell=False,
            )
            self.assertEqual(ret, eggs)

        # Non zero returncode raises exception?
        mock = MagicMock(return_value={'retcode': 1, 'stderr': 'CABOOOOMMM!'})
        with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
            self.assertRaises(
                CommandExecutionError,
                pip.freeze,
            )
Beispiel #9
0
    def test_list_pkgs(self):
        '''
        Test for listing installed packages.
        '''
        def _add_data(data, key, value):
            data[key] = value

        pkg_info_out = [
            'png-1.6.23',
            'vim-7.4.1467p1-gtk2',  # vim--gtk2
            'ruby-2.3.1p1'  # ruby%2.3
        ]
        run_stdout_mock = MagicMock(return_value='\n'.join(pkg_info_out))
        patches = {
            'cmd.run_stdout': run_stdout_mock,
            'pkg_resource.add_pkg': _add_data,
            'pkg_resource.sort_pkglist': MagicMock(),
            'pkg_resource.stringify': MagicMock(),
        }
        with patch.dict(openbsdpkg.__salt__, patches):
            pkgs = openbsdpkg.list_pkgs()
            self.assertDictEqual(pkgs, {
                'png': '1.6.23',
                'vim--gtk2': '7.4.1467p1',
                'ruby': '2.3.1p1'})
        run_stdout_mock.assert_called_once_with('pkg_info -q -a',
                                                output_loglevel='trace')
Beispiel #10
0
 def test_symlinks_argument(self):
     # We test for pyvenv only because with virtualenv this is un
     # unsupported option.
     mock = MagicMock(return_value={"retcode": 0, "stdout": ""})
     with patch.dict(virtualenv_mod.__salt__, {"cmd.run_all": mock}):
         virtualenv_mod.create("/tmp/foo", venv_bin="pyvenv", symlinks=True)
         mock.assert_called_once_with(["pyvenv", "--symlinks", "/tmp/foo"], runas=None, python_shell=False)
Beispiel #11
0
    def test_list_command(self):
        eggs = [
            "M2Crypto==0.21.1",
            "-e [email protected]:s0undt3ch/salt-testing.git@9ed81aa2f918d59d3706e56b18f0782d1ea43bf8#egg=SaltTesting-dev",
            "bbfreeze==1.1.0",
            "bbfreeze-loader==1.1.0",
            "pycrypto==2.6",
        ]
        mock = MagicMock(
            side_effect=[{"retcode": 0, "stdout": "pip MOCKED_VERSION"}, {"retcode": 0, "stdout": "\n".join(eggs)}]
        )
        with patch.dict(pip.__salt__, {"cmd.run_all": mock}):
            ret = pip.list_()
            mock.assert_called_with("pip freeze", runas=None, cwd=None)
            self.assertEqual(
                ret,
                {
                    "SaltTesting-dev": "[email protected]:s0undt3ch/salt-testing.git@9ed81aa2f918d59d3706e56b18f0782d1ea43bf8",
                    "M2Crypto": "0.21.1",
                    "bbfreeze-loader": "1.1.0",
                    "bbfreeze": "1.1.0",
                    "pip": "MOCKED_VERSION",
                    "pycrypto": "2.6",
                },
            )

        # Non zero returncode raises exception?
        mock = MagicMock(return_value={"retcode": 1, "stderr": "CABOOOOMMM!"})
        with patch.dict(pip.__salt__, {"cmd.run_all": mock}):
            self.assertRaises(CommandExecutionError, pip.list_)
Beispiel #12
0
 def test_install_download_cache_argument_in_resulting_command(self):
     mock = MagicMock(return_value={"retcode": 0, "stdout": ""})
     with patch.dict(pip.__salt__, {"cmd.run_all": mock}):
         pip.install("pep8", download_cache="/tmp/foo")
         mock.assert_called_once_with(
             "pip install --download-cache=/tmp/foo 'pep8'", saltenv="base", runas=None, cwd=None
         )
Beispiel #13
0
 def test_install_extra_index_url_argument_in_resulting_command(self):
     mock = MagicMock(return_value={"retcode": 0, "stdout": ""})
     with patch.dict(pip.__salt__, {"cmd.run_all": mock}):
         pip.install("pep8", extra_index_url="http://foo.tld")
         mock.assert_called_once_with(
             "pip install --extra-index-url='http://foo.tld' 'pep8'", saltenv="base", runas=None, cwd=None
         )
Beispiel #14
0
 def test_clear_argument(self):
     mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
     with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
         virtualenv_mod.create('/tmp/foo', clear=True)
         mock.assert_called_once_with(
             'virtualenv --clear /tmp/foo', runas=None
         )
Beispiel #15
0
    def test_delete_volume(self):
        '''
        Test if it deletes a gluster volume.
        '''
        mock_info = MagicMock(return_value={'Newvolume1': {'status': '1'}})
        with patch.object(glusterfs, 'info', mock_info):
            # volume doesn't exist
            self.assertFalse(glusterfs.delete_volume('Newvolume3'))

            mock_stop_volume = MagicMock(return_value=True)
            mock_run = MagicMock(return_value=xml_command_success)
            with patch.dict(glusterfs.__salt__, {'cmd.run': mock_run}):
                with patch.object(glusterfs, 'stop_volume', mock_stop_volume):
                    # volume exists, should not be stopped, and is started
                    self.assertFalse(glusterfs.delete_volume('Newvolume1',
                                                             False))
                    self.assertFalse(mock_run.called)
                    self.assertFalse(mock_stop_volume.called)

                    # volume exists, should be stopped, and is started
                    self.assertTrue(glusterfs.delete_volume('Newvolume1'))
                    self.assertTrue(mock_run.called)
                    self.assertTrue(mock_stop_volume.called)

        # volume exists and isn't started
        mock_info = MagicMock(return_value={'Newvolume1': {'status': '2'}})
        with patch.object(glusterfs, 'info', mock_info):
            mock_run = MagicMock(return_value=xml_command_success)
            with patch.dict(glusterfs.__salt__, {'cmd.run': mock_run}):
                self.assertTrue(glusterfs.delete_volume('Newvolume1'))
                mock_run.return_value = xml_command_fail
                self.assertFalse(glusterfs.delete_volume('Newvolume1'))
 def test_list_command_with_prefix(self):
     eggs = [
         'M2Crypto==0.21.1',
         '-e [email protected]:s0undt3ch/salt-testing.git@9ed81aa2f918d59d3706e56b18f0782d1ea43bf8#egg=SaltTesting-dev',
         'bbfreeze==1.1.0',
         'bbfreeze-loader==1.1.0',
         'pycrypto==2.6'
     ]
     mock = MagicMock(
         return_value={
             'retcode': 0,
             'stdout': '\n'.join(eggs)
         }
     )
     with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
         ret = pip.list_(prefix='bb')
         mock.assert_called_with(
             'pip freeze',
             runas=None,
             cwd=None,
             python_shell=False,
         )
         self.assertEqual(
             ret, {
                 'bbfreeze-loader': '1.1.0',
                 'bbfreeze': '1.1.0',
             }
         )
Beispiel #17
0
    def test_add_volume_bricks(self):
        '''
        Test if it add brick(s) to an existing volume
        '''
        mock_info = MagicMock(return_value={
            'Newvolume1': {
                'status': '1',
                'bricks': {
                    'brick1': {'path': 'host:/path1'},
                    'brick2': {'path': 'host:/path2'}
                }
            }
        })
        with patch.object(glusterfs, 'info', mock_info):
            mock_run = MagicMock(return_value=xml_command_success)
            with patch.dict(glusterfs.__salt__, {'cmd.run': mock_run}):
                # Volume does not exist
                self.assertFalse(glusterfs.add_volume_bricks('nonExisting',
                                                             ['bricks']))
                # Brick already exists
                self.assertTrue(glusterfs.add_volume_bricks('Newvolume1',
                                                       ['host:/path2']))
                # Already existing brick as a string
                self.assertTrue(glusterfs.add_volume_bricks('Newvolume1',
                                                            'host:/path2'))
                self.assertFalse(mock_run.called)
                # A new brick:
                self.assertTrue(glusterfs.add_volume_bricks('Newvolume1',
                                                            ['host:/new1']))
                self.assertTrue(mock_run.called)

                # Gluster call fails
                mock_run.return_value = xml_command_fail
                self.assertFalse(glusterfs.add_volume_bricks('Newvolume1',
                                                             ['new:/path']))
Beispiel #18
0
    def test_set_proxy_windows(self):
        '''
            Test to make sure we can set the proxy settings on Windows
        '''
        proxy.__grains__['os'] = 'Windows'
        expected = {
            'changes': {},
            'comment': 'Proxy settings updated correctly',
            'name': '192.168.0.1',
            'result': True
        }

        set_proxy_mock = MagicMock(return_value=True)
        patches = {
            'proxy.get_proxy_win': MagicMock(return_value={}),
            'proxy.get_proxy_bypass': MagicMock(return_value=[]),
            'proxy.set_proxy_win': set_proxy_mock,
        }

        with patch.dict(proxy.__salt__, patches):
            out = proxy.managed('192.168.0.1', '3128', user='******', password='******',
                                bypass_domains=['salt.com', 'test.com'])

            set_proxy_mock.assert_called_once_with('192.168.0.1', '3128', ['http', 'https', 'ftp'],
                                                   ['salt.com', 'test.com'])
            self.assertEqual(out, expected)
    def test_installed_enabled(self):
        '''
            Test enabling an already enabled bundle ID
        '''
        expected = {
            'changes': {},
            'comment': 'Already in the correct state',
            'name': 'com.apple.Chess',
            'result': True
        }

        installed_mock = MagicMock(return_value=True)
        install_mock = MagicMock()
        enabled_mock = MagicMock(return_value=True)
        enable_mock = MagicMock()

        with patch.dict(assistive.__salt__, {'assistive.installed': installed_mock,
                                             'assistive.install': install_mock,
                                             'assistive.enabled': enabled_mock,
                                             'assistive.enable': enable_mock}):
            out = assistive.installed('com.apple.Chess')
            enabled_mock.assert_called_once_with('com.apple.Chess')
            assert not enable_mock.called
            assert not install_mock.called
            self.assertEqual(out, expected)
Beispiel #20
0
 def test__rvm(self):
     mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
     with patch.dict(rvm.__salt__, {'cmd.run_all': mock}):
         rvm._rvm('install', '1.9.3')
         mock.assert_called_once_with(
             '/usr/local/rvm/bin/rvm install 1.9.3', runas=None
         )
Beispiel #21
0
    def test_package_removed_removed(self):
        '''
            Test removing a package already removed
        '''
        expected = {
            'comment': "The package Pack2 is already removed",
            'changes': {},
            'name': 'Pack2',
            'result': True}

        mock_removed = MagicMock(
            side_effect=[['Pack1'], ['Pack1']])
        mock_remove = MagicMock()
        mock_info = MagicMock(
            return_value={'Package Identity': 'Pack2'})

        with patch.dict(
            dism.__salt__, {'dism.installed_packages': mock_removed,
                            'dism.remove_package': mock_remove,
                            'dism.package_info': mock_info}):

            out = dism.package_removed('Pack2')

            mock_removed.assert_called_once_with()
            assert not mock_remove.called
            self.assertEqual(out, expected)
Beispiel #22
0
    def test_add_serial_missing(self):
        '''
            Test adding a certificate to specified certificate store when the file doesn't exist
        '''
        expected = {
            'changes': {},
            'comment': 'Certificate file not found.',
            'name': '/path/to/cert.cer',
            'result': False
        }

        cache_mock = MagicMock(return_value=False)
        get_cert_serial_mock = MagicMock(return_value='ABCDEF')
        get_store_serials_mock = MagicMock(return_value=['123456'])
        add_mock = MagicMock(return_value='Added successfully')
        with patch.dict(certutil.__salt__, {'cp.cache_file': cache_mock,
                                            'certutil.get_cert_serial': get_cert_serial_mock,
                                            'certutil.get_stored_cert_serials': get_store_serials_mock,
                                            'certutil.add_store': add_mock}):
            out = certutil.add_store('/path/to/cert.cer', 'TrustedPublisher')
            cache_mock.assert_called_once_with('/path/to/cert.cer', 'base')
            assert not get_cert_serial_mock.called
            assert not get_store_serials_mock.called
            assert not add_mock.called
            self.assertEqual(expected, out)
Beispiel #23
0
    def test_installed_activated(self):
        '''
            Test activating the given product key when its already activated
        '''
        expected = {
            'changes': {},
            'comment': 'Windows is already activated.',
            'name': 'AAAAA-AAAAA-AAAAA-AAAA-AAAAA-ABCDE',
            'result': True
        }

        info = {
            'description': 'Prof',
            'licensed': True,
            'name': 'Win7',
            'partial_key': 'ABCDE'
        }

        info_mock = MagicMock(return_value=info)
        install_mock = MagicMock(return_value='Installed successfully')
        activate_mock = MagicMock(return_value='Activated successfully')
        with patch.dict(license.__salt__, {'license.info': info_mock,
                                           'license.install': install_mock,
                                           'license.activate': activate_mock}):
            out = license.activate('AAAAA-AAAAA-AAAAA-AAAA-AAAAA-ABCDE')
            info_mock.assert_called_once_with()
            assert not install_mock.called
            assert not activate_mock.called
            self.assertEqual(out, expected)
Beispiel #24
0
 def test_wipe(self):
     mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
     with patch.dict(blockdev.__salt__, {'cmd.run_all': mock}):
         blockdev.wipe('/dev/sda')
         mock.assert_called_once_with(
             'wipefs /dev/sda'
         )
Beispiel #25
0
    def test_installed_pkg_version_succeeds(self, _mod_run_check_mock):
        '''
            Test installing a PKG file where the version number matches the current installed version
        '''
        expected = {
            'changes': {},
            'comment': 'Version already matches .*5\\.1\\.[0-9]',
            'name': '/path/to/file.pkg',
            'result': True
        }

        installed_mock = MagicMock(return_value=['com.apple.id', 'some.other.id'])
        get_pkg_id_mock = MagicMock(return_value=['some.other.id'])
        install_mock = MagicMock(return_value={'retcode': 0})
        cmd_mock = MagicMock(return_value='Version of this: 5.1.9')
        _mod_run_check_mock.return_value = True

        with patch.dict(macpackage.__salt__, {'macpackage.installed_pkgs': installed_mock,
                                              'macpackage.get_pkg_id': get_pkg_id_mock,
                                              'macpackage.install': install_mock,
                                              'cmd.run': cmd_mock}):
            out = macpackage.installed('/path/to/file.pkg', version_check=r'/usr/bin/runme --version=.*5\.1\.[0-9]')
            cmd_mock.assert_called_once_with('/usr/bin/runme --version', output_loglevel="quiet", ignore_retcode=True)
            assert not installed_mock.called
            assert not get_pkg_id_mock.called
            assert not install_mock.called
            self.assertEqual(out, expected)
Beispiel #26
0
    def _test_clone_type(self, clone_type):
        '''
        Assertions for checking that a certain clone type
        works
        '''
        obj_ref = MagicMock()
        obj_ref.snapshot = vim.vm.Snapshot(None, None)
        obj_ref.snapshot.currentSnapshot = vim.vm.Snapshot(None, None)
        clone_spec = vmware.handle_snapshot(
            vim.vm.ConfigSpec(),
            obj_ref,
            vim.vm.RelocateSpec(),
            False,
            {'snapshot': {
                'disk_move_type': clone_type}})
        self.assertEqual(clone_spec.location.diskMoveType, clone_type)

        obj_ref2 = MagicMock()
        obj_ref2.snapshot = vim.vm.Snapshot(None, None)
        obj_ref2.snapshot.currentSnapshot = vim.vm.Snapshot(None, None)

        clone_spec2 = vmware.handle_snapshot(
            vim.vm.ConfigSpec(),
            obj_ref2,
            vim.vm.RelocateSpec(),
            True,
            {'snapshot': {
                'disk_move_type': clone_type}})

        self.assertEqual(clone_spec2.location.diskMoveType, clone_type)
Beispiel #27
0
 def test_get_properties_of_managed_object_call(self):
     mock_get_properties_of_managed_object = MagicMock()
     with patch('salt.utils.vmware.get_properties_of_managed_object',
                mock_get_properties_of_managed_object):
         salt.utils.vmware.get_managed_object_name(self.mock_mo_ref)
     mock_get_properties_of_managed_object.assert_called_once_with(
         self.mock_mo_ref, ['name'])
Beispiel #28
0
 def test_reboot_with_timeout_in_seconds(self):
     '''
         Test to reboot the system with a timeout
     '''
     mock = MagicMock(return_value='salt')
     with patch.dict(win_system.__salt__, {'cmd.run': mock}):
         self.assertEqual(win_system.reboot(5, in_seconds=True), 'salt')
         mock.assert_called_once_with(['shutdown', '/r', '/t', '5'], python_shell=False)
Beispiel #29
0
 def test_reboot(self):
     '''
         Test to reboot the system
     '''
     mock = MagicMock(return_value='salt')
     with patch.dict(win_system.__salt__, {'cmd.run': mock}):
         self.assertEqual(win_system.reboot(), 'salt')
         mock.assert_called_once_with(['shutdown', '/r', '/t', '300'], python_shell=False)
Beispiel #30
0
 def test_uninstall(self):
     '''
         Test Uninstalling an APP package with a specific target
     '''
     mock = MagicMock()
     with patch.dict(macpackage.__salt__, {'file.remove': mock}):
         macpackage.uninstall_app('/path/to/file.app')
         mock.assert_called_once_with('/path/to/file.app')
Beispiel #31
0
class PsTestCase(TestCase):
    def test__needs_change(self):
        self.assertTrue(cron._needs_change(True, False))

    def test__needs_change_random(self):
        '''
        Assert that if the new var is 'random' and old is '* that we return True
        '''
        self.assertTrue(cron._needs_change('*', 'random'))

    ## Still trying to figure this one out.
    # def test__render_tab(self):
    #     pass
    def test__get_cron_cmdstr_solaris(self):
        cron.__grains__ = __grains__
        with patch.dict(cron.__grains__, {'os_family': 'Solaris'}):
            self.assertEqual('su - root -c "crontab /tmp"',
                             cron._get_cron_cmdstr(STUB_USER, STUB_PATH))

    def test__get_cron_cmdstr(self):
        cron.__grains__ = __grains__
        with patch.dict(cron.__grains__, {'os_family': None}):
            self.assertEqual('crontab -u root /tmp',
                             cron._get_cron_cmdstr(STUB_USER, STUB_PATH))

    def test__date_time_match(self):
        '''
        Passes if a match is found on all elements. Note the conversions to strings here!
        :return:
        '''
        self.assertTrue(
            cron._date_time_match(STUB_CRON_TIMESTAMP,
                                  minute=STUB_CRON_TIMESTAMP['minute'],
                                  hour=STUB_CRON_TIMESTAMP['hour'],
                                  daymonth=STUB_CRON_TIMESTAMP['daymonth'],
                                  dayweek=STUB_CRON_TIMESTAMP['dayweek']))

    @patch('salt.modules.cron.raw_cron',
           new=MagicMock(return_value=STUB_SIMPLE_RAW_CRON))
    def test_list_tab(self):
        self.assertDictEqual(STUB_SIMPLE_CRON_DICT,
                             cron.list_tab('DUMMY_USER'))

    @patch('salt.modules.cron._write_cron_lines')
    @patch('salt.modules.cron.list_tab',
           new=MagicMock(return_value=STUB_SIMPLE_CRON_DICT))
    def test_set_special(self, write_cron_lines_mock):
        expected_write_call = call('DUMMY_USER', [
            '5 0 * * * /tmp/no_script.sh\n',
            '# Lines below here are managed by Salt, do not edit\n',
            '@hourly echo Hi!\n'
        ])
        ret = cron.set_special('DUMMY_USER', '@hourly', 'echo Hi!')
        write_cron_lines_mock.assert_has_calls(expected_write_call)

    def test__get_cron_date_time(self):
        ret = cron._get_cron_date_time(
            minute=STUB_CRON_TIMESTAMP['minute'],
            hour=STUB_CRON_TIMESTAMP['hour'],
            daymonth=STUB_CRON_TIMESTAMP['daymonth'],
            dayweek=STUB_CRON_TIMESTAMP['dayweek'],
            month=STUB_CRON_TIMESTAMP['month'])
        self.assertDictEqual(ret, STUB_CRON_TIMESTAMP)

    ## FIXME: More sophisticated _get_cron_date_time checks should be added here.

    @patch('salt.modules.cron._write_cron_lines',
           new=MagicMock(return_value={'retcode': False}))
    @patch('salt.modules.cron.raw_cron',
           new=MagicMock(return_value=STUB_SIMPLE_RAW_CRON))
    def test_set_job(self):
        cron.__grains__ = __grains__
        with patch.dict(cron.__grains__, {'os': None}):
            cron.set_job('DUMMY_USER', 1, 2, 3, 4, 5, '/bin/echo NOT A DROID',
                         'WERE YOU LOOKING FOR ME?')
            expected_call = call('DUMMY_USER', [
                '5 0 * * * /tmp/no_script.sh\n',
                '# Lines below here are managed by Salt, do not edit\n',
                '# WERE YOU LOOKING FOR ME?\n',
                '1 2 3 4 5 /bin/echo NOT A DROID\n'
            ])
            cron._write_cron_lines.call_args.assert_called_with(expected_call)

    @patch('salt.modules.cron._write_cron_lines',
           new=MagicMock(return_value={'retcode': False}))
    @patch('salt.modules.cron.raw_cron',
           new=MagicMock(return_value=STUB_SIMPLE_RAW_CRON))
    def test_rm_job_is_absent(self):
        with patch.dict(cron.__grains__, {'os': None}):
            ret = cron.rm_job('DUMMY_USER', '/bin/echo NOT A DROID', 1, 2, 3,
                              4, 5)
            self.assertEqual('absent', ret)
Beispiel #32
0
    '''
    Extended TestCase class containing additional helper methods.
    '''
    def assertRaisesWithMessage(self, exc_type, exc_msg, func, *args,
                                **kwargs):
        try:
            func(*args, **kwargs)
            self.assertFail()
        except Exception as exc:
            self.assertEqual(type(exc), exc_type)
            self.assertEqual(exc.message, exc_msg)


@skipIf(not HAS_CERTS, 'Cannot find CA cert bundle')
@skipIf(NO_MOCK, NO_MOCK_REASON)
@patch('salt.cloud.clouds.gce.__virtual__', MagicMock(return_value='gce'))
@patch('libcloud.common.google.GoogleInstalledAppAuthConnection.get_new_token',
       MagicMock(return_value=DUMMY_TOKEN))
@patch('libcloud.compute.drivers.gce.GCENodeDriver.ex_list_zones',
       MagicMock(return_value=[]))
@patch('libcloud.compute.drivers.gce.GCENodeDriver.ex_list_regions',
       MagicMock(return_value=[]))
class GCETestCase(ExtendedTestCase):
    '''
    Unit TestCase for salt.cloud.clouds.gce module.
    '''
    def test_destroy_call(self):
        '''
        Tests that a SaltCloudSystemExit is raised when trying to call destroy
        with --function or -f.
        '''
Beispiel #33
0
class PostgresUserTestCase(TestCase):
    @patch.dict(
        SALT_STUB, {
            'postgres.role_get': Mock(return_value=None),
            'postgres.user_create': MagicMock(),
        })
    def test_present__creation(self):
        # test=True
        with patch.dict(postgres_user.__opts__, {'test': True}):
            ret = postgres_user.present('foo')
            self.assertEqual(
                ret, {
                    'comment': 'User foo is set to be created',
                    'changes': {},
                    'name': 'foo',
                    'result': None
                })
            self.assertEqual(SALT_STUB['postgres.user_create'].call_count, 0)

        # test=False
        ret = postgres_user.present('foo')
        self.assertEqual(
            ret, {
                'comment': 'The user foo has been created',
                'changes': {
                    'foo': 'Present'
                },
                'name': 'foo',
                'result': True
            })
        SALT_STUB['postgres.user_create'].assert_called_once_with(
            username='******',
            superuser=None,
            encrypted=True,
            runas=None,
            inherit=None,
            rolepassword=None,
            port=None,
            replication=None,
            host=None,
            createroles=None,
            user=None,
            groups=None,
            maintenance_db=None,
            login=None,
            password=None,
            createdb=None)

    @patch.dict(
        SALT_STUB, {
            'postgres.role_get':
            Mock(
                return_value={
                    'can create databases': False,
                    'can create roles': False,
                    'can login': False,
                    'can update system catalogs': False,
                    'connections': None,
                    'defaults variables': {},
                    'expiry time': None,
                    'inherits privileges': True,
                    'replication': False,
                    'superuser': False,
                }),
            'postgres.user_update':
            MagicMock(),
        })
    def test_present__update(self):
        # test=True
        with patch.dict(postgres_user.__opts__, {'test': True}):
            ret = postgres_user.present('foo', login=True, replication=False)
            self.assertEqual(
                ret, {
                    'comment': 'User foo is set to be updated',
                    'changes': {
                        'foo': {
                            'login': True
                        }
                    },
                    'name': 'foo',
                    'result': None
                })
            self.assertEqual(SALT_STUB['postgres.user_update'].call_count, 0)

        # test=False
        ret = postgres_user.present('foo', login=True, replication=False)
        self.assertEqual(
            ret, {
                'comment': 'The user foo has been updated',
                'changes': {
                    'foo': {
                        'login': True
                    }
                },
                'name': 'foo',
                'result': True
            })
        SALT_STUB['postgres.user_update'].assert_called_once_with(
            username='******',
            superuser=None,
            encrypted=True,
            runas=None,
            inherit=None,
            rolepassword=None,
            port=None,
            replication=False,
            host=None,
            createroles=None,
            user=None,
            groups=None,
            maintenance_db=None,
            login=True,
            password=None,
            createdb=None)

    @patch.dict(
        SALT_STUB, {
            'postgres.role_get':
            Mock(
                return_value={
                    'can create databases': False,
                    'can create roles': False,
                    'can login': False,
                    'can update system catalogs': False,
                    'connections': None,
                    'defaults variables': {},
                    'expiry time': None,
                    'inherits privileges': True,
                    'replication': False,
                    'superuser': False,
                }),
            'postgres.user_update':
            MagicMock(),
        })
    def test_present__no_update(self):
        # test=True
        with patch.dict(OPTS, {'test': True}):
            ret = postgres_user.present('foo', login=False, replication=False)
            self.assertEqual(
                ret, {
                    'comment': 'User foo is already present',
                    'changes': {},
                    'name': 'foo',
                    'result': True
                })
            self.assertEqual(SALT_STUB['postgres.user_update'].call_count, 0)

        # test=False
        ret = postgres_user.present('foo', login=False, replication=False)
        self.assertEqual(
            ret, {
                'comment': 'User foo is already present',
                'changes': {},
                'name': 'foo',
                'result': True
            })
        self.assertEqual(SALT_STUB['postgres.user_update'].call_count, 0)
Beispiel #34
0
# Import python libs
from __future__ import absolute_import

# Import Salt Libs
import salt.utils.url

# Import Salt Testing Libs
from salttesting import TestCase, skipIf
from salttesting.helpers import ensure_in_syspath
from salttesting.mock import (MagicMock, patch, NO_MOCK, NO_MOCK_REASON)

ensure_in_syspath('../../')


@patch('salt.utils.is_windows', MagicMock(return_value=False))
@skipIf(NO_MOCK, NO_MOCK_REASON)
class UrlTestCase(TestCase):
    '''
    TestCase for salt.utils.url module
    '''

    # parse tests

    def test_parse_path(self):
        '''
        Test parsing an ordinary path
        '''
        path = 'interesting?/path&.conf:and other things'

        self.assertEqual(salt.utils.url.parse(path), (path, None))
Beispiel #35
0
# Import Salt Testing libs
from salttesting import skipIf, TestCase
from salttesting.helpers import (ensure_in_syspath, TestsLoggingHandler,
                                 ForceImportErrorOn)
from salttesting.mock import NO_MOCK, NO_MOCK_REASON, MagicMock, patch

ensure_in_syspath('../../')

# Import salt libs
from salt.modules import virtualenv_mod
from salt.exceptions import CommandExecutionError

virtualenv_mod.__salt__ = {}
virtualenv_mod.__opts__['venv_bin'] = 'virtualenv'
base_virtualenv_mock = MagicMock()
base_virtualenv_mock.__version__ = '1.9.1'


@skipIf(NO_MOCK, NO_MOCK_REASON)
@patch('salt.utils.which', lambda bin_name: bin_name)
@patch.dict('sys.modules', {'virtualenv': base_virtualenv_mock})
class VirtualenvTestCase(TestCase):
    def test_issue_6029_deprecated_distribute(self):
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})

        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            virtualenv_mod._install_script = MagicMock(return_value={
                'retcode': 0,
                'stdout': 'Installed script!',
                'stderr': ''
Beispiel #36
0
    def test_prompt_argument(self):
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            virtualenv_mod.create('/tmp/foo', prompt='PY Prompt')
            mock.assert_called_once_with(
                'virtualenv --prompt=\'PY Prompt\' /tmp/foo', runas=None)

        # Now with some quotes on the mix
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            virtualenv_mod.create('/tmp/foo', prompt='\'PY\' Prompt')
            mock.assert_called_once_with(
                'virtualenv --prompt="\'PY\' Prompt" /tmp/foo', runas=None)

        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            virtualenv_mod.create('/tmp/foo', prompt='"PY" Prompt')
            mock.assert_called_once_with(
                'virtualenv --prompt=\'"PY" Prompt\' /tmp/foo', runas=None)
Beispiel #37
0
    def test_list_worktrees(self):
        '''
        This tests git.list_worktrees
        '''
        def _build_worktree_output(path):
            '''
            Build 'git worktree list' output for a given path
            '''
            return 'worktree {0}\nHEAD {1}\n{2}\n'.format(
                path,
                WORKTREE_INFO[path]['HEAD'],
                'branch {0}'.format(WORKTREE_INFO[path]['branch'])
                    if WORKTREE_INFO[path]['branch'] != 'detached'
                    else 'detached'
            )

        # Build dict for _cmd_run_side_effect below. Start with the output from
        # 'git worktree list'.
        _cmd_run_values = {
            'git worktree list --porcelain': '\n'.join(
                [_build_worktree_output(x) for x in WORKTREE_INFO]
            ),
            'git --version': 'git version 2.7.0',
        }
        # Add 'git tag --points-at' output for detached HEAD worktrees with
        # tags pointing at HEAD.
        for path in WORKTREE_INFO:
            if WORKTREE_INFO[path]['branch'] != 'detached':
                continue
            key = 'git tag --points-at ' + WORKTREE_INFO[path]['HEAD']
            _cmd_run_values[key] = '\n'.join(
                WORKTREE_INFO[path].get('tags', [])
            )

        def _cmd_run_side_effect(key, **kwargs):
            # Not using dict.get() here because we want to know if
            # _cmd_run_values doesn't account for all uses of cmd.run_all.
            return {'stdout': _cmd_run_values[' '.join(key)],
                    'stderr': '',
                    'retcode': 0,
                    'pid': 12345}

        def _isdir_side_effect(key):
            # os.path.isdir() would return True on a non-stale worktree
            return not WORKTREE_INFO[key].get('stale', False)

        # Build return dict for comparison
        worktree_ret = copy.deepcopy(WORKTREE_INFO)
        for key in worktree_ret:
            ptr = worktree_ret.get(key)
            ptr['detached'] = ptr['branch'] == 'detached'
            ptr['branch'] = None \
                if ptr['detached'] \
                else ptr['branch'].replace('refs/heads/', '', 1)

        cmd_run_mock = MagicMock(side_effect=_cmd_run_side_effect)
        isdir_mock = MagicMock(side_effect=_isdir_side_effect)
        with patch.dict(git_mod.__salt__, {'cmd.run_all': cmd_run_mock}):
            with patch.object(os.path, 'isdir', isdir_mock):
                # Test all=True. Include all return data.
                self.maxDiff = None
                self.assertEqual(
                    git_mod.list_worktrees(
                        WORKTREE_ROOT, all=True, stale=False
                    ),
                    worktree_ret
                )
                # Test all=False and stale=False. Exclude stale worktrees from
                # return data.
                self.assertEqual(
                    git_mod.list_worktrees(
                        WORKTREE_ROOT, all=False, stale=False
                    ),
                    dict([(x, worktree_ret[x]) for x in WORKTREE_INFO
                          if not WORKTREE_INFO[x].get('stale', False)])
                )
                # Test stale=True. Exclude non-stale worktrees from return
                # data.
                self.assertEqual(
                    git_mod.list_worktrees(
                        WORKTREE_ROOT, all=False, stale=True
                    ),
                    dict([(x, worktree_ret[x]) for x in WORKTREE_INFO
                          if WORKTREE_INFO[x].get('stale', False)])
                )
Beispiel #38
0
 def _get_mock(verify, provider):
     '''
     Return a MagicMock with the desired return value
     '''
     return MagicMock(return_value=verify.endswith(provider))
Beispiel #39
0
class MacUserTestCase(TestCase):
    '''
    TestCase for the salt.modules.mac_user modules
    '''

    mac_user.__context__ = {}
    mac_user.__grains__ = {}
    mac_user.__salt__ = {}

    mock_pwall = [pwd.struct_passwd(('_amavisd', '*', 83, 83, 'AMaViS Daemon',
                                    '/var/virusmails', '/usr/bin/false')),
                  pwd.struct_passwd(('_appleevents', '*', 55, 55,
                                     'AppleEvents Daemon',
                                    '/var/empty', '/usr/bin/false')),
                  pwd.struct_passwd(('_appowner', '*', 87, 87,
                                     'Application Owner',
                                     '/var/empty', '/usr/bin/false'))]
    mock_pwnam = pwd.struct_passwd(('_TEST_GROUP', '*', 83, 83, 'AMaViS Daemon',
                                    '/var/virusmails', '/usr/bin/false'))
    mock_getgrgid = grp.struct_group(('_TEST_GROUP', '*', 83, []))
    mock_getgrall = [grp.struct_group(('accessibility', '*', 90, [])),
                     grp.struct_group(('admin', '*', 80, ['root', 'admin']))]
    mock_info_ret = {'shell': '/bin/bash', 'name': 'test', 'gid': 4376,
                     'groups': ['TEST_GROUP'], 'home': '/Users/foo',
                     'fullname': 'TEST USER', 'uid': 4376}

    def test_osmajor(self):
        '''
        Tests version of OS X
        '''
        with patch.dict(mac_user.__grains__, {'kernel': 'Darwin',
                                              'osrelease': '10.9.1'}):
            self.assertEqual(mac_user._osmajor(), 10.9)

    @skipIf(True, 'Waiting on some clarifications from bug report #10594')
    def test_flush_dscl_cache(self):
        # TODO: Implement tests after clarifications come in
        pass

    def test_dscl(self):
        '''
        Tests the creation of a dscl node
        '''
        mac_mock = MagicMock(return_value={'pid': 4948,
                                           'retcode': 0,
                                           'stderr': '',
                                           'stdout': ''})
        with patch.dict(mac_user.__salt__, {'cmd.run_all': mac_mock}):
            with patch.dict(mac_user.__grains__, {'kernel': 'Darwin',
                                                  'osrelease': '10.9.1'}):
                self.assertEqual(mac_user._dscl('username'), {'pid': 4948,
                                                              'retcode': 0,
                                                              'stderr': '',
                                                              'stdout': ''})

    @patch('pwd.getpwall', MagicMock(return_value=mock_pwall))
    def test_first_avail_uid(self):
        '''
        Tests the availability of the next uid
        '''
        self.assertEqual(mac_user._first_avail_uid(), 501)

    # 'add' function tests: 4
    # Only tested error handling
    # Full functionality tests covered in integration testing

    @patch('salt.modules.mac_user.info', MagicMock(return_value=mock_info_ret))
    def test_add_user_exists(self):
        '''
        Tests if the user exists or not
        '''
        self.assertRaises(CommandExecutionError, mac_user.add, 'test')

    @patch('salt.modules.mac_user.info', MagicMock(return_value={}))
    def test_add_whitespace(self):
        '''
        Tests if there is whitespace in the user name
        '''
        self.assertRaises(SaltInvocationError, mac_user.add, 'foo bar')

    @patch('salt.modules.mac_user.info', MagicMock(return_value={}))
    def test_add_uid_int(self):
        '''
        Tests if the uid is an int
        '''
        self.assertRaises(SaltInvocationError, mac_user.add, 'foo', 'foo')

    @patch('salt.modules.mac_user.info', MagicMock(return_value={}))
    def test_add_gid_int(self):
        '''
        Tests if the gid is an int
        '''
        self.assertRaises(SaltInvocationError, mac_user.add, 'foo', 20, 'foo')

    # 'delete' function tests: 2
    # Only tested pure logic of function
    # Full functionality tests covered in integration testing

    def test_delete_whitespace(self):
        '''
        Tests if there is whitespace in the user name
        '''
        self.assertRaises(SaltInvocationError, mac_user.delete, 'foo bar')

    @patch('salt.modules.mac_user.info', MagicMock(return_value={}))
    def test_delete_user_exists(self):
        '''
        Tests if the user exists or not
        '''
        self.assertTrue(mac_user.delete('foo'))

    @patch('pwd.getpwall', MagicMock(return_value=mock_pwall))
    @patch('salt.modules.mac_user.list_groups',
           MagicMock(return_value=['TEST_GROUP']))
    def test_getent(self):
        '''
        Tests the list of information for all users
        '''
        ret = [{'shell': '/usr/bin/false', 'name': '_amavisd', 'gid': 83,
                'groups': ['TEST_GROUP'], 'home': '/var/virusmails',
                'fullname': 'AMaViS Daemon', 'uid': 83},
               {'shell': '/usr/bin/false', 'name': '_appleevents', 'gid': 55,
                'groups': ['TEST_GROUP'], 'home': '/var/empty',
                'fullname': 'AppleEvents Daemon', 'uid': 55},
               {'shell': '/usr/bin/false', 'name': '_appowner', 'gid': 87,
                'groups': ['TEST_GROUP'], 'home': '/var/empty',
                'fullname': 'Application Owner', 'uid': 87}]
        self.assertEqual(mac_user.getent(), ret)

    # 'chuid' function tests: 3
    # Only tested pure logic of function
    # Full functionality tests covered in integration testing

    def test_chuid_int(self):
        '''
        Tests if the uid is an int
        '''
        self.assertRaises(SaltInvocationError, mac_user.chuid, 'foo', 'foo')

    @patch('salt.modules.mac_user.info', MagicMock(return_value={}))
    def test_chuid_user_exists(self):
        '''
        Tests if the user exists or not
        '''
        self.assertRaises(CommandExecutionError, mac_user.chuid, 'foo', 4376)

    @patch('salt.modules.mac_user.info', MagicMock(return_value=mock_info_ret))
    def test_chuid_same_uid(self):
        '''
        Tests if the user's uid is the same as as the argument
        '''
        self.assertTrue(mac_user.chuid('foo', 4376))

    # 'chgid' function tests: 3
    # Only tested pure logic of function
    # Full functionality tests covered in integration testing

    def test_chgid_int(self):
        '''
        Tests if the gid is an int
        '''
        self.assertRaises(SaltInvocationError, mac_user.chgid, 'foo', 'foo')

    @patch('salt.modules.mac_user.info', MagicMock(return_value={}))
    def test_chgid_user_exists(self):
        '''
        Tests if the user exists or not
        '''
        self.assertRaises(CommandExecutionError, mac_user.chgid, 'foo', 4376)

    @patch('salt.modules.mac_user.info', MagicMock(return_value=mock_info_ret))
    def test_chgid_same_gid(self):
        '''
        Tests if the user's gid is the same as as the argument
        '''
        self.assertTrue(mac_user.chgid('foo', 4376))

    # 'chshell' function tests: 2
    # Only tested pure logic of function
    # Full functionality tests covered in integration testing

    @patch('salt.modules.mac_user.info', MagicMock(return_value={}))
    def test_chshell_user_exists(self):
        '''
        Tests if the user exists or not
        '''
        self.assertRaises(CommandExecutionError, mac_user.chshell,
                          'foo', '/bin/bash')

    @patch('salt.modules.mac_user.info', MagicMock(return_value=mock_info_ret))
    def test_chshell_same_shell(self):
        '''
        Tests if the user's shell is the same as the argument
        '''
        self.assertTrue(mac_user.chshell('foo', '/bin/bash'))

    # 'chhome' function tests: 2
    # Only tested pure logic of function
    # Full functionality tests covered in integration testing

    @patch('salt.modules.mac_user.info', MagicMock(return_value={}))
    def test_chhome_user_exists(self):
        '''
        Test if the user exists or not
        '''
        self.assertRaises(CommandExecutionError, mac_user.chhome,
                          'foo', '/Users/foo')

    @patch('salt.modules.mac_user.info', MagicMock(return_value=mock_info_ret))
    def test_chhome_same_home(self):
        '''
        Tests if the user's home is the same as the argument
        '''
        self.assertTrue(mac_user.chhome('foo', '/Users/foo'))

    # 'chfullname' function tests: 2
    # Only tested pure logic of function
    # Full functionality tests covered in integration testing

    @patch('salt.modules.mac_user.info', MagicMock(return_value={}))
    def test_chfullname_user_exists(self):
        '''
        Tests if the user exists or not
        '''
        self.assertRaises(CommandExecutionError, mac_user.chfullname,
                          'test', 'TEST USER')

    @patch('salt.modules.mac_user.info', MagicMock(return_value=mock_info_ret))
    def test_chfullname_same_name(self):
        '''
        Tests if the user's full name is the same as the argument
        '''
        self.assertTrue(mac_user.chfullname('test', 'TEST USER'))

    # 'chgroups' function tests: 3
    # Only tested pure logic of function
    # Full functionality tests covered in integration testing

    @patch('salt.modules.mac_user.info', MagicMock(return_value={}))
    def test_chgroups_user_exists(self):
        '''
        Tests if the user exists or not
        '''
        self.assertRaises(CommandExecutionError, mac_user.chgroups,
                          'foo', 'wheel,root')

    @patch('salt.modules.mac_user.info', MagicMock(return_value=mock_info_ret))
    def test_chgroups_bad_groups(self):
        '''
        Test if there is white space in groups argument
        '''
        self.assertRaises(SaltInvocationError, mac_user.chgroups,
                          'test', 'bad group')

    @patch('salt.modules.mac_user.info', MagicMock(return_value=mock_info_ret))
    @patch('salt.modules.mac_user.list_groups',
           MagicMock(return_value=('wheel', 'root')))
    def test_chgroups_same_desired(self):
        '''
        Tests if the user's list of groups is the same as the arguments
        '''
        mock_primary = MagicMock(return_value='wheel')
        with patch.dict(mac_user.__salt__, {'file.gid_to_group': mock_primary}):
            self.assertTrue(mac_user.chgroups('test', 'wheel,root'))

    @patch('salt.modules.mac_user.list_groups',
           MagicMock(return_value=['_TEST_GROUP']))
    def test_info(self):
        '''
        Tests the return of user information
        '''
        mock_pwnam = pwd.struct_passwd(('test', '*', 0, 0, 'TEST USER',
                                        '/var/test', '/bin/bash'))
        ret = {'shell': '/bin/bash', 'name': 'test', 'gid': 0,
               'groups': ['_TEST_GROUP'], 'home': '/var/test',
               'fullname': 'TEST USER', 'uid': 0}
        with patch('pwd.getpwnam', MagicMock(return_value=mock_pwnam)):
            self.assertEqual(mac_user.info('root'), ret)

    @patch('salt.modules.mac_user.list_groups',
           MagicMock(return_value=['_TEST_GROUP']))
    def test_format_info(self):
        '''
        Tests the formatting of returned user information
        '''
        data = pwd.struct_passwd(('_TEST_GROUP', '*', 83, 83, 'AMaViS Daemon',
                                  '/var/virusmails', '/usr/bin/false'))
        ret = {'shell': '/usr/bin/false', 'name': '_TEST_GROUP', 'gid': 83,
                     'groups': ['_TEST_GROUP'], 'home': '/var/virusmails',
                     'fullname': 'AMaViS Daemon', 'uid': 83}
        self.assertEqual(mac_user._format_info(data), ret)

    @patch('pwd.getpwnam', MagicMock(return_value=mock_pwnam))
    @patch('grp.getgrgid', MagicMock(return_value=mock_getgrgid))
    @patch('grp.getgrall', MagicMock(return_value=mock_getgrall))
    def test_list_groups(self):
        '''
        Tests the list of groups the user belongs to
        '''
        self.assertEqual(mac_user.list_groups('name'), ['_TEST_GROUP'])

    @patch('pwd.getpwall', MagicMock(return_value=mock_pwall))
    def test_list_users(self):
        '''
        Tests the list of all users
        '''
        ret = ['_amavisd', '_appleevents', '_appowner']
        self.assertEqual(mac_user.list_users(), ret)
Beispiel #40
0
class AtTestCase(TestCase):
    '''
    TestCase for the salt.modules.at module
    '''

    atq_output = {
        'jobs': [{
            'date': '2014-12-11',
            'job': 101,
            'queue': 'A',
            'tag': '',
            'time': '19:48:47',
            'user': '******'
        }]
    }

    @patch('salt.modules.at._cmd', MagicMock(return_value=None))
    def test_atq_not_available(self):
        '''
        Tests the at.atq not available for any type of os_family.
        '''
        with patch.dict(at.__grains__, {'os_family': 'RedHat'}):
            self.assertEqual(at.atq(), '\'at.atq\' is not available.')

        with patch.dict(at.__grains__, {'os_family': ''}):
            self.assertEqual(at.atq(), '\'at.atq\' is not available.')

    @patch('salt.modules.at._cmd', MagicMock(return_value=''))
    def test_atq_no_jobs_available(self):
        '''
        Tests the no jobs available for any type of os_family.
        '''
        with patch.dict(at.__grains__, {'os_family': 'RedHat'}):
            self.assertDictEqual(at.atq(), {'jobs': []})

        with patch.dict(at.__grains__, {'os_family': ''}):
            self.assertDictEqual(at.atq(), {'jobs': []})

    @patch('salt.modules.at._cmd')
    def test_atq_list(self, salt_modules_at__cmd_mock):
        '''
        Tests the list all queued and running jobs.
        '''
        salt_modules_at__cmd_mock.return_value = '101\tThu Dec 11 \
        19:48:47 2014 A B'

        with patch.dict(at.__grains__, {'os_family': '', 'os': ''}):
            self.assertDictEqual(
                at.atq(), {
                    'jobs': [{
                        'date': '2014-12-11',
                        'job': 101,
                        'queue': 'A',
                        'tag': '',
                        'time': '19:48:00',
                        'user': '******'
                    }]
                })

        salt_modules_at__cmd_mock.return_value = '101\t2014-12-11 \
        19:48:47 A B'

        with patch.dict(at.__grains__, {'os_family': 'RedHat', 'os': ''}):
            self.assertDictEqual(
                at.atq(), {
                    'jobs': [{
                        'date': '2014-12-11',
                        'job': 101,
                        'queue': 'A',
                        'tag': '',
                        'time': '19:48:47',
                        'user': '******'
                    }]
                })

        salt_modules_at__cmd_mock.return_value = 'SALT: Dec 11, \
        2014 19:48 A 101 B'

        with patch.dict(at.__grains__, {'os_family': '', 'os': 'OpenBSD'}):
            self.assertDictEqual(
                at.atq(), {
                    'jobs': [{
                        'date': '2014-12-11',
                        'job': '101',
                        'queue': 'B',
                        'tag': '',
                        'time': '19:48:00',
                        'user': '******'
                    }]
                })

    @patch('salt.modules.at.atq', MagicMock(return_value=atq_output))
    def test_atrm(self):
        """
        Tests for remove jobs from the queue.
        """
        with patch.object(salt.utils, 'which', return_value=None):
            self.assertEqual(at.atrm(), "'at.atrm' is not available.")

        with patch.object(salt.utils, 'which', return_value=True):
            self.assertDictEqual(at.atrm(),
                                 {'jobs': {
                                     'removed': [],
                                     'tag': None
                                 }})

        with patch.object(at, '_cmd', return_value=True):
            with patch.object(salt.utils, 'which', return_value=True):
                self.assertDictEqual(
                    at.atrm('all'),
                    {'jobs': {
                        'removed': ['101'],
                        'tag': None
                    }})

        with patch.object(at, '_cmd', return_value=True):
            with patch.object(salt.utils, 'which', return_value=True):
                self.assertDictEqual(
                    at.atrm(101), {'jobs': {
                        'removed': ['101'],
                        'tag': None
                    }})

        with patch.object(at, '_cmd', return_value=None):
            self.assertEqual(at.atrm(101), '\'at.atrm\' is not available.')

    @patch('salt.modules.at.atq', MagicMock(return_value=atq_output))
    def test_jobcheck(self):
        """
        Tests for check the job from queue.
        """
        self.assertDictEqual(at.jobcheck(),
                             {'error': 'You have given a condition'})

        self.assertDictEqual(at.jobcheck(runas='foo'), {
            'note': 'No match jobs or time format error',
            'jobs': []
        })

        self.assertDictEqual(
            at.jobcheck(runas='B',
                        tag='',
                        hour=19,
                        minute=48,
                        day=11,
                        month=12,
                        Year=2014), {
                            'jobs': [{
                                'date': '2014-12-11',
                                'job': 101,
                                'queue': 'A',
                                'tag': '',
                                'time': '19:48:47',
                                'user': '******'
                            }]
                        })
Beispiel #41
0
class ConfigTestCase(TestCase, integration.AdaptedConfigurationTestCaseMixIn):
    def test_proper_path_joining(self):
        fpath = tempfile.mktemp()
        try:
            salt.utils.fopen(fpath, 'w').write("root_dir: /\n"
                                               "key_logfile: key\n")
            config = sconfig.master_config(fpath)
            # os.path.join behaviour
            self.assertEqual(config['key_logfile'], os.path.join('/', 'key'))
            # os.sep.join behaviour
            self.assertNotEqual(config['key_logfile'], '//key')
        finally:
            if os.path.isfile(fpath):
                os.unlink(fpath)

    def test_common_prefix_stripping(self):
        tempdir = tempfile.mkdtemp(dir=integration.SYS_TMP_DIR)
        try:
            root_dir = os.path.join(tempdir, 'foo', 'bar')
            os.makedirs(root_dir)
            fpath = os.path.join(root_dir, 'config')
            salt.utils.fopen(fpath, 'w').write('root_dir: {0}\n'
                                               'log_file: {1}\n'.format(
                                                   root_dir, fpath))
            config = sconfig.master_config(fpath)
            self.assertEqual(config['log_file'], fpath)
        finally:
            if os.path.isdir(tempdir):
                shutil.rmtree(tempdir)

    def test_load_master_config_from_environ_var(self):
        original_environ = os.environ.copy()

        tempdir = tempfile.mkdtemp(dir=integration.SYS_TMP_DIR)
        try:
            env_root_dir = os.path.join(tempdir, 'foo', 'env')
            os.makedirs(env_root_dir)
            env_fpath = os.path.join(env_root_dir, 'config-env')

            salt.utils.fopen(env_fpath, 'w').write('root_dir: {0}\n'
                                                   'log_file: {1}\n'.format(
                                                       env_root_dir,
                                                       env_fpath))

            os.environ['SALT_MASTER_CONFIG'] = env_fpath
            # Should load from env variable, not the default configuration file.
            config = sconfig.master_config('/etc/salt/master')
            self.assertEqual(config['log_file'], env_fpath)
            os.environ.clear()
            os.environ.update(original_environ)

            root_dir = os.path.join(tempdir, 'foo', 'bar')
            os.makedirs(root_dir)
            fpath = os.path.join(root_dir, 'config')
            salt.utils.fopen(fpath, 'w').write('root_dir: {0}\n'
                                               'log_file: {1}\n'.format(
                                                   root_dir, fpath))
            # Let's set the environment variable, yet, since the configuration
            # file path is not the default one, ie, the user has passed an
            # alternative configuration file form the CLI parser, the
            # environment variable will be ignored.
            os.environ['SALT_MASTER_CONFIG'] = env_fpath
            config = sconfig.master_config(fpath)
            self.assertEqual(config['log_file'], fpath)
            os.environ.clear()
            os.environ.update(original_environ)

        finally:
            if os.path.isdir(tempdir):
                shutil.rmtree(tempdir)

    def test_load_minion_config_from_environ_var(self):
        original_environ = os.environ.copy()

        tempdir = tempfile.mkdtemp(dir=integration.SYS_TMP_DIR)
        try:
            env_root_dir = os.path.join(tempdir, 'foo', 'env')
            os.makedirs(env_root_dir)
            env_fpath = os.path.join(env_root_dir, 'config-env')

            salt.utils.fopen(env_fpath, 'w').write('root_dir: {0}\n'
                                                   'log_file: {1}\n'.format(
                                                       env_root_dir,
                                                       env_fpath))

            os.environ['SALT_MINION_CONFIG'] = env_fpath
            # Should load from env variable, not the default configuration file
            config = sconfig.minion_config('/etc/salt/minion')
            self.assertEqual(config['log_file'], env_fpath)
            os.environ.clear()
            os.environ.update(original_environ)

            root_dir = os.path.join(tempdir, 'foo', 'bar')
            os.makedirs(root_dir)
            fpath = os.path.join(root_dir, 'config')
            salt.utils.fopen(fpath, 'w').write('root_dir: {0}\n'
                                               'log_file: {1}\n'.format(
                                                   root_dir, fpath))
            # Let's set the environment variable, yet, since the configuration
            # file path is not the default one, ie, the user has passed an
            # alternative configuration file form the CLI parser, the
            # environment variable will be ignored.
            os.environ['SALT_MINION_CONFIG'] = env_fpath
            config = sconfig.minion_config(fpath)
            self.assertEqual(config['log_file'], fpath)
            os.environ.clear()
            os.environ.update(original_environ)
        finally:
            if os.path.isdir(tempdir):
                shutil.rmtree(tempdir)

    def test_load_client_config_from_environ_var(self):
        original_environ = os.environ.copy()
        try:
            tempdir = tempfile.mkdtemp(dir=integration.SYS_TMP_DIR)
            env_root_dir = os.path.join(tempdir, 'foo', 'env')
            os.makedirs(env_root_dir)

            # Let's populate a master configuration file which should not get
            # picked up since the client configuration tries to load the master
            # configuration settings using the provided client configuration
            # file
            master_config = os.path.join(env_root_dir, 'master')
            salt.utils.fopen(master_config,
                             'w').write('blah: true\n'
                                        'root_dir: {0}\n'
                                        'log_file: {1}\n'.format(
                                            env_root_dir, master_config))
            os.environ['SALT_MASTER_CONFIG'] = master_config

            # Now the client configuration file
            env_fpath = os.path.join(env_root_dir, 'config-env')
            salt.utils.fopen(env_fpath, 'w').write('root_dir: {0}\n'
                                                   'log_file: {1}\n'.format(
                                                       env_root_dir,
                                                       env_fpath))

            os.environ['SALT_CLIENT_CONFIG'] = env_fpath
            # Should load from env variable, not the default configuration file
            config = sconfig.client_config(os.path.expanduser('~/.salt'))
            self.assertEqual(config['log_file'], env_fpath)
            self.assertTrue('blah' not in config)
            os.environ.clear()
            os.environ.update(original_environ)

            root_dir = os.path.join(tempdir, 'foo', 'bar')
            os.makedirs(root_dir)
            fpath = os.path.join(root_dir, 'config')
            salt.utils.fopen(fpath, 'w').write('root_dir: {0}\n'
                                               'log_file: {1}\n'.format(
                                                   root_dir, fpath))
            # Let's set the environment variable, yet, since the configuration
            # file path is not the default one, ie, the user has passed an
            # alternative configuration file form the CLI parser, the
            # environment variable will be ignored.
            os.environ['SALT_MASTER_CONFIG'] = env_fpath
            config = sconfig.master_config(fpath)
            self.assertEqual(config['log_file'], fpath)
            os.environ.clear()
            os.environ.update(original_environ)

        finally:
            if os.path.isdir(tempdir):
                shutil.rmtree(tempdir)

    def test_issue_5970_minion_confd_inclusion(self):
        try:
            tempdir = tempfile.mkdtemp(dir=integration.SYS_TMP_DIR)
            minion_config = os.path.join(tempdir, 'minion')
            minion_confd = os.path.join(tempdir, 'minion.d')
            os.makedirs(minion_confd)

            # Let's populate a minion configuration file with some basic
            # settings
            salt.utils.fopen(minion_config,
                             'w').write('blah: false\n'
                                        'root_dir: {0}\n'
                                        'log_file: {1}\n'.format(
                                            tempdir, minion_config))

            # Now, let's populate an extra configuration file under minion.d
            # Notice that above we've set blah as False and bellow as True.
            # Since the minion.d files are loaded after the main configuration
            # file so overrides can happen, the final value of blah should be
            # True.
            extra_config = os.path.join(minion_confd, 'extra.conf')
            salt.utils.fopen(extra_config, 'w').write('blah: true\n')

            # Let's load the configuration
            config = sconfig.minion_config(minion_config)

            self.assertEqual(config['log_file'], minion_config)
            # As proven by the assertion below, blah is True
            self.assertTrue(config['blah'])
        finally:
            if os.path.isdir(tempdir):
                shutil.rmtree(tempdir)

    def test_master_confd_inclusion(self):
        try:
            tempdir = tempfile.mkdtemp(dir=integration.SYS_TMP_DIR)
            master_config = os.path.join(tempdir, 'master')
            master_confd = os.path.join(tempdir, 'master.d')
            os.makedirs(master_confd)

            # Let's populate a master configuration file with some basic
            # settings
            salt.utils.fopen(master_config,
                             'w').write('blah: false\n'
                                        'root_dir: {0}\n'
                                        'log_file: {1}\n'.format(
                                            tempdir, master_config))

            # Now, let's populate an extra configuration file under master.d
            # Notice that above we've set blah as False and bellow as True.
            # Since the master.d files are loaded after the main configuration
            # file so overrides can happen, the final value of blah should be
            # True.
            extra_config = os.path.join(master_confd, 'extra.conf')
            salt.utils.fopen(extra_config, 'w').write('blah: true\n')

            # Let's load the configuration
            config = sconfig.master_config(master_config)

            self.assertEqual(config['log_file'], master_config)
            # As proven by the assertion below, blah is True
            self.assertTrue(config['blah'])
        finally:
            if os.path.isdir(tempdir):
                shutil.rmtree(tempdir)

    def test_syndic_config(self):
        syndic_conf_path = self.get_config_file_path('syndic')
        minion_conf_path = self.get_config_file_path('minion')
        syndic_opts = sconfig.syndic_config(syndic_conf_path, minion_conf_path)
        syndic_opts.update(salt.minion.resolve_dns(syndic_opts))
        root_dir = syndic_opts['root_dir']
        # id & pki dir are shared & so configured on the minion side
        self.assertEqual(syndic_opts['id'], 'minion')
        self.assertEqual(syndic_opts['pki_dir'], os.path.join(root_dir, 'pki'))
        # the rest is configured master side
        self.assertEqual(syndic_opts['master_uri'], 'tcp://127.0.0.1:54506')
        self.assertEqual(syndic_opts['master_port'], 54506)
        self.assertEqual(syndic_opts['master_ip'], '127.0.0.1')
        self.assertEqual(syndic_opts['master'], 'localhost')
        self.assertEqual(syndic_opts['sock_dir'],
                         os.path.join(root_dir, 'minion_sock'))
        self.assertEqual(syndic_opts['cachedir'],
                         os.path.join(root_dir, 'cachedir'))
        self.assertEqual(syndic_opts['log_file'],
                         os.path.join(root_dir, 'osyndic.log'))
        self.assertEqual(syndic_opts['pidfile'],
                         os.path.join(root_dir, 'osyndic.pid'))
        # Show that the options of localclient that repub to local master
        # are not merged with syndic ones
        self.assertEqual(syndic_opts['_master_conf_file'], minion_conf_path)
        self.assertEqual(syndic_opts['_minion_conf_file'], syndic_conf_path)

    def test_check_dns_deprecation_warning(self):
        helium_version = SaltStackVersion.from_name('Helium')
        if salt_version.__version_info__ >= helium_version:
            raise AssertionError(
                'Failing this test on purpose! Please delete this test case, '
                'the \'check_dns\' keyword argument and the deprecation '
                'warnings in `salt.config.minion_config` and '
                'salt.config.apply_minion_config`')

        # Let's force the warning to always be thrown
        warnings.resetwarnings()
        warnings.filterwarnings('always', '(.*)check_dns(.*)',
                                DeprecationWarning, 'salt.config')
        with warnings.catch_warnings(record=True) as w:
            sconfig.minion_config(None, None, check_dns=True)
            self.assertEqual(
                'The functionality behind the \'check_dns\' keyword argument '
                'is no longer required, as such, it became unnecessary and is '
                'now deprecated. \'check_dns\' will be removed in Salt '
                '{0}.'.format(helium_version.formatted_version),
                str(w[-1].message))

        with warnings.catch_warnings(record=True) as w:
            sconfig.apply_minion_config(overrides=None,
                                        defaults=None,
                                        check_dns=True)
            self.assertEqual(
                'The functionality behind the \'check_dns\' keyword argument '
                'is no longer required, as such, it became unnecessary and is '
                'now deprecated. \'check_dns\' will be removed in Salt '
                '{0}.'.format(helium_version.formatted_version),
                str(w[-1].message))

        with warnings.catch_warnings(record=True) as w:
            sconfig.minion_config(None, None, check_dns=False)
            self.assertEqual(
                'The functionality behind the \'check_dns\' keyword argument '
                'is no longer required, as such, it became unnecessary and is '
                'now deprecated. \'check_dns\' will be removed in Salt '
                '{0}.'.format(helium_version.formatted_version),
                str(w[-1].message))

        with warnings.catch_warnings(record=True) as w:
            sconfig.apply_minion_config(overrides=None,
                                        defaults=None,
                                        check_dns=False)
            self.assertEqual(
                'The functionality behind the \'check_dns\' keyword argument '
                'is no longer required, as such, it became unnecessary and is '
                'now deprecated. \'check_dns\' will be removed in Salt '
                '{0}.'.format(helium_version.formatted_version),
                str(w[-1].message))

    def test_issue_6714_parsing_errors_logged(self):
        try:
            tempdir = tempfile.mkdtemp(dir=integration.SYS_TMP_DIR)
            test_config = os.path.join(tempdir, 'config')

            # Let's populate a master configuration file with some basic
            # settings
            salt.utils.fopen(
                test_config,
                'w').write('root_dir: {0}\n'
                           'log_file: {0}/foo.log\n'.format(tempdir) + '\n\n\n'
                           'blah:false\n')

            with TestsLoggingHandler() as handler:
                # Let's load the configuration
                config = sconfig.master_config(test_config)
                for message in handler.messages:
                    if message.startswith('ERROR:Error parsing configuration'):
                        break
                else:
                    raise AssertionError('No parsing error message was logged')
        finally:
            if os.path.isdir(tempdir):
                shutil.rmtree(tempdir)

    @patch('salt.utils.network.get_fqhostname',
           MagicMock(return_value='localhost'))
    def test_get_id_etc_hostname(self):
        '''
        Test calling salt.config.get_id() and falling back to looking at
        /etc/hostname.
        '''
        with patch('salt.utils.fopen', _fopen_side_effect_etc_hostname):
            self.assertEqual(sconfig.get_id(cache=False),
                             (MOCK_HOSTNAME, False))

    @patch('salt.utils.network.get_fqhostname',
           MagicMock(return_value='localhost'))
    def test_get_id_etc_hosts(self):
        '''
        Test calling salt.config.get_id() and falling back all the way to
        looking up data from /etc/hosts.
        '''
        with patch('salt.utils.fopen', _fopen_side_effect_etc_hosts):
            self.assertEqual(sconfig.get_id(cache=False),
                             (MOCK_HOSTNAME, False))
Beispiel #42
0
 def test_clear_argument(self):
     mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
     with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
         virtualenv_mod.create('/tmp/foo', clear=True)
         mock.assert_called_once_with('virtualenv --clear /tmp/foo',
                                      runas=None)
Beispiel #43
0
    def test_issue_6029_deprecated_distribute(self):
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})

        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            virtualenv_mod._install_script = MagicMock(return_value={
                'retcode': 0,
                'stdout': 'Installed script!',
                'stderr': ''
            })
            virtualenv_mod.create('/tmp/foo',
                                  system_site_packages=True,
                                  distribute=True)
            mock.assert_called_once_with(
                'virtualenv --distribute --system-site-packages /tmp/foo',
                runas=None)

        with TestsLoggingHandler() as handler:
            # Let's fake a higher virtualenv version
            virtualenv_mock = MagicMock()
            virtualenv_mock.__version__ = '1.10rc1'
            mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
            with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
                with patch.dict('sys.modules',
                                {'virtualenv': virtualenv_mock}):
                    virtualenv_mod.create('/tmp/foo',
                                          system_site_packages=True,
                                          distribute=True)
                    mock.assert_called_once_with(
                        'virtualenv --system-site-packages /tmp/foo',
                        runas=None)

                # Are we logging the deprecation information?
                self.assertIn(
                    'INFO:The virtualenv \'--distribute\' option has been '
                    'deprecated in virtualenv(>=1.10), as such, the '
                    '\'distribute\' option to `virtualenv.create()` has '
                    'also been deprecated and it\'s not necessary anymore.',
                    handler.messages)
Beispiel #44
0
 def test_check_start_true(self):
     '''
     If start is True, then dockerng.running will try
     to start a container that is stopped.
     '''
     image_id = 'abcdefg'
     dockerng_create = Mock()
     dockerng_start = Mock()
     dockerng_list_containers = Mock(return_value=['cont'])
     dockerng_inspect_container = Mock(
         return_value={
             'Config': {
                 'Image': 'image:latest',
                 'Tty': False,
                 'Labels': {},
                 'Domainname': '',
                 'User': '',
                 'AttachStderr': True,
                 'AttachStdout': True,
                 'Hostname': 'saltstack-container',
                 'Env': [],
                 'WorkingDir': '/',
                 'Cmd': ['bash'],
                 'Volumes': {},
                 'Entrypoint': None,
                 'ExposedPorts': {},
                 'OpenStdin': False,
             },
             'HostConfig': {
                 'PublishAllPorts': False,
                 'Dns': [],
                 'Links': None,
                 'CpusetCpus': '',
                 'RestartPolicy': {
                     'MaximumRetryCount': 0,
                     'Name': ''
                 },
                 'CapAdd': None,
                 'NetworkMode': 'default',
                 'PidMode': '',
                 'MemorySwap': 0,
                 'ExtraHosts': None,
                 'PortBindings': None,
                 'LxcConf': None,
                 'DnsSearch': [],
                 'Privileged': False,
                 'Binds': None,
                 'Memory': 0,
                 'VolumesFrom': None,
                 'CpuShares': 0,
                 'CapDrop': None,
             },
             'NetworkSettings': {
                 'MacAddress': '00:00:00:00:00:01',
             },
             'Image': image_id
         })
     dockerng_inspect_image = MagicMock(
         return_value={
             'Id': image_id,
             'Config': {
                 'Hostname': 'saltstack-container',
                 'WorkingDir': '/',
                 'Cmd': ['bash'],
                 'Volumes': {},
                 'Entrypoint': None,
                 'ExposedPorts': {},
             },
         })
     __salt__ = {
         'dockerng.list_containers': dockerng_list_containers,
         'dockerng.inspect_container': dockerng_inspect_container,
         'dockerng.inspect_image': dockerng_inspect_image,
         'dockerng.list_tags': MagicMock(),
         'dockerng.pull': MagicMock(return_value=True),
         'dockerng.state': MagicMock(side_effect=['stopped', 'running']),
         'dockerng.create': dockerng_create,
         'dockerng.start': dockerng_start,
     }
     with patch.dict(dockerng_state.__dict__, {'__salt__': __salt__}):
         ret = dockerng_state.running(
             'cont',
             image='image:latest',
             start=True,
         )
     self.assertEqual(
         ret, {
             'name': 'cont',
             'comment': "Container 'cont' changed state.",
             'changes': {
                 'state': {
                     'new': 'running',
                     'old': 'stopped'
                 },
                 'image': True
             },
             'result': True,
         })
Beispiel #45
0
class NftablesTestCase(TestCase):
    '''
    Test cases for salt.modules.nftables
    '''

    # 'version' function tests: 1

    def test_version(self):
        '''
        Test if it return version from nftables --version
        '''
        mock = MagicMock(return_value='nf_tables 0.3-1')
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertEqual(nftables.version(), '0.3-1')

    # 'build_rule' function tests: 1

    def test_build_rule(self):
        '''
        Test if it build a well-formatted nftables rule based on kwargs.
        '''
        self.assertEqual(nftables.build_rule(full='True'),
                         'Error: Table needs to be specified')

        self.assertEqual(nftables.build_rule(table='filter', full='True'),
                         'Error: Chain needs to be specified')

        self.assertEqual(
            nftables.build_rule(table='filter', chain='input', full='True'),
            'Error: Command needs to be specified')

        self.assertEqual(
            nftables.build_rule(table='filter',
                                chain='input',
                                command='insert',
                                position='3',
                                full='True'),
            'nft insert rule ip filter input position 3 ')

        self.assertEqual(
            nftables.build_rule(table='filter',
                                chain='input',
                                command='insert',
                                full='True'),
            'nft insert rule ip filter input ')

        self.assertEqual(
            nftables.build_rule(table='filter',
                                chain='input',
                                command='halt',
                                full='True'), 'nft halt rule ip filter input ')

        self.assertEqual(nftables.build_rule(), '')

    # 'get_saved_rules' function tests: 1

    def test_get_saved_rules(self):
        '''
        Test if it return a data structure of the rules in the conf file
        '''
        with patch.dict(nftables.__grains__, {'os_family': 'Debian'}):
            with patch.object(salt.utils, 'fopen', MagicMock(mock_open())):
                self.assertListEqual(nftables.get_saved_rules(), [])

    # 'get_rules' function tests: 1

    def test_get_rules(self):
        '''
        Test if it return a data structure of the current, in-memory rules
        '''
        mock = MagicMock(return_value='SALT STACK')
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertListEqual(nftables.get_rules(), ['SALT STACK'])

        mock = MagicMock(return_value=False)
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertListEqual(nftables.get_rules(), [])

    # 'save' function tests: 1

    def test_save(self):
        '''
        Test if it save the current in-memory rules to disk
        '''
        with patch.dict(nftables.__grains__, {'os_family': 'Debian'}):
            mock = MagicMock(return_value=False)
            with patch.dict(nftables.__salt__, {'cmd.run': mock}):
                with patch.object(salt.utils, 'fopen', MagicMock(mock_open())):
                    self.assertEqual(nftables.save(), '#! nft -f\n\n')

                with patch.object(salt.utils, 'fopen',
                                  MagicMock(side_effect=IOError)):
                    self.assertRaises(CommandExecutionError, nftables.save)

    # 'get_rule_handle' function tests: 1

    def test_get_rule_handle(self):
        '''
        Test if it get the handle for a particular rule
        '''
        self.assertEqual(nftables.get_rule_handle(),
                         'Error: Chain needs to be specified')

        self.assertEqual(nftables.get_rule_handle(chain='input'),
                         'Error: Rule needs to be specified')

        _ru = 'input tcp dport 22 log accept'
        ret = 'Error: 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 = 'Error: 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 = ('Error: rule input tcp dport 22 log accept chain input'
               ' in table filter in family ipv4 does not exist')
        ret1 = 'Error: could not find rule input tcp dport 22 log accept'
        with patch.object(nftables, 'check_table',
                          MagicMock(return_value=True)):
            with patch.object(nftables, 'check_chain',
                              MagicMock(return_value=True)):
                with patch.object(nftables, 'check',
                                  MagicMock(side_effect=[False, True])):
                    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)

    # 'check' function tests: 1

    def test_check(self):
        '''
        Test if it check for the existence of a rule in the table and chain
        '''
        self.assertEqual(nftables.check(),
                         'Error: Chain needs to be specified')

        self.assertEqual(nftables.check(chain='input'),
                         'Error: Rule needs to be specified')

        _ru = 'input tcp dport 22 log accept'
        ret = 'Error: table filter in family ipv4 does not exist'
        mock = MagicMock(return_value='')
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertEqual(nftables.check(chain='input', rule=_ru), ret)

        mock = MagicMock(return_value='table ip filter')
        ret = 'Error: chain input in table filter in family ipv4 does not exist'
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertEqual(nftables.check(chain='input', rule=_ru), ret)

        mock = MagicMock(return_value='table ip filter chain input {{')
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertFalse(nftables.check(chain='input', rule=_ru))

        r_val = 'table ip filter chain input {{ input tcp dport 22 log accept #'
        mock = MagicMock(return_value=r_val)
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertTrue(nftables.check(chain='input', rule=_ru))

    # 'check_chain' function tests: 1

    def test_check_chain(self):
        '''
        Test if it check for the existence of a chain in the table
        '''
        self.assertEqual(nftables.check_chain(),
                         'Error: Chain needs to be specified')

        mock = MagicMock(return_value='')
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertFalse(nftables.check_chain(chain='input'))

        mock = MagicMock(return_value='chain input {{')
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertTrue(nftables.check_chain(chain='input'))

    # 'check_table' function tests: 1

    def test_check_table(self):
        '''
        Test if it check for the existence of a table
        '''
        self.assertEqual(nftables.check_table(),
                         'Error: table needs to be specified')

        mock = MagicMock(return_value='')
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertFalse(nftables.check_table(table='nat'))

        mock = MagicMock(return_value='table ip nat')
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertTrue(nftables.check_table(table='nat'))

    # 'new_table' function tests: 1

    def test_new_table(self):
        '''
        Test if it create new custom table.
        '''
        self.assertEqual(nftables.new_table(table=None),
                         'Error: table needs to be specified')

        mock = MagicMock(return_value='')
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertEqual(nftables.new_table(table='nat'), True)

        mock = MagicMock(return_value='table ip nat')
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertEqual(nftables.new_table(table='nat'),
                             'Error: table nat in family ipv4 already exists')

    # 'delete_table' function tests: 1

    def test_delete_table(self):
        '''
        Test if it delete custom table.
        '''
        self.assertEqual(nftables.delete_table(table=None),
                         'Error: table needs to be specified')

        mock = MagicMock(return_value='')
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertEqual(nftables.delete_table(table='nat'),
                             'Error: table nat in family ipv4 does not exist')

        mock = MagicMock(return_value='table ip nat')
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertEqual(nftables.delete_table(table='nat'),
                             'table ip nat')

    # 'new_chain' function tests: 2

    def test_new_chain(self):
        '''
        Test if it create new chain to the specified table.
        '''
        self.assertEqual(nftables.new_chain(),
                         'Error: Chain needs to be specified')

        ret = 'Error: table filter in family ipv4 does not exist'
        mock = MagicMock(return_value='')
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertEqual(nftables.new_chain(chain='input'), ret)

        ret = 'Error: chain input in table filter in family ipv4 already exists'
        mock = MagicMock(return_value='table ip filter chain input {{')
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertEqual(nftables.new_chain(chain='input'), ret)

    @patch('salt.modules.nftables.check_chain', MagicMock(return_value=False))
    @patch('salt.modules.nftables.check_table', MagicMock(return_value=True))
    def test_new_chain_variable(self):
        '''
        Test if it create new chain to the specified table.
        '''
        mock = MagicMock(return_value='')
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertEqual(
                nftables.new_chain(chain='input', table_type='filter'),
                'Error: table_type hook and priority required')

            self.assertTrue(
                nftables.new_chain(chain='input',
                                   table_type='filter',
                                   hook='input',
                                   priority=0))

    # 'delete_chain' function tests: 1

    def test_delete_chain(self):
        '''
        Test if it delete the chain from the specified table.
        '''
        self.assertEqual(nftables.delete_chain(),
                         'Error: Chain needs to be specified')

        ret = 'Error: table filter in family ipv4 does not exist'
        mock = MagicMock(return_value='')
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertEqual(nftables.delete_chain(chain='input'), ret)

        ret = 'Error: 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.delete_chain(chain='input'), ret)

    @patch('salt.modules.nftables.check_chain', MagicMock(return_value=True))
    @patch('salt.modules.nftables.check_table', MagicMock(return_value=True))
    def test_delete_chain_variables(self):
        '''
        Test if it delete the chain from the specified table.
        '''
        mock = MagicMock(return_value='')
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertTrue(nftables.delete_chain(chain='input'))

    # 'append' function tests: 2

    def test_append(self):
        '''
        Test if it append a rule to the specified table & chain.
        '''
        self.assertEqual(nftables.append(),
                         'Error: Chain needs to be specified')

        self.assertEqual(nftables.append(chain='input'),
                         'Error: Rule needs to be specified')

        _ru = 'input tcp dport 22 log accept'
        ret = 'Error: table filter in family ipv4 does not exist'
        mock = MagicMock(return_value='')
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertEqual(nftables.append(chain='input', rule=_ru), ret)

        ret = 'Error: 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.append(chain='input', rule=_ru), ret)

        r_val = 'table ip filter chain input {{ input tcp dport 22 log accept #'
        mock = MagicMock(return_value=r_val)
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertTrue(nftables.append(chain='input', rule=_ru))

    @patch('salt.modules.nftables.check', MagicMock(return_value=False))
    @patch('salt.modules.nftables.check_chain', MagicMock(return_value=True))
    @patch('salt.modules.nftables.check_table', MagicMock(return_value=True))
    def test_append_rule(self):
        '''
        Test if it append a rule to the specified table & chain.
        '''
        _ru = 'input tcp dport 22 log accept'
        mock = MagicMock(side_effect=['1', ''])
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertFalse(nftables.append(chain='input', rule=_ru))
            self.assertTrue(nftables.append(chain='input', rule=_ru))

    # 'insert' function tests: 2

    def test_insert(self):
        '''
        Test if it insert a rule into the specified table & chain,
        at the specified position.
        '''
        self.assertEqual(nftables.insert(),
                         'Error: Chain needs to be specified')

        self.assertEqual(nftables.insert(chain='input'),
                         'Error: Rule needs to be specified')

        _ru = 'input tcp dport 22 log accept'
        ret = 'Error: table filter in family ipv4 does not exist'
        mock = MagicMock(return_value='')
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertEqual(nftables.insert(chain='input', rule=_ru), ret)

        ret = 'Error: 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.insert(chain='input', rule=_ru), ret)

        r_val = 'table ip filter chain input {{ input tcp dport 22 log accept #'
        mock = MagicMock(return_value=r_val)
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertTrue(nftables.insert(chain='input', rule=_ru))

    @patch('salt.modules.nftables.check', MagicMock(return_value=False))
    @patch('salt.modules.nftables.check_chain', MagicMock(return_value=True))
    @patch('salt.modules.nftables.check_table', MagicMock(return_value=True))
    def test_insert_rule(self):
        '''
        Test if it insert a rule into the specified table & chain,
        at the specified position.
        '''
        _ru = 'input tcp dport 22 log accept'
        mock = MagicMock(side_effect=['1', ''])
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertFalse(nftables.insert(chain='input', rule=_ru))
            self.assertTrue(nftables.insert(chain='input', rule=_ru))

    # 'delete' function tests: 2

    def test_delete(self):
        '''
        Test if it delete a rule from the specified table & chain,
        specifying either the rule in its entirety, or
        the rule's position in the chain.
        '''
        _ru = 'input tcp dport 22 log accept'
        self.assertEqual(
            nftables.delete(table='filter',
                            chain='input',
                            position='3',
                            rule=_ru),
            'Error: Only specify a position or a rule, not both')

        ret = 'Error: table filter in family ipv4 does not exist'
        mock = MagicMock(return_value='')
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertEqual(
                nftables.delete(table='filter', chain='input', rule=_ru), ret)

        ret = 'Error: 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.delete(table='filter', chain='input', rule=_ru), ret)

        mock = MagicMock(return_value='table ip filter chain input {{')
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertTrue(
                nftables.delete(table='filter', chain='input', rule=_ru))

    @patch('salt.modules.nftables.check', MagicMock(return_value=True))
    @patch('salt.modules.nftables.check_chain', MagicMock(return_value=True))
    @patch('salt.modules.nftables.check_table', MagicMock(return_value=True))
    def test_delete_rule(self):
        '''
        Test if it delete a rule from the specified table & chain,
        specifying either the rule in its entirety, or
        the rule's position in the chain.
        '''
        mock = MagicMock(side_effect=['1', ''])
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertFalse(
                nftables.delete(table='filter', chain='input', position='3'))
            self.assertTrue(
                nftables.delete(table='filter', chain='input', position='3'))

    # 'flush' function tests: 2

    def test_flush(self):
        '''
        Test if it flush the chain in the specified table, flush all chains
        in the specified table if chain is not specified.
        '''
        ret = 'Error: table filter in family ipv4 does not exist'
        mock = MagicMock(return_value='')
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertEqual(nftables.flush(table='filter', chain='input'),
                             ret)

        ret = 'Error: chain input in table filter in family ip does not exist'
        mock = MagicMock(return_value='table ip filter')
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertEqual(nftables.flush(table='filter', chain='input'),
                             ret)

    @patch('salt.modules.nftables.check_chain', MagicMock(return_value=True))
    @patch('salt.modules.nftables.check_table', MagicMock(return_value=True))
    def test_flush_chain(self):
        '''
        Test if it flush the chain in the specified table, flush all chains
        in the specified table if chain is not specified.
        '''
        mock = MagicMock(side_effect=['1', ''])
        with patch.dict(nftables.__salt__, {'cmd.run': mock}):
            self.assertFalse(nftables.flush(table='filter', chain='input'))
            self.assertTrue(nftables.flush(table='filter', chain='input'))
Beispiel #46
0
    def test_issue5940_install_multiple_pip_mirrors(self):
        mirrors = [
            'http://g.pypi.python.org', 'http://c.pypi.python.org',
            'http://pypi.crate.io'
        ]

        # Passing mirrors as a list
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
            pip.install(mirrors=mirrors)
            mock.assert_called_once_with(
                'pip install --use-mirrors '
                '--mirrors=http://g.pypi.python.org '
                '--mirrors=http://c.pypi.python.org '
                '--mirrors=http://pypi.crate.io',
                saltenv='base',
                runas=None,
                cwd=None)

        # Passing mirrors as a comma separated list
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
            pip.install(mirrors=','.join(mirrors))
            mock.assert_called_once_with(
                'pip install --use-mirrors '
                '--mirrors=http://g.pypi.python.org '
                '--mirrors=http://c.pypi.python.org '
                '--mirrors=http://pypi.crate.io',
                saltenv='base',
                runas=None,
                cwd=None)

        # As a single string
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
            pip.install(mirrors=mirrors[0])
            mock.assert_called_once_with(
                'pip install --use-mirrors '
                '--mirrors=http://g.pypi.python.org',
                saltenv='base',
                runas=None,
                cwd=None)
Beispiel #47
0
    def test_get_virtualenv_version_from_shell(self):
        with ForceImportErrorOn('virtualenv'):

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

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

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

            # ----- virtualenv binary returns 1.10rc1 as it's version ------->
            mock = MagicMock(side_effect=[{
                'retcode': 0,
                'stdout': '1.10rc1'
            }, {
                'retcode': 0,
                'stdout': ''
            }])
            with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
                virtualenv_mod.create('/tmp/foo', never_download=True)
                mock.assert_called_with('virtualenv /tmp/foo', runas=None)
Beispiel #48
0
    def test_install_with_multiple_find_links(self):
        find_links = [
            'http://g.pypi.python.org', 'http://c.pypi.python.org',
            'http://pypi.crate.io'
        ]

        # Passing mirrors as a list
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
            pip.install('pep8', find_links=find_links)
            mock.assert_called_once_with(
                'pip install '
                '--find-links=http://g.pypi.python.org '
                '--find-links=http://c.pypi.python.org '
                '--find-links=http://pypi.crate.io \'pep8\'',
                saltenv='base',
                runas=None,
                cwd=None)

        # Passing mirrors as a comma separated list
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
            pip.install('pep8', find_links=','.join(find_links))
            mock.assert_called_once_with(
                'pip install '
                '--find-links=http://g.pypi.python.org '
                '--find-links=http://c.pypi.python.org '
                '--find-links=http://pypi.crate.io \'pep8\'',
                saltenv='base',
                runas=None,
                cwd=None)

        # Passing mirrors as a single string entry
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
            pip.install('pep8', find_links=find_links[0])
            mock.assert_called_once_with(
                'pip install --find-links=http://g.pypi.python.org \'pep8\'',
                saltenv='base',
                runas=None,
                cwd=None)

        # Invalid proto raises exception
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
            self.assertRaises(CommandExecutionError,
                              pip.install,
                              '\'pep8\'',
                              find_links='sftp://pypi.crate.io')

        # Valid protos work?
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
            pip.install('pep8',
                        find_links=[
                            'ftp://g.pypi.python.org',
                            'http://c.pypi.python.org', 'https://pypi.crate.io'
                        ])
            mock.assert_called_once_with(
                'pip install '
                '--find-links=ftp://g.pypi.python.org '
                '--find-links=http://c.pypi.python.org '
                '--find-links=https://pypi.crate.io \'pep8\'',
                saltenv='base',
                runas=None,
                cwd=None)
Beispiel #49
0
    def test_present_when_function_exists_and_permissions(self):
        self.conn.list_functions.return_value = {'Functions': [function_ret]}
        self.conn.update_function_code.return_value = function_ret
        self.conn.get_policy.return_value = {
            "Policy":
            json.dumps({
                "Version":
                "2012-10-17",
                "Statement": [{
                    "Condition": {
                        "ArnLike": {
                            "AWS:SourceArn":
                            "arn:aws:events:us-east-1:9999999999:rule/fooo"
                        }
                    },
                    "Action": "lambda:InvokeFunction",
                    "Resource":
                    "arn:aws:lambda:us-east-1:999999999999:function:testfunction",
                    "Effect": "Allow",
                    "Principal": {
                        "Service": "events.amazonaws.com"
                    },
                    "Sid": "AWSEvents_foo-bar999999999999"
                }],
                "Id":
                "default"
            })
        }

        with patch.dict(
                funcs,
            {'boto_iam.get_account_id': MagicMock(return_value='1234')}):
            with TempZipFile() as zipfile:
                with patch('hashlib.sha256') as sha256:
                    with patch('os.path.getsize', return_value=199):
                        sha = sha256()
                        digest = sha.digest()
                        encoded = sha.encode()
                        encoded.strip.return_value = function_ret['CodeSha256']
                        result = salt_states['boto_lambda.function_present'](
                            'function present',
                            FunctionName=function_ret['FunctionName'],
                            Runtime=function_ret['Runtime'],
                            Role=function_ret['Role'],
                            Handler=function_ret['Handler'],
                            ZipFile=zipfile,
                            Description=function_ret['Description'],
                            Timeout=function_ret['Timeout'])
        self.assertTrue(result['result'])
        self.assertEqual(
            result['changes'], {
                'old': {
                    'Permissions': {
                        'AWSEvents_foo-bar999999999999': {
                            'Action':
                            'lambda:InvokeFunction',
                            'Principal':
                            'events.amazonaws.com',
                            'SourceArn':
                            'arn:aws:events:us-east-1:9999999999:rule/fooo'
                        }
                    }
                },
                'new': {
                    'Permissions': {
                        'AWSEvents_foo-bar999999999999': {}
                    }
                }
            })
Beispiel #50
0
    def test_install_install_options_argument_in_resulting_command(self):
        install_options = [
            '--exec-prefix=/foo/bar', '--install-scripts=/foo/bar/bin'
        ]

        # Passing options as a list
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
            pip.install('pep8', install_options=install_options)
            mock.assert_called_once_with(
                'pip install '
                '--install-option=\'--exec-prefix=/foo/bar\' '
                '--install-option=\'--install-scripts=/foo/bar/bin\' \'pep8\'',
                saltenv='base',
                runas=None,
                cwd=None)

        # Passing mirrors as a comma separated list
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
            pip.install('pep8', install_options=','.join(install_options))
            mock.assert_called_once_with(
                'pip install '
                '--install-option=\'--exec-prefix=/foo/bar\' '
                '--install-option=\'--install-scripts=/foo/bar/bin\' \'pep8\'',
                saltenv='base',
                runas=None,
                cwd=None)

        # Passing mirrors as a single string entry
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
            pip.install('pep8', install_options=install_options[0])
            mock.assert_called_once_with(
                'pip install --install-option=\'--exec-prefix=/foo/bar\' '
                '\'pep8\'',
                saltenv='base',
                runas=None,
                cwd=None)
Beispiel #51
0
class PostgresSchemaTestCase(TestCase):
    @patch.dict(
        SALT_STUB, {
            'postgres.schema_get': Mock(return_value=None),
            'postgres.schema_create': MagicMock(),
        })
    def test_present_creation(self):
        ret = postgres_schema.present('dbname', 'foo')
        self.assertEqual(
            ret, {
                'comment': 'Schema foo has been created in database dbname',
                'changes': {
                    'foo': 'Present'
                },
                'dbname': 'dbname',
                'name': 'foo',
                'result': True
            })
        self.assertEqual(SALT_STUB['postgres.schema_create'].call_count, 1)

    @patch.dict(
        SALT_STUB, {
            'postgres.schema_get':
            Mock(return_value={'foo': {
                'acl': '',
                'owner': 'postgres'
            }}),
            'postgres.schema_create':
            MagicMock(),
        })
    def test_present_nocreation(self):
        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(SALT_STUB['postgres.schema_create'].call_count, 0)

    @patch.dict(
        SALT_STUB, {
            'postgres.schema_exists': Mock(return_value=True),
            'postgres.schema_remove': MagicMock(),
        })
    def test_absent_remove(self):
        ret = postgres_schema.absent('dbname', 'foo')
        self.assertEqual(
            ret, {
                'comment': 'Schema foo has been removed from database dbname',
                'changes': {
                    'foo': 'Absent'
                },
                'dbname': 'dbname',
                'name': 'foo',
                'result': True
            })
        self.assertEqual(SALT_STUB['postgres.schema_remove'].call_count, 1)

    @patch.dict(
        SALT_STUB, {
            'postgres.schema_exists': Mock(return_value=False),
            'postgres.schema_remove': MagicMock(),
        })
    def test_absent_noremove(self):
        ret = postgres_schema.absent('dbname', 'foo')
        self.assertEqual(
            ret, {
                'comment': 'Schema foo is not present in database dbname,'
                ' so it cannot be removed',
                'changes': {},
                'dbname': 'dbname',
                'name': 'foo',
                'result': True
            })
        self.assertEqual(SALT_STUB['postgres.schema_remove'].call_count, 0)
Beispiel #52
0
    def test_install_global_options_argument_in_resulting_command(self):
        global_options = ['--quiet', '--no-user-cfg']

        # Passing options as a list
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
            pip.install('pep8', global_options=global_options)
            mock.assert_called_once_with(
                'pip install '
                '--global-option=\'--quiet\' '
                '--global-option=\'--no-user-cfg\' \'pep8\'',
                saltenv='base',
                runas=None,
                cwd=None)

        # Passing mirrors as a comma separated list
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
            pip.install('pep8', global_options=','.join(global_options))
            mock.assert_called_once_with(
                'pip install '
                '--global-option=\'--quiet\' '
                '--global-option=\'--no-user-cfg\' \'pep8\'',
                saltenv='base',
                runas=None,
                cwd=None)

        # Passing mirrors as a single string entry
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
            pip.install('pep8', global_options=global_options[0])
            mock.assert_called_once_with(
                'pip install --global-option=\'--quiet\' \'pep8\'',
                saltenv='base',
                runas=None,
                cwd=None)
Beispiel #53
0
    def test_present(self):
        '''
        Test to verifies that the specified host is known by the specified user.
        '''
        name = 'github.com'
        user = '******'
        key = '16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48'
        fingerprint = [key]

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

        with patch.dict(ssh_known_hosts.__opts__, {'test': True}):
            with patch.object(os.path, 'isabs', MagicMock(return_value=False)):
                comt = ('If not specifying a "user", '
                        'specify an absolute "config".')
                ret.update({'comment': comt})
                self.assertDictEqual(ssh_known_hosts.present(name), ret)

            comt = ('Specify either "key" or "fingerprint", not both.')
            ret.update({'comment': comt})
            self.assertDictEqual(
                ssh_known_hosts.present(name, user, key=key,
                                        fingerprint=[key]), ret)

            comt = ('Required argument "enc" if using "key" argument.')
            ret.update({'comment': comt})
            self.assertDictEqual(ssh_known_hosts.present(name, user, key=key),
                                 ret)

            mock = MagicMock(side_effect=['exists', 'add', 'update'])
            with patch.dict(ssh_known_hosts.__salt__,
                            {'ssh.check_known_host': mock}):
                comt = ('Host github.com is already in .ssh/known_hosts')
                ret.update({'comment': comt, 'result': True})
                self.assertDictEqual(ssh_known_hosts.present(name, user), ret)

                comt = ('Key for github.com is set to be'
                        ' added to .ssh/known_hosts')
                ret.update({'comment': comt, 'result': None})
                self.assertDictEqual(ssh_known_hosts.present(name, user), ret)

                comt = ('Key for github.com is set to be '
                        'updated in .ssh/known_hosts')
                ret.update({'comment': comt})
                self.assertDictEqual(ssh_known_hosts.present(name, user), ret)

        with patch.dict(ssh_known_hosts.__opts__, {'test': False}):
            result = {'status': 'exists', 'error': ''}
            mock = MagicMock(return_value=result)
            with patch.dict(ssh_known_hosts.__salt__,
                            {'ssh.set_known_host': mock}):
                comt = ('github.com already exists in .ssh/known_hosts')
                ret.update({'comment': comt, 'result': True})
                self.assertDictEqual(ssh_known_hosts.present(name, user), ret)

            result = {'status': 'error', 'error': ''}
            mock = MagicMock(return_value=result)
            with patch.dict(ssh_known_hosts.__salt__,
                            {'ssh.set_known_host': mock}):
                ret.update({'comment': '', 'result': False})
                self.assertDictEqual(ssh_known_hosts.present(name, user), ret)

            result = {
                'status': 'updated',
                'error': '',
                'new': {
                    'fingerprint': fingerprint,
                    'key': key
                },
                'old': ''
            }
            mock = MagicMock(return_value=result)
            with patch.dict(ssh_known_hosts.__salt__,
                            {'ssh.set_known_host': mock}):
                comt = (
                    "{0}'s key saved to .ssh/known_hosts (key: {1})".format(
                        name, key))
                ret.update({
                    'comment': comt,
                    'result': True,
                    'changes': {
                        'new': {
                            'fingerprint': fingerprint,
                            'key': key
                        },
                        'old': ''
                    }
                })
                self.assertDictEqual(
                    ssh_known_hosts.present(name, user, key=key), ret)

                comt = (
                    "{0}'s key saved to .ssh/known_hosts (fingerprint: {1})".
                    format(name, fingerprint))
                ret.update({'comment': comt})
                self.assertDictEqual(ssh_known_hosts.present(name, user), ret)
Beispiel #54
0
    def test_uninstall_multiple_requirements_arguments_in_resulting_command(
            self, get_cached_requirements):
        get_cached_requirements.side_effect = [
            'my_cached_reqs-1', 'my_cached_reqs-2'
        ]
        requirements = [
            'salt://requirements-1.txt', 'salt://requirements-2.txt'
        ]

        # Passing option as a list
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
            pip.uninstall(requirements=requirements)
            mock.assert_called_once_with(
                'pip uninstall -y '
                '--requirement=\'my_cached_reqs-1\' '
                '--requirement=\'my_cached_reqs-2\'',
                saltenv='base',
                runas=None,
                cwd=None)

        # Passing option as a comma separated list
        get_cached_requirements.side_effect = [
            'my_cached_reqs-1', 'my_cached_reqs-2'
        ]
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
            pip.uninstall(requirements=','.join(requirements))
            mock.assert_called_once_with(
                'pip uninstall -y '
                '--requirement=\'my_cached_reqs-1\' '
                '--requirement=\'my_cached_reqs-2\'',
                saltenv='base',
                runas=None,
                cwd=None)

        # Passing option as a single string entry
        get_cached_requirements.side_effect = ['my_cached_reqs-1']
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
            pip.uninstall(requirements=requirements[0])
            mock.assert_called_once_with(
                'pip uninstall -y --requirement=\'my_cached_reqs-1\'',
                saltenv='base',
                runas=None,
                cwd=None)
Beispiel #55
0
    def test_command_defined_on_image_layer_dont_diff_if_attempted_to_blank(
            self):
        '''
        Assuming the docker image has a command defined, like ``sh``.
        Erasing this value on sls level will not delete the command
        in the container. And such the diff shouldn't be reported.
        Assuming also the container is already running.

        1. define your sls

        .. code-block:: yaml

            cont:
                docker.running:
                    - image: image:latest


        2. run state.highstate

        No diff should be reported
        '''
        image_id = 'abcdefg'
        docker_create = Mock(return_value=True)
        docker_start = Mock()
        docker_list_containers = Mock(return_value=['cont'])
        docker_inspect_container = Mock(side_effect=[{
            'Config': {
                'Image': 'image:latest',
                'Tty': False,
                'Labels': {},
                'Domainname': '',
                'User': '',
                'AttachStderr': True,
                'AttachStdout': True,
                'Hostname': 'saltstack-container',
                'Env': [],
                'WorkingDir': '/',
                'Cmd': None,
                'Volumes': {},
                'Entrypoint': None,
                'ExposedPorts': {},
                'OpenStdin': False,
            },
            'HostConfig': {
                'PublishAllPorts': False,
                'Dns': [],
                'Links': None,
                'CpusetCpus': '',
                'RestartPolicy': {
                    'MaximumRetryCount': 0,
                    'Name': ''
                },
                'CapAdd': None,
                'NetworkMode': 'default',
                'PidMode': '',
                'MemorySwap': 0,
                'ExtraHosts': None,
                'PortBindings': None,
                'LxcConf': None,
                'DnsSearch': [],
                'Privileged': False,
                'Binds': [],
                'Memory': 0,
                'VolumesFrom': None,
                'CpuShares': 0,
                'CapDrop': None,
            },
            'NetworkSettings': {
                'MacAddress': '00:00:00:00:00:01',
            },
            'Image': image_id
        }])
        docker_inspect_image = MagicMock(
            return_value={
                'Id': image_id,
                'Config': {
                    'Hostname': 'saltstack-container',
                    'WorkingDir': '/',
                    'Cmd': ['bash'],  # !!! Cmd defined on Image
                    'Volumes': {},
                    'Entrypoint': None,
                    'ExposedPorts': {},
                },
            })
        __salt__ = {
            'docker.list_containers': docker_list_containers,
            'docker.inspect_container': docker_inspect_container,
            'docker.inspect_image': docker_inspect_image,
            'docker.list_tags': MagicMock(side_effect=[['image:latest']]),
            'docker.state': MagicMock(side_effect=['running']),
        }
        with patch.dict(docker_state.__dict__, {'__salt__': __salt__}):
            ret = docker_state.running(
                'cont',
                image='image:latest',
            )
        self.assertEqual(
            ret, {
                'name': 'cont',
                'comment': "Container 'cont' is already"
                " configured as specified",
                'changes': {},
                'result': True,
            })
Beispiel #56
0
    def test_install_multiple_pkgs_and_editables(self):
        pkgs = ['pep8', 'salt']

        editables = [
            'git+https://github.com/jek/blinker.git#egg=Blinker',
            'git+https://github.com/saltstack/salt-testing.git#egg=SaltTesting'
        ]

        # Passing editables as a list
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
            pip.install(pkgs=pkgs, editable=editables)
            mock.assert_called_once_with(
                'pip install \'pep8\' \'salt\' '
                '--editable=git+https://github.com/jek/blinker.git#egg=Blinker '
                '--editable=git+https://github.com/saltstack/salt-testing.git#egg=SaltTesting',
                saltenv='base',
                runas=None,
                cwd=None)

        # Passing editables as a comma separated list
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
            pip.install(pkgs=','.join(pkgs), editable=','.join(editables))
            mock.assert_called_once_with(
                'pip install \'pep8\' \'salt\' '
                '--editable=git+https://github.com/jek/blinker.git#egg=Blinker '
                '--editable=git+https://github.com/saltstack/salt-testing.git#egg=SaltTesting',
                saltenv='base',
                runas=None,
                cwd=None)

        # As a single string
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
        with patch.dict(pip.__salt__, {'cmd.run_all': mock}):
            pip.install(pkgs=pkgs[0], editable=editables[0])
            mock.assert_called_once_with(
                'pip install \'pep8\' '
                '--editable=git+https://github.com/jek/blinker.git#egg=Blinker',
                saltenv='base',
                runas=None,
                cwd=None)
Beispiel #57
0
class GroupAddTestCase(TestCase):
    '''
    TestCase for salt.modules.groupadd
    '''
    groupadd.__grains__ = {}
    groupadd.__salt__ = {}
    groupadd.__context__ = {}
    mock_group = {'passwd': '*', 'gid': 0, 'name': 'test', 'members': ['root']}
    mock_getgrnam = grp.struct_group(('foo', '*', 20, ['test']))

    # 'add' function tests: 1

    def test_add(self):
        '''
        Tests if specified group was added
        '''
        mock = MagicMock(return_value={'retcode': 0})
        with patch.dict(groupadd.__salt__, {'cmd.run_all': mock}):
            self.assertTrue(groupadd.add('test', 100))

        with patch.dict(groupadd.__grains__, {'kernel': 'Linux'}):
            with patch.dict(groupadd.__salt__, {'cmd.run_all': mock}):
                self.assertTrue(groupadd.add('test', 100, True))

    # 'info' function tests: 1

    @patch('grp.getgrnam', MagicMock(return_value=mock_getgrnam))
    def test_info(self):
        '''
        Tests the return of group information
        '''
        ret = {'passwd': '*', 'gid': 20, 'name': 'foo', 'members': ['test']}
        self.assertEqual(groupadd.info('foo'), ret)

    # '_format_info' function tests: 1

    @patch('salt.modules.groupadd._format_info',
           MagicMock(return_value=mock_group))
    def test_format_info(self):
        '''
        Tests the formatting of returned group information
        '''
        data = grp.struct_group(('wheel', '*', 0, ['root']))
        ret = {'passwd': '*', 'gid': 0, 'name': 'test', 'members': ['root']}
        self.assertDictEqual(groupadd._format_info(data), ret)

    # 'getent' function tests: 1

    @patch('grp.getgrall', MagicMock(return_value=[mock_getgrnam]))
    def test_getent(self):
        '''
        Tests the return of information on all groups
        '''
        ret = [{'passwd': '*', 'gid': 20, 'name': 'foo', 'members': ['test']}]
        self.assertEqual(groupadd.getent(), ret)

    # 'chgid' function tests: 2

    def test_chgid_gid_same(self):
        '''
        Tests if the group id is the same as argument
        '''
        mock_pre_gid = MagicMock(return_value=10)
        with patch.dict(groupadd.__salt__,
                        {'file.group_to_gid': mock_pre_gid}):
            self.assertTrue(groupadd.chgid('test', 10))

    def test_chgid(self):
        '''
        Tests the gid for a named group was changed
        '''
        mock_pre_gid = MagicMock(return_value=0)
        mock_cmdrun = MagicMock(return_value=0)
        with patch.dict(groupadd.__salt__,
                        {'file.group_to_gid': mock_pre_gid}):
            with patch.dict(groupadd.__salt__, {'cmd.run': mock_cmdrun}):
                self.assertFalse(groupadd.chgid('test', 500))

    # 'delete' function tests: 1

    def test_delete(self):
        '''
        Tests if the specified group was deleted
        '''
        mock_ret = MagicMock(return_value={'retcode': 0})
        with patch.dict(groupadd.__salt__, {'cmd.run_all': mock_ret}):
            self.assertTrue(groupadd.delete('test'))

    # 'adduser' function tests: 1

    def test_adduser(self):
        '''
        Tests if specified user gets added in the group.
        '''
        os_version_list = [
            {
                'grains': {
                    'kernel': 'Linux',
                    'os_family': 'RedHat',
                    'osmajorrelease': '5'
                },
                'cmd': 'gpasswd -a root test'
            },
            {
                'grains': {
                    'kernel': 'Linux',
                    'os_family': 'Suse',
                    'osrelease_info': [11, 2]
                },
                'cmd': 'usermod -A test root'
            },
            {
                'grains': {
                    'kernel': 'Linux'
                },
                'cmd': 'gpasswd --add root test'
            },
            {
                'grains': {
                    'kernel': 'OTHERKERNEL'
                },
                'cmd': 'usermod -G test root'
            },
        ]

        for os_version in os_version_list:
            mock = MagicMock(return_value={'retcode': 0})
            with patch.dict(groupadd.__grains__, os_version['grains']):
                with patch.dict(groupadd.__salt__, {'cmd.retcode': mock}):
                    self.assertFalse(groupadd.adduser('test', 'root'))
                    groupadd.__salt__['cmd.retcode'].assert_called_once_with(
                        os_version['cmd'], python_shell=False)

    # 'deluser' function tests: 1

    def test_deluser(self):
        '''
        Tests if specified user gets deleted from the group.
        '''
        os_version_list = [
            {
                'grains': {
                    'kernel': 'Linux',
                    'os_family': 'RedHat',
                    'osmajorrelease': '5'
                },
                'cmd': 'gpasswd -d root test'
            },
            {
                'grains': {
                    'kernel': 'Linux',
                    'os_family': 'Suse',
                    'osrelease_info': [11, 2]
                },
                'cmd': 'usermod -R test root'
            },
            {
                'grains': {
                    'kernel': 'Linux'
                },
                'cmd': 'gpasswd --del root test'
            },
            {
                'grains': {
                    'kernel': 'OpenBSD'
                },
                'cmd': 'usermod -S foo root'
            },
        ]

        for os_version in os_version_list:
            mock_ret = MagicMock(return_value={'retcode': 0})
            mock_stdout = MagicMock(return_value='test foo')
            mock_info = MagicMock(return_value={
                'passwd': '*',
                'gid': 0,
                'name': 'test',
                'members': ['root']
            })

            with patch.dict(groupadd.__grains__, os_version['grains']):
                with patch.dict(
                        groupadd.__salt__, {
                            'cmd.retcode': mock_ret,
                            'group.info': mock_info,
                            'cmd.run_stdout': mock_stdout
                        }):
                    self.assertFalse(groupadd.deluser('test', 'root'))
                    groupadd.__salt__['cmd.retcode'].assert_called_once_with(
                        os_version['cmd'], python_shell=False)

    # 'deluser' function tests: 1

    def test_members(self):
        '''
        Tests if members of the group, get replaced with a provided list.
        '''
        os_version_list = [
            {
                'grains': {
                    'kernel': 'Linux',
                    'os_family': 'RedHat',
                    'osmajorrelease': '5'
                },
                'cmd': "gpasswd -M foo test"
            },
            {
                'grains': {
                    'kernel': 'Linux',
                    'os_family': 'Suse',
                    'osrelease_info': [11, 2]
                },
                'cmd': 'groupmod -A foo test'
            },
            {
                'grains': {
                    'kernel': 'Linux'
                },
                'cmd': 'gpasswd --members foo test'
            },
            {
                'grains': {
                    'kernel': 'OpenBSD'
                },
                'cmd': 'usermod -G test foo'
            },
        ]

        for os_version in os_version_list:
            mock_ret = MagicMock(return_value={'retcode': 0})
            mock_stdout = MagicMock(return_value={'cmd.run_stdout': 1})
            mock_info = MagicMock(return_value={
                'passwd': '*',
                'gid': 0,
                'name': 'test',
                'members': ['root']
            })
            mock = MagicMock(return_value=True)

            with patch.dict(groupadd.__grains__, os_version['grains']):
                with patch.dict(
                        groupadd.__salt__, {
                            'cmd.retcode': mock_ret,
                            'group.info': mock_info,
                            'cmd.run_stdout': mock_stdout,
                            'cmd.run': mock
                        }):
                    self.assertFalse(groupadd.members('test', 'foo'))
                    groupadd.__salt__['cmd.retcode'].assert_called_once_with(
                        os_version['cmd'], python_shell=False)
Beispiel #58
0
class DaemontoolsTestCase(TestCase):
    '''
    Test cases for salt.modules.daemontools
    '''
    def test_start(self):
        '''
        Test for Starts service via daemontools
        '''
        mock = MagicMock(return_value=None)
        with patch.dict(daemontools.__salt__, {'file.remove': mock}):
            mock = MagicMock(return_value='')
            with patch.object(daemontools, '_service_path', mock):
                mock = MagicMock(return_value=False)
                with patch.dict(daemontools.__salt__, {'cmd.retcode': mock}):
                    self.assertTrue(daemontools.start('name'))

    def test_stop(self):
        '''
        Test for Stops service via daemontools
        '''
        mock = MagicMock(return_value=None)
        with patch.dict(daemontools.__salt__, {'file.touch': mock}):
            mock = MagicMock(return_value='')
            with patch.object(daemontools, '_service_path', mock):
                mock = MagicMock(return_value=False)
                with patch.dict(daemontools.__salt__, {'cmd.retcode': mock}):
                    self.assertTrue(daemontools.stop('name'))

    def test_term(self):
        '''
        Test for Send a TERM to service via daemontools
        '''
        mock = MagicMock(return_value='')
        with patch.object(daemontools, '_service_path', mock):
            mock = MagicMock(return_value=False)
            with patch.dict(daemontools.__salt__, {'cmd.retcode': mock}):
                self.assertTrue(daemontools.term('name'))

    def test_reload_(self):
        '''
        Test for Wrapper for term()
        '''
        mock = MagicMock(return_value=None)
        with patch.object(daemontools, 'term', mock):
            self.assertEqual(daemontools.reload_('name'), None)

    def test_restart(self):
        '''
        Test for Restart service via daemontools. This will stop/start service
        '''
        mock = MagicMock(return_value=False)
        with patch.object(daemontools, 'stop', mock):
            self.assertEqual(daemontools.restart('name'), 'restart False')

    def test_full_restart(self):
        '''
        Test for Calls daemontools.restart() function
        '''
        mock = MagicMock(return_value=None)
        with patch.object(daemontools, 'restart', mock):
            self.assertEqual(daemontools.restart('name'), None)

    @patch('re.search', MagicMock(return_value=1))
    def test_status(self):
        '''
        Test for Return the status for a service via
        daemontools, return pid if running
        '''
        mock = MagicMock(return_value='')
        with patch.object(daemontools, '_service_path', mock):
            mock = MagicMock(return_value='name')
            with patch.dict(daemontools.__salt__, {'cmd.run_stdout': mock}):
                self.assertEqual(daemontools.status('name'), '')

    def test_available(self):
        '''
        Test for Returns ``True`` if the specified service
        is available, otherwise returns``False``.
        '''
        mock = MagicMock(return_value=[])
        with patch.object(daemontools, 'get_all', mock):
            self.assertFalse(daemontools.available('name'))

    def test_missing(self):
        '''
        Test for The inverse of daemontools.available.
        '''
        mock = MagicMock(return_value=[])
        with patch.object(daemontools, 'get_all', mock):
            self.assertTrue(daemontools.missing('name'))

    def test_get_all(self):
        '''
        Test for Return a list of all available services
        '''
        self.assertRaises(CommandExecutionError, daemontools.get_all)

        daemontools.SERVICE_DIR = 'A'
        mock = MagicMock(return_value='A')
        with patch.object(os, 'listdir', mock):
            self.assertEqual(daemontools.get_all(), ['A'])
Beispiel #59
0
    def test_removal_of_parameter_is_detected(self):
        '''
        Test dockerng.running with deleted parameter.

        1. define your sls

        .. code-block:: yaml

            container:
                dockerng.running:
                    - name: super-container
                    - binds:
                        - /path:/path:ro

        2. run state.highstate

        3. modify your sls by removing `- binds:`

        .. code-block:: yaml

            container:
                dockerng.running:
                    - name: super-container

        4. enjoy your new created container without mounted volumes.
        '''
        image_id = 'abcdefg'
        dockerng_create = Mock(return_value=True)
        dockerng_start = Mock()
        dockerng_list_containers = Mock(return_value=['cont'])
        dockerng_inspect_container = Mock(side_effect=[{
            'Config': {
                'Image': 'image:latest',
                'Tty': False,
                'Labels': {},
                'Domainname': '',
                'User': '',
                'AttachStderr': True,
                'AttachStdout': True,
                'Hostname': 'saltstack-container',
                'Env': [],
                'WorkingDir': '/',
                'Cmd': ['bash'],
                'Volumes': {
                    '/path': {}
                },
                'Entrypoint': None,
                'ExposedPorts': {},
                'OpenStdin': False,
            },
            'HostConfig': {
                'PublishAllPorts': False,
                'Dns': [],
                'Links': None,
                'CpusetCpus': '',
                'RestartPolicy': {
                    'MaximumRetryCount': 0,
                    'Name': ''
                },
                'CapAdd': None,
                'NetworkMode': 'default',
                'PidMode': '',
                'MemorySwap': 0,
                'ExtraHosts': None,
                'PortBindings': None,
                'LxcConf': None,
                'DnsSearch': [],
                'Privileged': False,
                'Binds': ['/path:/path:ro'],
                'Memory': 0,
                'VolumesFrom': None,
                'CpuShares': 0,
                'CapDrop': None,
            },
            'NetworkSettings': {
                'MacAddress': '00:00:00:00:00:01',
            },
            'Image': image_id
        }, {
            'Config': {
                'Image': 'image:latest',
                'Tty': False,
                'Labels': {},
                'Domainname': '',
                'User': '',
                'AttachStderr': True,
                'AttachStdout': True,
                'Hostname': 'saltstack-container',
                'Env': [],
                'WorkingDir': '/',
                'Cmd': ['bash'],
                'Volumes': {
                    '/path': {}
                },
                'Entrypoint': None,
                'ExposedPorts': {},
                'OpenStdin': False,
            },
            'HostConfig': {
                'PublishAllPorts': False,
                'Dns': [],
                'Links': None,
                'CpusetCpus': '',
                'RestartPolicy': {
                    'MaximumRetryCount': 0,
                    'Name': ''
                },
                'CapAdd': None,
                'NetworkMode': 'default',
                'PidMode': '',
                'MemorySwap': 0,
                'ExtraHosts': None,
                'PortBindings': None,
                'LxcConf': None,
                'DnsSearch': [],
                'Privileged': False,
                'Binds': None,
                'Memory': 0,
                'VolumesFrom': None,
                'CpuShares': 0,
                'CapDrop': None,
            },
            'NetworkSettings': {
                'MacAddress': '00:00:00:00:00:01',
            },
            'Image': image_id
        }])
        dockerng_inspect_image = MagicMock(
            return_value={
                'Id': image_id,
                'Config': {
                    'Hostname': 'saltstack-container',
                    'WorkingDir': '/',
                    'Cmd': ['bash'],
                    'Volumes': {
                        '/path': {}
                    },
                    'Entrypoint': None,
                    'ExposedPorts': {},
                },
            })
        __salt__ = {
            'dockerng.list_containers': dockerng_list_containers,
            'dockerng.inspect_container': dockerng_inspect_container,
            'dockerng.inspect_image': dockerng_inspect_image,
            'dockerng.list_tags': MagicMock(),
            'dockerng.pull': MagicMock(return_value=True),
            'dockerng.state': MagicMock(side_effect=['stopped', 'running']),
            'dockerng.rm': MagicMock(return_value='cont'),
            'dockerng.create': dockerng_create,
            'dockerng.start': dockerng_start,
        }
        with patch.dict(dockerng_state.__dict__, {'__salt__': __salt__}):
            ret = dockerng_state.running(
                'cont',
                image='image:latest',
            )
        self.assertEqual(
            ret, {
                'name': 'cont',
                'comment': "Container 'cont' changed state.."
                " Container 'cont' was replaced.",
                'changes': {
                    'diff': {
                        'binds': {
                            'new': [],
                            'old': ['/path:/path:ro']
                        }
                    },
                    'image': True,
                    'removed': 'cont',
                    'state': {
                        'new': 'running',
                        'old': 'stopped'
                    },
                    'added': True,
                },
                'result': True,
            })
        dockerng_create.assert_called_with('image:latest',
                                           validate_ip_addrs=False,
                                           validate_input=False,
                                           name='cont',
                                           client_timeout=60)
Beispiel #60
0
    def test_issue_6030_deprecated_never_download(self):
        mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})

        with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
            virtualenv_mod.create('/tmp/foo', never_download=True)
            mock.assert_called_once_with(
                'virtualenv --never-download /tmp/foo', runas=None)

        with TestsLoggingHandler() as handler:
            mock = MagicMock(return_value={'retcode': 0, 'stdout': ''})
            # Let's fake a higher virtualenv version
            virtualenv_mock = MagicMock()
            virtualenv_mock.__version__ = '1.10rc1'
            with patch.dict(virtualenv_mod.__salt__, {'cmd.run_all': mock}):
                with patch.dict('sys.modules',
                                {'virtualenv': virtualenv_mock}):
                    virtualenv_mod.create('/tmp/foo', never_download=True)
                    mock.assert_called_once_with('virtualenv /tmp/foo',
                                                 runas=None)

                # Are we logging the deprecation information?
                self.assertIn(
                    'INFO:The virtualenv \'--never-download\' option has been '
                    'deprecated in virtualenv(>=1.10), as such, the '
                    '\'never_download\' option to `virtualenv.create()` has '
                    'also been deprecated and it\'s not necessary anymore.',
                    handler.messages)