Exemple #1
0
    def test_repo_noadd_mod_noref(self):
        '''
        Test mod_repo detects the repository exists,
        calls modify to update 'autorefresh' but does not call refresh

        :return:
        '''
        url = self.new_repo_config['url']
        name = self.new_repo_config['name']
        self.zypper_patcher_config['_get_configured_repos'] = Mock(
            **{'return_value.sections.return_value': [name]})
        zypper_patcher = patch.multiple('salt.modules.zypper',
                                        **self.zypper_patcher_config)
        with zypper_patcher:
            zypper.mod_repo(name, **{'url': url, 'refresh': True})
            zypper.__zypper__.xml.call.assert_not_called()
            zypper.__zypper__.refreshable.xml.call.assert_called_once_with(
                'mr', '--refresh', name)
Exemple #2
0
    def test_device_no_repeat_with_not_found_state(self):
        config = {'states': ['offline'], 'battery_low': 30}

        out = [
            'List of devices attached\nHTC\tdevice', '25',
            'List of devices attached\nHTC\tdevice', '25'
        ]
        mock = Mock(side_effect=out)
        with patch.dict(adb.__salt__, {'cmd.run': mock}):
            ret = adb.beacon(config)
            self.assertEqual(ret, [{
                'device': 'HTC',
                'battery_level': 25,
                'tag': 'battery_low'
            }])

            ret = adb.beacon(config)
            self.assertEqual(ret, [])
Exemple #3
0
    def test_version(self, popen_mock):
        '''
        Test that salt.utils.systemd.booted() returns True when minion is
        systemd-booted.
        '''
        _version = 231
        output = 'systemd {0}\n-SYSVINIT'.format(_version)
        popen_mock.return_value = Mock(
            communicate=lambda *args, **kwargs: (output, None),
            pid=lambda: 12345,
            retcode=0
        )

        # Test without context dict passed
        self.assertEqual(_systemd.version(), _version)
        # Test that context key is set when context dict is passed
        context = {}
        self.assertTrue(_systemd.version(context))
        self.assertEqual(context, {'salt.utils.systemd.version': _version})
Exemple #4
0
    def test_multiple_low_batteries(self):
        config = {'states': ['device'], 'battery_low': 30}

        out = [
            'List of devices attached\nHTC\tdevice',
            '25\n14',
        ]
        mock = Mock(side_effect=out)
        with patch.dict(adb.__salt__, {'cmd.run': mock}):
            ret = adb.beacon(config)
            self.assertEqual(ret, [{
                'device': 'HTC',
                'state': 'device',
                'tag': 'device'
            }, {
                'device': 'HTC',
                'battery_level': 25,
                'tag': 'battery_low'
            }])
Exemple #5
0
 def test_has_scope_version_parse_problem(self, popen_mock):
     '''
     Test the case where the system is systemd-booted, but we failed to
     parse the "systemctl --version" output.
     '''
     popen_mock.return_value = Mock(
         communicate=lambda *args, **kwargs: ('invalid', None),
         pid=lambda: 12345,
         retcode=0
     )
     with patch('os.stat', side_effect=_booted_effect):
         # Test without context dict passed
         self.assertFalse(_systemd.has_scope())
         # Test that context key is set when context dict is passed. A
         # failure to parse the systemctl output should not set a context
         # key, so it should not be present in the context dict.
         context = {}
         self.assertFalse(_systemd.has_scope(context))
         self.assertEqual(context, {'salt.utils.systemd.booted': True})
Exemple #6
0
    def test_running_with_labels_from_image(self):
        '''
        Test dockerng.running with labels parameter supports also
        labels carried by the image.
        '''
        dockerng_create = Mock()

        image_id = 'a' * 128
        dockerng_inspect_image = MagicMock(
            return_value={
                'Id': image_id,
                'Config': {
                    'Hostname': 'saltstack-container',
                    'WorkingDir': '/',
                    'Cmd': ['bash'],
                    'Volumes': {'/path': {}},
                    'Entrypoint': None,
                    'ExposedPorts': {},
                    'Labels': {'IMAGE_LABEL': 'image_foo',
                               'LABEL1': 'label1'},
                },
                })
        __salt__ = {'dockerng.list_containers': MagicMock(),
                    'dockerng.list_tags': MagicMock(),
                    'dockerng.pull': MagicMock(),
                    'dockerng.state': MagicMock(),
                    'dockerng.inspect_image': dockerng_inspect_image,
                    'dockerng.create': dockerng_create,
                    }
        with patch.dict(dockerng_state.__dict__,
                        {'__salt__': __salt__}):
            dockerng_state.running(
                'cont',
                image='image:latest',
                labels=[{'LABEL1': 'foo1'}, {'LABEL2': 'foo2'}],
                )
        dockerng_create.assert_called_with(
            'image:latest',
            validate_input=False,
            validate_ip_addrs=False,
            name='cont',
            labels={'LABEL1': 'foo1', 'LABEL2': 'foo2'},
            client_timeout=60)
Exemple #7
0
    def test_repo_noadd_nomod_noref(self):
        '''
        Test mod_repo detects the repo already exists,
        no modification was requested and no refresh requested either

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

        with zypper_patcher:
            self.assertEqual(zypper.mod_repo(name, **{'url': url}),
                             {'comment': 'Specified arguments did not result in modification of repo'})
            zypper.__zypper__.xml.call.assert_not_called()
            zypper.__zypper__.refreshable.xml.call.assert_not_called()
Exemple #8
0
    def test_repo_noadd_nomod_ref(self):
        '''
        Test mod_repo detects the repo already exists,
        has nothing to modify and refreshes the repo with
            `zypper --gpg-auto-import-keys refresh <repo-name>`

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

        with zypper_patcher:
            zypper.mod_repo(name, **{'url': url, 'gpgautoimport': True})
            self.assertEqual(zypper.__zypper__.xml.call.call_args_list,
                             [call('--gpg-auto-import-keys', 'refresh', name)])
            zypper.__zypper__.refreshable.xml.call.assert_not_called()
Exemple #9
0
    def test_device_state_change(self):
        config = {'states': ['offline']}

        out = [
            'List of devices attached\nHTC\tdevice',
            'List of devices attached\nHTC\toffline'
        ]

        mock = Mock(side_effect=out)
        with patch.dict(adb.__salt__, {'cmd.run': mock}):

            ret = adb.beacon(config)
            self.assertEqual(ret, [])

            ret = adb.beacon(config)
            self.assertEqual(ret, [{
                'device': 'HTC',
                'state': 'offline',
                'tag': 'offline'
            }])
Exemple #10
0
    def test_running_compare_images_by_id(self):
        '''
        Make sure the container is running
        against expected image.

        Here the local image is named 'image:latest' and the container
        is also running against an image called 'image:latest'.
        Therefore the image ids are diverging because the tag 'image:latest'
        moved to a fresher image.
        Thus this test make sure the old container is droped and recreated.
        '''
        new_fake_image_id = 'abcdefgh'
        old_fake_image_id = '123456789'
        dockerng_inspect_image = Mock(return_value={'Id': new_fake_image_id})
        dockerng_inspect_container = Mock(
            return_value={'Image': old_fake_image_id,
                          'Config': {'Image': 'image:latest'}})
        dockerng_list_containers = Mock(return_value=['cont'])
        dockerng__state = Mock(return_value='running')
        dockerng_stop = Mock(return_value={'result': True})
        dockerng_rm = Mock(return_value=['container-id'])
        __salt__ = {'dockerng.list_containers': dockerng_list_containers,
                    'dockerng.inspect_container': dockerng_inspect_container,
                    'dockerng.inspect_image': dockerng_inspect_image,
                    'dockerng.list_tags': MagicMock(),
                    'dockerng.state': dockerng__state,
                    'dockerng.pull': MagicMock(return_value=new_fake_image_id),
                    'dockerng.create': MagicMock(return_value='new_container'),
                    'dockerng.start': MagicMock(),
                    'dockerng.stop': dockerng_stop,
                    'dockerng.rm': dockerng_rm,
                    }
        with patch.dict(dockerng_state.__dict__,
                        {'__salt__': __salt__}):
            ret = dockerng_state.running(
                'cont',
                image='image:latest',
                )
            dockerng_stop.assert_called_with('cont', timeout=10, unpause=True)
            dockerng_rm.assert_called_with('cont')
        self.assertEqual(ret, {'name': 'cont',
                               'comment': "Container 'cont' was replaced",
                               'result': True,
                               'changes': {'added': 'new_container',
                                           'image': new_fake_image_id,
                                           'removed': ['container-id']}
                               })
Exemple #11
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)
            client = MagicMock()
            client.api_version = '1.12'
            get_client_mock = MagicMock(return_value=client)

            with patch.dict(
                    dockerng_mod.__salt__, {
                        'mine.send': mine_send,
                        'container_resource.run': MagicMock(),
                        'cp.cache_file': MagicMock(return_value=False)
                    }):
                with patch.object(dockerng_mod, '_get_client',
                                  get_client_mock):
                    with patch.object(dockerng_mod, 'get_client_args',
                                      self.client_args_mock):
                        command('container', *args)
            mine_send.assert_called_with('dockerng.ps',
                                         verbose=True,
                                         all=True,
                                         host=True)
Exemple #12
0
    def test_device_no_repeat_capacity_increase(self):
        config = {'states': ['device'], 'battery_low': 75}

        out = [
            'List of devices attached\nHTC\tdevice', '25',
            'List of devices attached\nHTC\tdevice', '30'
        ]
        mock = Mock(side_effect=out)
        with patch.dict(adb.__salt__, {'cmd.run': mock}):
            ret = adb.beacon(config)
            self.assertEqual(ret, [{
                'device': 'HTC',
                'state': 'device',
                'tag': 'device'
            }, {
                'device': 'HTC',
                'battery_level': 25,
                'tag': 'battery_low'
            }])

            ret = adb.beacon(config)
            self.assertEqual(ret, [])
Exemple #13
0
    def test_no_devices_no_repeat(self):
        config = {'states': ['offline', 'device'], 'no_devices_event': True}

        out = [
            'List of devices attached\nHTC\tdevice',
            'List of devices attached', 'List of devices attached'
        ]

        mock = Mock(side_effect=out)
        with patch.dict(adb.__salt__, {'cmd.run': mock}):

            ret = adb.beacon(config)
            self.assertEqual(ret, [{
                'device': 'HTC',
                'state': 'device',
                'tag': 'device'
            }])

            ret = adb.beacon(config)
            self.assertEqual(ret, [{'tag': 'no_devices'}])

            ret = adb.beacon(config)
            self.assertEqual(ret, [])
Exemple #14
0
    def test_os_environment_remains_intact(self, loads_mock, popen_mock,
                                           getpwnam_mock):
        '''
        Make sure the OS environment is not tainted after running a command
        that specifies runas.
        '''
        environment = os.environ.copy()

        popen_mock.return_value = Mock(
            communicate=lambda *args, **kwags: ['{}', None],
            pid=lambda: 1,
            retcode=0)

        loads_mock.return_value = {'data': {'USER': '******'}}

        from salt.modules import cmdmod

        cmdmod.__grains__ = {'os': 'darwin'}
        if sys.platform.startswith('freebsd'):
            shell = '/bin/sh'
        else:
            shell = '/bin/bash'

        try:
            cmdmod._run('ls',
                        cwd=tempfile.gettempdir(),
                        runas='foobar',
                        shell=shell)

            environment2 = os.environ.copy()

            self.assertEqual(environment, environment2)

            getpwnam_mock.assert_called_with('foobar')
            loads_mock.assert_called_with('{}')
        finally:
            delattr(cmdmod, '__grains__')
Exemple #15
0
 def test_running_with_labels(self):
     '''
     Test dockerng.running with labels parameter.
     '''
     dockerng_create = Mock()
     __salt__ = {
         'dockerng.list_containers': MagicMock(),
         'dockerng.list_tags': MagicMock(),
         'dockerng.pull': MagicMock(),
         'dockerng.state': MagicMock(),
         'dockerng.inspect_image': MagicMock(),
         'dockerng.create': dockerng_create,
     }
     with patch.dict(dockerng_state.__dict__, {'__salt__': __salt__}):
         dockerng_state.running(
             'cont',
             image='image:latest',
             labels=['LABEL1', 'LABEL2'],
         )
     dockerng_create.assert_called_with('image:latest',
                                        validate_input=False,
                                        name='cont',
                                        labels=['LABEL1', 'LABEL2'],
                                        client_timeout=60)
 def make_decryption_mock(self):
     decrypted_data_mock = Mock()
     decrypted_data_mock.ok = True
     decrypted_data_mock.__str__ = lambda x: DECRYPTED_STRING
     return decrypted_data_mock
Exemple #17
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,
                            })
Exemple #18
0
class DockerngTestCase(TestCase):
    '''
    Validate dockerng module
    '''
    def setUp(self):
        '''
        Ensure we aren't persisting context dunders between tests
        '''
        dockerng_mod.__context__ = {'docker.docker_version': ''}

    try:
        docker_version = dockerng_mod.docker.version_info
    except AttributeError:
        docker_version = 0,

    client_args_mock = MagicMock(
        return_value={
            'create_container': [
                'image', 'command', 'hostname', 'user', 'detach', 'stdin_open',
                'tty', 'ports', 'environment', 'volumes', 'network_disabled',
                'name', 'entrypoint', 'working_dir', 'domainname', 'cpuset',
                'host_config', 'mac_address', 'labels', 'volume_driver',
                'stop_signal', 'networking_config', 'healthcheck',
                'stop_timeout'
            ],
            'host_config': [
                'binds', 'port_bindings', 'lxc_conf', 'publish_all_ports',
                'links', 'privileged', 'dns', 'dns_search', 'volumes_from',
                'network_mode', 'restart_policy', 'cap_add', 'cap_drop',
                'devices', 'extra_hosts', 'read_only', 'pid_mode', 'ipc_mode',
                'security_opt', 'ulimits', 'log_config', 'mem_limit',
                'memswap_limit', 'mem_reservation', 'kernel_memory',
                'mem_swappiness', 'cgroup_parent', 'group_add', 'cpu_quota',
                'cpu_period', 'blkio_weight', 'blkio_weight_device',
                'device_read_bps', 'device_write_bps', 'device_read_iops',
                'device_write_iops', 'oom_kill_disable', 'shm_size', 'sysctls',
                'tmpfs', 'oom_score_adj', 'dns_opt', 'cpu_shares',
                'cpuset_cpus', 'userns_mode', 'pids_limit', 'isolation',
                'auto_remove', 'storage_opt'
            ],
            'networking_config': [
                'aliases', 'links', 'ipv4_address', 'ipv6_address',
                'link_local_ips'
            ],
        })

    def test_ps_with_host_true(self):
        '''
        Check that dockerng.ps called with host is ``True``,
        include resutlt of ``network.interfaces`` command in returned result.
        '''
        client = Mock()
        client.containers = MagicMock(return_value=[])
        get_client_mock = MagicMock(return_value=client)

        network_interfaces = Mock(return_value={'mocked': None})
        with patch.dict(dockerng_mod.__salt__,
                        {'network.interfaces': network_interfaces}):
            with patch.object(dockerng_mod, '_get_client', get_client_mock):
                ret = dockerng_mod.ps_(host=True)
                self.assertEqual(ret,
                                 {'host': {
                                     'interfaces': {
                                         'mocked': None
                                     }
                                 }})

    def test_ps_with_filters(self):
        '''
        Check that dockerng.ps accept filters parameter.
        '''
        client = Mock()
        client.containers = MagicMock(return_value=[])
        get_client_mock = MagicMock(return_value=client)

        with patch.object(dockerng_mod, '_get_client', get_client_mock):
            dockerng_mod.ps_(filters={'label': 'KEY'})
            client.containers.assert_called_once_with(all=True,
                                                      filters={'label': 'KEY'})

    @patch.object(dockerng_mod, '_get_exec_driver')
    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)
            client = MagicMock()
            client.api_version = '1.12'
            get_client_mock = MagicMock(return_value=client)

            with patch.dict(
                    dockerng_mod.__salt__, {
                        'mine.send': mine_send,
                        'container_resource.run': MagicMock(),
                        'cp.cache_file': MagicMock(return_value=False)
                    }):
                with patch.object(dockerng_mod, '_get_client',
                                  get_client_mock):
                    with patch.object(dockerng_mod, 'get_client_args',
                                      self.client_args_mock):
                        command('container', *args)
            mine_send.assert_called_with('dockerng.ps',
                                         verbose=True,
                                         all=True,
                                         host=True)

    @skipIf(docker_version < (
        1, 4, 0
    ), 'docker module must be installed to run this test or is too old. >=1.4.0'
            )
    @patch.object(dockerng_mod, 'images', MagicMock())
    @patch.object(dockerng_mod, 'inspect_image')
    @patch.object(dockerng_mod, 'version',
                  Mock(return_value={'ApiVersion': '1.19'}))
    def test_create_with_arg_cmd(self, *args):
        '''
        When cmd argument is passed check it is renamed to command.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
        }
        host_config = {}
        client = Mock()
        client.api_version = '1.19'
        client.create_host_config.return_value = host_config
        client.create_container.return_value = {}
        get_client_mock = MagicMock(return_value=client)

        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.object(dockerng_mod, '_get_client', get_client_mock):
                with patch.object(dockerng_mod, 'get_client_args',
                                  self.client_args_mock):
                    dockerng_mod.create('image', cmd='ls', name='ctn')
        client.create_container.assert_called_once_with(
            command='ls', host_config=host_config, image='image', name='ctn')

    @skipIf(docker_version < (
        1, 4, 0
    ), 'docker module must be installed to run this test or is too old. >=1.4.0'
            )
    @patch.object(dockerng_mod, 'images', MagicMock())
    @patch.object(dockerng_mod, 'inspect_image')
    @patch.object(dockerng_mod, 'version',
                  Mock(return_value={'ApiVersion': '1.19'}))
    def test_create_send_host_config(self, *args):
        '''
        Check host_config object is passed to create_container.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
        }
        host_config = {'PublishAllPorts': True}
        client = Mock()
        client.api_version = '1.19'
        client.create_host_config.return_value = host_config
        client.create_container.return_value = {}
        get_client_mock = MagicMock(return_value=client)

        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.object(dockerng_mod, '_get_client', get_client_mock):
                with patch.object(dockerng_mod, 'get_client_args',
                                  self.client_args_mock):
                    dockerng_mod.create('image',
                                        name='ctn',
                                        publish_all_ports=True)
        client.create_container.assert_called_once_with(
            host_config=host_config, image='image', name='ctn')

    @skipIf(docker_version < (
        1, 4, 0
    ), 'docker module must be installed to run this test or is too old. >=1.4.0'
            )
    @patch.object(dockerng_mod, 'images', MagicMock())
    @patch.object(dockerng_mod, 'inspect_image')
    @patch.object(dockerng_mod, 'version',
                  Mock(return_value={'ApiVersion': '1.19'}))
    def test_create_with_labels_dict(self, *args):
        '''
        Create container with labels dictionary.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
            'dockerng.version': MagicMock(return_value={}),
        }
        host_config = {}
        client = Mock()
        client.api_version = '1.19'
        client.create_host_config.return_value = host_config
        client.create_container.return_value = {}
        get_client_mock = MagicMock(return_value=client)

        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.object(dockerng_mod, '_get_client', get_client_mock):
                with patch.object(dockerng_mod, 'get_client_args',
                                  self.client_args_mock):
                    dockerng_mod.create(
                        'image',
                        name='ctn',
                        labels={'KEY': 'VALUE'},
                        validate_input=True,
                    )
        client.create_container.assert_called_once_with(
            labels={'KEY': 'VALUE'},
            host_config=host_config,
            image='image',
            name='ctn',
        )

    @skipIf(docker_version < (
        1, 4, 0
    ), 'docker module must be installed to run this test or is too old. >=1.4.0'
            )
    @patch.object(dockerng_mod, 'images', MagicMock())
    @patch.object(dockerng_mod, 'inspect_image')
    @patch.object(dockerng_mod, 'version',
                  Mock(return_value={'ApiVersion': '1.19'}))
    def test_create_with_labels_list(self, *args):
        '''
        Create container with labels list.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
            'dockerng.version': MagicMock(return_value={}),
        }
        host_config = {}
        client = Mock()
        client.api_version = '1.19'
        client.create_host_config.return_value = host_config
        client.create_container.return_value = {}
        get_client_mock = MagicMock(return_value=client)
        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.object(dockerng_mod, '_get_client', get_client_mock):
                with patch.object(dockerng_mod, 'get_client_args',
                                  self.client_args_mock):
                    dockerng_mod.create(
                        'image',
                        name='ctn',
                        labels=['KEY1', 'KEY2'],
                        validate_input=True,
                    )
        client.create_container.assert_called_once_with(
            labels=['KEY1', 'KEY2'],
            host_config=host_config,
            image='image',
            name='ctn',
        )

    @skipIf(docker_version < (
        1, 4, 0
    ), 'docker module must be installed to run this test or is too old. >=1.4.0'
            )
    @patch.object(dockerng_mod, 'images', MagicMock())
    @patch.object(dockerng_mod, 'inspect_image')
    @patch.object(dockerng_mod, 'version',
                  Mock(return_value={'ApiVersion': '1.19'}))
    def test_create_with_labels_error(self, *args):
        '''
        Create container with invalid labels.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
            'dockerng.version': MagicMock(return_value={}),
        }
        host_config = {}
        client = Mock()
        client.api_version = '1.19'
        client.create_host_config.return_value = host_config
        client.create_container.return_value = {}
        get_client_mock = MagicMock(return_value=client)

        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.object(dockerng_mod, '_get_client', get_client_mock):
                with patch.object(dockerng_mod, 'get_client_args',
                                  self.client_args_mock):
                    self.assertRaises(
                        SaltInvocationError,
                        dockerng_mod.create,
                        'image',
                        name='ctn',
                        labels=22,
                        validate_input=True,
                    )

    @skipIf(docker_version < (
        1, 4, 0
    ), 'docker module must be installed to run this test or is too old. >=1.4.0'
            )
    @patch.object(dockerng_mod, 'images', MagicMock())
    @patch.object(dockerng_mod, 'inspect_image')
    @patch.object(dockerng_mod, 'version',
                  Mock(return_value={'ApiVersion': '1.19'}))
    def test_create_with_labels_dictlist(self, *args):
        '''
        Create container with labels dictlist.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
            'dockerng.version': MagicMock(return_value={}),
        }
        host_config = {}
        client = Mock()
        client.api_version = '1.19'
        client.create_host_config.return_value = host_config
        client.create_container.return_value = {}
        get_client_mock = MagicMock(return_value=client)

        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.object(dockerng_mod, '_get_client', get_client_mock):
                with patch.object(dockerng_mod, 'get_client_args',
                                  self.client_args_mock):
                    dockerng_mod.create(
                        'image',
                        name='ctn',
                        labels=[{
                            'KEY1': 'VALUE1'
                        }, {
                            'KEY2': 'VALUE2'
                        }],
                        validate_input=True,
                    )
        client.create_container.assert_called_once_with(
            labels={
                'KEY1': 'VALUE1',
                'KEY2': 'VALUE2'
            },
            host_config=host_config,
            image='image',
            name='ctn',
        )

    @skipIf(docker_version < (
        1, 5, 0
    ), 'docker module must be installed to run this test or is too old. >=1.5.0'
            )
    @patch('salt.modules.dockerng._get_docker_py_versioninfo',
           MagicMock(return_value=docker_version))
    def test_list_networks(self, *args):
        '''
        test list networks.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
        }
        host_config = {}
        client = Mock()
        client.api_version = '1.21'
        get_client_mock = MagicMock(return_value=client)

        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.object(dockerng_mod, '_get_client', get_client_mock):
                dockerng_mod.networks(
                    names=['foo'],
                    ids=['01234'],
                )
        client.networks.assert_called_once_with(
            names=['foo'],
            ids=['01234'],
        )

    @skipIf(docker_version < (
        1, 5, 0
    ), 'docker module must be installed to run this test or is too old. >=1.5.0'
            )
    @patch('salt.modules.dockerng._get_docker_py_versioninfo',
           MagicMock(return_value=docker_version))
    def test_create_network(self, *args):
        '''
        test create network.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
        }
        host_config = {}
        client = Mock()
        client.api_version = '1.21'
        get_client_mock = MagicMock(return_value=client)

        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.object(dockerng_mod, '_get_client', get_client_mock):
                dockerng_mod.create_network('foo', driver='bridge')
        client.create_network.assert_called_once_with('foo', driver='bridge')

    @skipIf(docker_version < (
        1, 5, 0
    ), 'docker module must be installed to run this test or is too old. >=1.5.0'
            )
    @patch('salt.modules.dockerng._get_docker_py_versioninfo',
           MagicMock(return_value=docker_version))
    def test_remove_network(self, *args):
        '''
        test remove network.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
        }
        host_config = {}
        client = Mock()
        client.api_version = '1.21'
        get_client_mock = MagicMock(return_value=client)

        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.object(dockerng_mod, '_get_client', get_client_mock):
                dockerng_mod.remove_network('foo')
        client.remove_network.assert_called_once_with('foo')

    @skipIf(docker_version < (
        1, 5, 0
    ), 'docker module must be installed to run this test or is too old. >=1.5.0'
            )
    @patch('salt.modules.dockerng._get_docker_py_versioninfo',
           MagicMock(return_value=docker_version))
    def test_inspect_network(self, *args):
        '''
        test inspect network.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
        }
        host_config = {}
        client = Mock()
        client.api_version = '1.21'
        get_client_mock = MagicMock(return_value=client)

        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.object(dockerng_mod, '_get_client', get_client_mock):
                dockerng_mod.inspect_network('foo')
        client.inspect_network.assert_called_once_with('foo')

    @skipIf(docker_version < (
        1, 5, 0
    ), 'docker module must be installed to run this test or is too old. >=1.5.0'
            )
    @patch('salt.modules.dockerng._get_docker_py_versioninfo',
           MagicMock(return_value=docker_version))
    def test_connect_container_to_network(self, *args):
        '''
        test inspect network.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
        }
        host_config = {}
        client = Mock()
        client.api_version = '1.21'
        get_client_mock = MagicMock(return_value=client)

        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.object(dockerng_mod, '_get_client', get_client_mock):
                dockerng_mod.connect_container_to_network('container', 'foo')
        client.connect_container_to_network.assert_called_once_with(
            'container', 'foo')

    @skipIf(docker_version < (
        1, 5, 0
    ), 'docker module must be installed to run this test or is too old. >=1.5.0'
            )
    @patch('salt.modules.dockerng._get_docker_py_versioninfo',
           MagicMock(return_value=docker_version))
    def test_disconnect_container_from_network(self, *args):
        '''
        test inspect network.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
        }
        host_config = {}
        client = Mock()
        client.api_version = '1.21'
        get_client_mock = MagicMock(return_value=client)

        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.object(dockerng_mod, '_get_client', get_client_mock):
                dockerng_mod.disconnect_container_from_network(
                    'container', 'foo')
        client.disconnect_container_from_network.assert_called_once_with(
            'container', 'foo')

    @skipIf(docker_version < (
        1, 5, 0
    ), 'docker module must be installed to run this test or is too old. >=1.5.0'
            )
    @patch('salt.modules.dockerng._get_docker_py_versioninfo',
           MagicMock(return_value=docker_version))
    def test_list_volumes(self, *args):
        '''
        test list volumes.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
        }
        client = Mock()
        client.api_version = '1.21'
        get_client_mock = MagicMock(return_value=client)

        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.object(dockerng_mod, '_get_client', get_client_mock):
                dockerng_mod.volumes(filters={'dangling': [True]})
        client.volumes.assert_called_once_with(filters={'dangling': [True]})

    @skipIf(docker_version < (
        1, 5, 0
    ), 'docker module must be installed to run this test or is too old. >=1.5.0'
            )
    @patch('salt.modules.dockerng._get_docker_py_versioninfo',
           MagicMock(return_value=docker_version))
    def test_create_volume(self, *args):
        '''
        test create volume.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
        }
        client = Mock()
        client.api_version = '1.21'
        get_client_mock = MagicMock(return_value=client)

        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.object(dockerng_mod, '_get_client', get_client_mock):
                dockerng_mod.create_volume(
                    'foo',
                    driver='bridge',
                    driver_opts={},
                )
        client.create_volume.assert_called_once_with(
            'foo',
            driver='bridge',
            driver_opts={},
        )

    @skipIf(docker_version < (
        1, 5, 0
    ), 'docker module must be installed to run this test or is too old. >=1.5.0'
            )
    @patch('salt.modules.dockerng._get_docker_py_versioninfo',
           MagicMock(return_value=docker_version))
    def test_remove_volume(self, *args):
        '''
        test remove volume.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
        }
        client = Mock()
        client.api_version = '1.21'
        get_client_mock = MagicMock(return_value=client)

        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.object(dockerng_mod, '_get_client', get_client_mock):
                dockerng_mod.remove_volume('foo')
        client.remove_volume.assert_called_once_with('foo')

    @skipIf(docker_version < (
        1, 5, 0
    ), 'docker module must be installed to run this test or is too old. >=1.5.0'
            )
    @patch('salt.modules.dockerng._get_docker_py_versioninfo',
           MagicMock(return_value=docker_version))
    def test_inspect_volume(self, *args):
        '''
        test inspect volume.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
        }
        client = Mock()
        client.api_version = '1.21'
        get_client_mock = MagicMock(return_value=client)

        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.object(dockerng_mod, '_get_client', get_client_mock):
                dockerng_mod.inspect_volume('foo')
        client.inspect_volume.assert_called_once_with('foo')

    def test_wait_success(self):
        client = Mock()
        client.api_version = '1.21'
        client.wait = Mock(return_value=0)
        get_client_mock = MagicMock(return_value=client)

        dockerng_inspect_container = Mock(side_effect=[{
            'State': {
                'Running': True
            }
        }, {
            'State': {
                'Stopped': True
            }
        }])
        with patch.object(dockerng_mod, 'inspect_container',
                          dockerng_inspect_container):
            with patch.object(dockerng_mod, '_get_client', get_client_mock):
                dockerng_mod._clear_context()
                result = dockerng_mod.wait('foo')
        self.assertEqual(
            result, {
                'result': True,
                'exit_status': 0,
                'state': {
                    'new': 'stopped',
                    'old': 'running'
                }
            })

    def test_wait_fails_already_stopped(self):
        client = Mock()
        client.api_version = '1.21'
        client.wait = Mock(return_value=0)
        get_client_mock = MagicMock(return_value=client)

        dockerng_inspect_container = Mock(side_effect=[
            {
                'State': {
                    'Stopped': True
                }
            },
            {
                'State': {
                    'Stopped': True
                }
            },
        ])
        with patch.object(dockerng_mod, 'inspect_container',
                          dockerng_inspect_container):
            with patch.object(dockerng_mod, '_get_client', get_client_mock):
                dockerng_mod._clear_context()
                result = dockerng_mod.wait('foo')
        self.assertEqual(
            result, {
                'result': False,
                'comment': "Container 'foo' already stopped",
                'exit_status': 0,
                'state': {
                    'new': 'stopped',
                    'old': 'stopped'
                }
            })

    def test_wait_success_already_stopped(self):
        client = Mock()
        client.api_version = '1.21'
        client.wait = Mock(return_value=0)
        get_client_mock = MagicMock(return_value=client)

        dockerng_inspect_container = Mock(side_effect=[
            {
                'State': {
                    'Stopped': True
                }
            },
            {
                'State': {
                    'Stopped': True
                }
            },
        ])
        with patch.object(dockerng_mod, 'inspect_container',
                          dockerng_inspect_container):
            with patch.object(dockerng_mod, '_get_client', get_client_mock):
                dockerng_mod._clear_context()
                result = dockerng_mod.wait('foo', ignore_already_stopped=True)
        self.assertEqual(
            result, {
                'result': True,
                'comment': "Container 'foo' already stopped",
                'exit_status': 0,
                'state': {
                    'new': 'stopped',
                    'old': 'stopped'
                }
            })

    def test_wait_success_absent_container(self):
        client = Mock()
        client.api_version = '1.21'
        get_client_mock = MagicMock(return_value=client)
        dockerng_inspect_container = Mock(side_effect=CommandExecutionError)

        with patch.object(dockerng_mod, 'inspect_container',
                          dockerng_inspect_container):
            with patch.object(dockerng_mod, '_get_client', get_client_mock):
                dockerng_mod._clear_context()
                result = dockerng_mod.wait('foo', ignore_already_stopped=True)
        self.assertEqual(result, {
            'result': True,
            'comment': "Container 'foo' absent"
        })

    def test_wait_fails_on_exit_status(self):
        client = Mock()
        client.api_version = '1.21'
        client.wait = Mock(return_value=1)
        get_client_mock = MagicMock(return_value=client)
        dockerng_inspect_container = Mock(side_effect=[{
            'State': {
                'Running': True
            }
        }, {
            'State': {
                'Stopped': True
            }
        }])

        with patch.object(dockerng_mod, 'inspect_container',
                          dockerng_inspect_container):
            with patch.object(dockerng_mod, '_get_client', get_client_mock):
                dockerng_mod._clear_context()
                result = dockerng_mod.wait('foo', fail_on_exit_status=True)
        self.assertEqual(
            result, {
                'result': False,
                'exit_status': 1,
                'state': {
                    'new': 'stopped',
                    'old': 'running'
                }
            })

    def test_wait_fails_on_exit_status_and_already_stopped(self):
        client = Mock()
        client.api_version = '1.21'
        client.wait = Mock(return_value=1)
        get_client_mock = MagicMock(return_value=client)
        dockerng_inspect_container = Mock(side_effect=[{
            'State': {
                'Stopped': True
            }
        }, {
            'State': {
                'Stopped': True
            }
        }])

        with patch.object(dockerng_mod, 'inspect_container',
                          dockerng_inspect_container):
            with patch.object(dockerng_mod, '_get_client', get_client_mock):
                dockerng_mod._clear_context()
                result = dockerng_mod.wait('foo',
                                           ignore_already_stopped=True,
                                           fail_on_exit_status=True)
        self.assertEqual(
            result, {
                'result': False,
                'comment': "Container 'foo' already stopped",
                'exit_status': 1,
                'state': {
                    'new': 'stopped',
                    'old': 'stopped'
                }
            })

    def test_sls_build(self, *args):
        '''
        test build sls image.
        '''
        docker_start_mock = MagicMock(return_value={})
        docker_create_mock = MagicMock(return_value={
            'Id': 'ID',
            'Name': 'NAME'
        })
        docker_stop_mock = MagicMock(return_value={
            'state': {
                'old': 'running',
                'new': 'stopped'
            },
            'result': True
        })
        docker_commit_mock = MagicMock(return_value={
            'Id': 'ID2',
            'Image': 'foo',
            'Time_Elapsed': 42
        })

        docker_sls_mock = MagicMock(
            return_value={
                "file_|-/etc/test.sh_|-/etc/test.sh_|-managed": {
                    "comment": "File /etc/test.sh is in the correct state",
                    "name": "/etc/test.sh",
                    "start_time": "07:04:26.834792",
                    "result": True,
                    "duration": 13.492,
                    "__run_num__": 0,
                    "changes": {}
                },
                "test_|-always-passes_|-foo_|-succeed_without_changes": {
                    "comment": "Success!",
                    "name": "foo",
                    "start_time": "07:04:26.848915",
                    "result": True,
                    "duration": 0.363,
                    "__run_num__": 1,
                    "changes": {}
                }
            })

        ret = None
        with patch.dict(
                dockerng_mod.__salt__, {
                    'dockerng.start': docker_start_mock,
                    'dockerng.create': docker_create_mock,
                    'dockerng.stop': docker_stop_mock,
                    'dockerng.commit': docker_commit_mock,
                    'dockerng.sls': docker_sls_mock
                }):
            ret = dockerng_mod.sls_build(
                'foo',
                mods='foo',
            )
        docker_create_mock.assert_called_once_with(cmd='sleep infinity',
                                                   image='opensuse/python',
                                                   interactive=True,
                                                   name='foo',
                                                   tty=True)
        docker_start_mock.assert_called_once_with('ID')
        docker_sls_mock.assert_called_once_with('ID', 'foo', 'base')
        docker_stop_mock.assert_called_once_with('ID')
        docker_commit_mock.assert_called_once_with('ID', 'foo')
        self.assertEqual({
            'Id': 'ID2',
            'Image': 'foo',
            'Time_Elapsed': 42
        }, ret)

    def test_sls_build_dryrun(self, *args):
        '''
        test build sls image in dryrun mode.
        '''
        docker_start_mock = MagicMock(return_value={})
        docker_create_mock = MagicMock(return_value={
            'Id': 'ID',
            'Name': 'NAME'
        })
        docker_stop_mock = MagicMock(return_value={
            'state': {
                'old': 'running',
                'new': 'stopped'
            },
            'result': True
        })
        docker_rm_mock = MagicMock(return_value={})

        docker_sls_mock = MagicMock(
            return_value={
                "file_|-/etc/test.sh_|-/etc/test.sh_|-managed": {
                    "comment": "File /etc/test.sh is in the correct state",
                    "name": "/etc/test.sh",
                    "start_time": "07:04:26.834792",
                    "result": True,
                    "duration": 13.492,
                    "__run_num__": 0,
                    "changes": {}
                },
                "test_|-always-passes_|-foo_|-succeed_without_changes": {
                    "comment": "Success!",
                    "name": "foo",
                    "start_time": "07:04:26.848915",
                    "result": True,
                    "duration": 0.363,
                    "__run_num__": 1,
                    "changes": {}
                }
            })

        ret = None
        with patch.dict(
                dockerng_mod.__salt__, {
                    'dockerng.start': docker_start_mock,
                    'dockerng.create': docker_create_mock,
                    'dockerng.stop': docker_stop_mock,
                    'dockerng.rm': docker_rm_mock,
                    'dockerng.sls': docker_sls_mock
                }):
            ret = dockerng_mod.sls_build('foo', mods='foo', dryrun=True)
        docker_create_mock.assert_called_once_with(cmd='sleep infinity',
                                                   image='opensuse/python',
                                                   interactive=True,
                                                   name='foo',
                                                   tty=True)
        docker_start_mock.assert_called_once_with('ID')
        docker_sls_mock.assert_called_once_with('ID', 'foo', 'base')
        docker_stop_mock.assert_called_once_with('ID')
        docker_rm_mock.assert_called_once_with('ID')
        self.assertEqual(
            {
                "file_|-/etc/test.sh_|-/etc/test.sh_|-managed": {
                    "comment": "File /etc/test.sh is in the correct state",
                    "name": "/etc/test.sh",
                    "start_time": "07:04:26.834792",
                    "result": True,
                    "duration": 13.492,
                    "__run_num__": 0,
                    "changes": {}
                },
                "test_|-always-passes_|-foo_|-succeed_without_changes": {
                    "comment": "Success!",
                    "name": "foo",
                    "start_time": "07:04:26.848915",
                    "result": True,
                    "duration": 0.363,
                    "__run_num__": 1,
                    "changes": {}
                }
            }, ret)

    def test_call_success(self):
        '''
        test module calling inside containers
        '''
        docker_run_all_mock = MagicMock(
            return_value={
                'retcode': 0,
                'stdout': '{"retcode": 0, "comment": "container cmd"}',
                'stderr': 'err',
            })
        docker_copy_to_mock = MagicMock(return_value={'retcode': 0})
        docker_config_mock = MagicMock(return_value='')
        client = Mock()
        client.put_archive = Mock()

        with nested(
                patch.dict(dockerng_mod.__opts__, {'cachedir': '/tmp'}),
                patch.dict(
                    dockerng_mod.__salt__, {
                        'dockerng.run_all': docker_run_all_mock,
                        'dockerng.copy_to': docker_copy_to_mock,
                        'config.option': docker_config_mock
                    }),
                patch.dict(dockerng_mod.__context__,
                           {'docker.client': client})):
            # call twice to verify tmp path later
            for i in range(2):
                ret = dockerng_mod.call('ID', 'test.arg', 1, 2, arg1='val1')

        # Check that the directory is different each time
        # [ call(name, [args]), ...
        self.assertIn('mkdir', docker_run_all_mock.mock_calls[0][1][1])
        self.assertIn('mkdir', docker_run_all_mock.mock_calls[3][1][1])
        self.assertNotEqual(docker_run_all_mock.mock_calls[0][1][1],
                            docker_run_all_mock.mock_calls[3][1][1])

        self.assertIn('salt-call', docker_run_all_mock.mock_calls[1][1][1])
        self.assertIn('salt-call', docker_run_all_mock.mock_calls[4][1][1])
        self.assertNotEqual(docker_run_all_mock.mock_calls[1][1][1],
                            docker_run_all_mock.mock_calls[4][1][1])

        # check directory cleanup
        self.assertIn('rm -rf', docker_run_all_mock.mock_calls[2][1][1])
        self.assertIn('rm -rf', docker_run_all_mock.mock_calls[5][1][1])
        self.assertNotEqual(docker_run_all_mock.mock_calls[2][1][1],
                            docker_run_all_mock.mock_calls[5][1][1])

        self.assertEqual({"retcode": 0, "comment": "container cmd"}, ret)

    def test_images_with_empty_tags(self):
        """
        docker 1.12 reports also images without tags with `null`.
        """
        client = Mock()
        client.api_version = '1.24'
        client.images = Mock(return_value=[{
            'Id': 'sha256:abcde',
            'RepoTags': None
        }, {
            'Id': 'sha256:abcdef'
        }, {
            'Id': 'sha256:abcdefg',
            'RepoTags': ['image:latest']
        }])
        get_client_mock = MagicMock(return_value=client)

        with patch.object(dockerng_mod, '_get_client', get_client_mock):
            dockerng_mod._clear_context()
            result = dockerng_mod.images()
        self.assertEqual(result,
                         {'sha256:abcdefg': {
                             'RepoTags': ['image:latest']
                         }})
Exemple #19
0
server accepts handled requests
 46756 46756 89318
Reading: 0 Writing: 7 Waiting: 0"""


class MockUrllibStatus(object):
    """Mock of urllib2 call for Nginx status"""
    def read(self):
        return MOCK_STATUS_OUTPUT

    def close(self):
        pass


@skipIf(NO_MOCK, NO_MOCK_REASON)
@patch('salt.utils.which', Mock(return_value='/usr/bin/nginx'))
class NginxTestCase(TestCase):
    @patch('salt.modules.nginx._urlopen',
           Mock(return_value=MockUrllibStatus()))
    def test_nginx_status(self):
        result = nginx.status()
        nginx._urlopen.assert_called_once_with('http://127.0.0.1/status')
        self.assertEqual(
            result, {
                'active connections': 7,
                'accepted': 46756,
                'handled': 46756,
                'requests': 89318,
                'reading': 0,
                'writing': 7,
                'waiting': 0,
Exemple #20
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(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(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)
Exemple #21
0
    def test_volume_present(self):
        '''
        Test dockerng.volume_present
        '''
        volumes = []
        default_driver = 'dummy_default'

        def create_volume(name, driver=None, driver_opts=None):
            for v in volumes:
                # volume_present should never try to add a conflicting
                # volume
                self.assertNotEqual(v['Name'], name)
            if driver is None:
                driver = default_driver
            new = {'Name': name, 'Driver': driver}
            volumes.append(new)
            return new

        def remove_volume(name):
            old_len = len(volumes)
            removed = [v for v in volumes if v['Name'] == name]
            # volume_present should not have tried to remove a volume
            # that didn't exist
            self.assertEqual(1, len(removed))
            volumes.remove(removed[0])
            return removed[0]

        dockerng_create_volume = Mock(side_effect=create_volume)
        __salt__ = {'dockerng.create_volume': dockerng_create_volume,
                    'dockerng.volumes': Mock(return_value={'Volumes': volumes}),
                    'dockerng.remove_volume': Mock(side_effect=remove_volume),
                    }
        with patch.dict(dockerng_state.__dict__,
                        {'__salt__': __salt__}):
            ret = dockerng_state.volume_present(
                'volume_foo',
                )
            dockerng_create_volume.assert_called_with('volume_foo',
                                                      driver=None,
                                                      driver_opts=None)
            self.assertEqual(
                {
                    'name': 'volume_foo',
                    'comment': '',
                    'changes': {
                        'created': {
                            'Driver': default_driver,
                            'Name': 'volume_foo',
                        },
                    },
                    'result': True,
                },
                ret)
            self.assertEqual(len(volumes), 1)
            self.assertEqual(volumes[0]['Name'], 'volume_foo')
            self.assertIs(volumes[0]['Driver'], default_driver)

            # run it again with the same arguments
            orig_volumes = [volumes[0].copy()]
            ret = dockerng_state.volume_present('volume_foo')
            self.assertEqual(
                {
                    'name': 'volume_foo',
                    'comment': "Volume 'volume_foo' already exists.",
                    'changes': {},
                    'result': True,
                },
                ret)
            self.assertEqual(orig_volumes, volumes)

            # run it again with a different driver but don't force
            ret = dockerng_state.volume_present('volume_foo', driver='local')
            self.assertEqual(
                {
                    'name': 'volume_foo',
                    'comment': ("Driver for existing volume 'volume_foo'"
                                " ('dummy_default') does not match specified"
                                " driver ('local') and force is False"),
                    'changes': {},
                    'result': False,
                },
                ret)
            self.assertEqual(orig_volumes, volumes)

            # run it again with a different driver and force
            ret = dockerng_state.volume_present(
                'volume_foo', driver='local', force=True)
            self.assertEqual(
                {
                    'name': 'volume_foo',
                    'comment': "",
                    'changes': {
                        'removed': {
                            'Driver': default_driver,
                            'Name': 'volume_foo',
                        },
                        'created': {
                            'Driver': 'local',
                            'Name': 'volume_foo',
                        },
                    },
                    'result': True,
                },
                ret)
            mod_orig_volumes = [orig_volumes[0].copy()]
            mod_orig_volumes[0]['Driver'] = 'local'
            self.assertEqual(mod_orig_volumes, volumes)
Exemple #22
0
class DockerngTestCase(TestCase):
    '''
    Validate dockerng module
    '''
    def test_ps_with_host_true(self):
        '''
        Check that dockerng.ps called with host is ``True``,
        include resutlt of ``network.interfaces`` command in returned result.
        '''
        network_interfaces = Mock(return_value={'mocked': None})
        with patch.dict(dockerng_mod.__salt__,
                        {'network.interfaces': network_interfaces}):
            with patch.dict(dockerng_mod.__context__,
                            {'docker.client': MagicMock()}):
                ret = dockerng_mod.ps_(host=True)
                self.assertEqual(ret,
                                 {'host': {
                                     'interfaces': {
                                         'mocked': None
                                     }
                                 }})

    def test_ps_with_filters(self):
        '''
        Check that dockerng.ps accept filters parameter.
        '''
        client = MagicMock()
        with patch.dict(dockerng_mod.__context__, {'docker.client': client}):
            dockerng_mod.ps_(filters={'label': 'KEY'})
            client.containers.assert_called_once_with(all=True,
                                                      filters={'label': 'KEY'})

    @patch.object(dockerng_mod, '_get_exec_driver')
    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)

    @skipIf(_docker_py_version() < (
        1, 4, 0
    ), 'docker module must be installed to run this test or is too old. >=1.4.0'
            )
    @patch.object(dockerng_mod, 'images', MagicMock())
    @patch.object(dockerng_mod, 'inspect_image')
    @patch.object(dockerng_mod, 'version',
                  Mock(return_value={'ApiVersion': '1.19'}))
    def test_create_with_arg_cmd(self, *args):
        '''
        When cmd argument is passed check it is renamed to command.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
        }
        host_config = {}
        client = Mock()
        client.api_version = '1.19'
        client.create_host_config.return_value = host_config
        client.create_container.return_value = {}
        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.dict(dockerng_mod.__context__,
                            {'docker.client': client}):
                dockerng_mod.create('image', cmd='ls', name='ctn')
        client.create_container.assert_called_once_with(
            command='ls', host_config=host_config, image='image', name='ctn')

    @skipIf(_docker_py_version() < (
        1, 4, 0
    ), 'docker module must be installed to run this test or is too old. >=1.4.0'
            )
    @patch.object(dockerng_mod, 'images', MagicMock())
    @patch.object(dockerng_mod, 'inspect_image')
    @patch.object(dockerng_mod, 'version',
                  Mock(return_value={'ApiVersion': '1.19'}))
    def test_create_send_host_config(self, *args):
        '''
        Check host_config object is passed to create_container.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
        }
        host_config = {'PublishAllPorts': True}
        client = Mock()
        client.api_version = '1.19'
        client.create_host_config.return_value = host_config
        client.create_container.return_value = {}
        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.dict(dockerng_mod.__context__,
                            {'docker.client': client}):
                dockerng_mod.create('image',
                                    name='ctn',
                                    publish_all_ports=True)
        client.create_container.assert_called_once_with(
            host_config=host_config, image='image', name='ctn')

    @skipIf(_docker_py_version() < (
        1, 4, 0
    ), 'docker module must be installed to run this test or is too old. >=1.4.0'
            )
    @patch.object(dockerng_mod, 'images', MagicMock())
    @patch.object(dockerng_mod, 'inspect_image')
    @patch.object(dockerng_mod, 'version',
                  Mock(return_value={'ApiVersion': '1.19'}))
    def test_create_with_labels_dict(self, *args):
        '''
        Create container with labels dictionary.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
        }
        host_config = {}
        client = Mock()
        client.api_version = '1.19'
        client.create_host_config.return_value = host_config
        client.create_container.return_value = {}
        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.dict(dockerng_mod.__context__,
                            {'docker.client': client}):
                dockerng_mod.create(
                    'image',
                    name='ctn',
                    labels={'KEY': 'VALUE'},
                    validate_input=True,
                )
        client.create_container.assert_called_once_with(
            labels={'KEY': 'VALUE'},
            host_config=host_config,
            image='image',
            name='ctn',
        )

    @skipIf(_docker_py_version() < (
        1, 4, 0
    ), 'docker module must be installed to run this test or is too old. >=1.4.0'
            )
    @patch.object(dockerng_mod, 'images', MagicMock())
    @patch.object(dockerng_mod, 'inspect_image')
    @patch.object(dockerng_mod, 'version',
                  Mock(return_value={'ApiVersion': '1.19'}))
    def test_create_with_labels_list(self, *args):
        '''
        Create container with labels list.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
        }
        host_config = {}
        client = Mock()
        client.api_version = '1.19'
        client.create_host_config.return_value = host_config
        client.create_container.return_value = {}
        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.dict(dockerng_mod.__context__,
                            {'docker.client': client}):
                dockerng_mod.create(
                    'image',
                    name='ctn',
                    labels=['KEY1', 'KEY2'],
                    validate_input=True,
                )
        client.create_container.assert_called_once_with(
            labels=['KEY1', 'KEY2'],
            host_config=host_config,
            image='image',
            name='ctn',
        )

    @skipIf(_docker_py_version() < (
        1, 4, 0
    ), 'docker module must be installed to run this test or is too old. >=1.4.0'
            )
    @patch.object(dockerng_mod, 'images', MagicMock())
    @patch.object(dockerng_mod, 'inspect_image')
    @patch.object(dockerng_mod, 'version',
                  Mock(return_value={'ApiVersion': '1.19'}))
    def test_create_with_labels_error(self, *args):
        '''
        Create container with invalid labels.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
        }
        host_config = {}
        client = Mock()
        client.api_version = '1.19'
        client.create_host_config.return_value = host_config
        client.create_container.return_value = {}
        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.dict(dockerng_mod.__context__,
                            {'docker.client': client}):
                self.assertRaises(
                    SaltInvocationError,
                    dockerng_mod.create,
                    'image',
                    name='ctn',
                    labels=22,
                    validate_input=True,
                )

    @skipIf(_docker_py_version() < (
        1, 4, 0
    ), 'docker module must be installed to run this test or is too old. >=1.4.0'
            )
    @patch.object(dockerng_mod, 'images', MagicMock())
    @patch.object(dockerng_mod, 'inspect_image')
    @patch.object(dockerng_mod, 'version',
                  Mock(return_value={'ApiVersion': '1.19'}))
    def test_create_with_labels_dictlist(self, *args):
        '''
        Create container with labels dictlist.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
        }
        host_config = {}
        client = Mock()
        client.api_version = '1.19'
        client.create_host_config.return_value = host_config
        client.create_container.return_value = {}
        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.dict(dockerng_mod.__context__,
                            {'docker.client': client}):
                dockerng_mod.create(
                    'image',
                    name='ctn',
                    labels=[{
                        'KEY1': 'VALUE1'
                    }, {
                        'KEY2': 'VALUE2'
                    }],
                    validate_input=True,
                )
        client.create_container.assert_called_once_with(
            labels={
                'KEY1': 'VALUE1',
                'KEY2': 'VALUE2'
            },
            host_config=host_config,
            image='image',
            name='ctn',
        )

    @skipIf(_docker_py_version() < (
        1, 5, 0
    ), 'docker module must be installed to run this test or is too old. >=1.5.0'
            )
    def test_list_networks(self, *args):
        '''
        test list networks.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
        }
        host_config = {}
        client = Mock()
        client.api_version = '1.21'
        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.dict(dockerng_mod.__context__,
                            {'docker.client': client}):
                dockerng_mod.networks(
                    names=['foo'],
                    ids=['01234'],
                )
        client.networks.assert_called_once_with(
            names=['foo'],
            ids=['01234'],
        )

    @skipIf(_docker_py_version() < (
        1, 5, 0
    ), 'docker module must be installed to run this test or is too old. >=1.5.0'
            )
    def test_create_network(self, *args):
        '''
        test create network.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
        }
        host_config = {}
        client = Mock()
        client.api_version = '1.21'
        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.dict(dockerng_mod.__context__,
                            {'docker.client': client}):
                dockerng_mod.create_network(
                    'foo',
                    driver='bridge',
                )
        client.create_network.assert_called_once_with(
            'foo',
            driver='bridge',
        )

    @skipIf(_docker_py_version() < (
        1, 5, 0
    ), 'docker module must be installed to run this test or is too old. >=1.5.0'
            )
    def test_remove_network(self, *args):
        '''
        test remove network.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
        }
        host_config = {}
        client = Mock()
        client.api_version = '1.21'
        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.dict(dockerng_mod.__context__,
                            {'docker.client': client}):
                dockerng_mod.remove_network('foo')
        client.remove_network.assert_called_once_with('foo')

    @skipIf(_docker_py_version() < (
        1, 5, 0
    ), 'docker module must be installed to run this test or is too old. >=1.5.0'
            )
    def test_inspect_network(self, *args):
        '''
        test inspect network.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
        }
        host_config = {}
        client = Mock()
        client.api_version = '1.21'
        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.dict(dockerng_mod.__context__,
                            {'docker.client': client}):
                dockerng_mod.inspect_network('foo')
        client.inspect_network.assert_called_once_with('foo')

    @skipIf(_docker_py_version() < (
        1, 5, 0
    ), 'docker module must be installed to run this test or is too old. >=1.5.0'
            )
    def test_connect_container_to_network(self, *args):
        '''
        test inspect network.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
        }
        host_config = {}
        client = Mock()
        client.api_version = '1.21'
        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.dict(dockerng_mod.__context__,
                            {'docker.client': client}):
                dockerng_mod.connect_container_to_network('container', 'foo')
        client.connect_container_to_network.assert_called_once_with(
            'container', 'foo')

    @skipIf(_docker_py_version() < (
        1, 5, 0
    ), 'docker module must be installed to run this test or is too old. >=1.5.0'
            )
    def test_disconnect_container_from_network(self, *args):
        '''
        test inspect network.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
        }
        host_config = {}
        client = Mock()
        client.api_version = '1.21'
        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.dict(dockerng_mod.__context__,
                            {'docker.client': client}):
                dockerng_mod.disconnect_container_from_network(
                    'container', 'foo')
        client.disconnect_container_from_network.assert_called_once_with(
            'container', 'foo')

    @skipIf(_docker_py_version() < (
        1, 5, 0
    ), 'docker module must be installed to run this test or is too old. >=1.5.0'
            )
    def test_list_volumes(self, *args):
        '''
        test list volumes.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
        }
        client = Mock()
        client.api_version = '1.21'
        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.dict(dockerng_mod.__context__,
                            {'docker.client': client}):
                dockerng_mod.volumes(filters={'dangling': [True]}, )
        client.volumes.assert_called_once_with(filters={'dangling': [True]}, )

    @skipIf(_docker_py_version() < (
        1, 5, 0
    ), 'docker module must be installed to run this test or is too old. >=1.5.0'
            )
    def test_create_volume(self, *args):
        '''
        test create volume.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
        }
        client = Mock()
        client.api_version = '1.21'
        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.dict(dockerng_mod.__context__,
                            {'docker.client': client}):
                dockerng_mod.create_volume(
                    'foo',
                    driver='bridge',
                    driver_opts={},
                )
        client.create_volume.assert_called_once_with(
            'foo',
            driver='bridge',
            driver_opts={},
        )

    @skipIf(_docker_py_version() < (
        1, 5, 0
    ), 'docker module must be installed to run this test or is too old. >=1.5.0'
            )
    def test_remove_volume(self, *args):
        '''
        test remove volume.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
        }
        client = Mock()
        client.api_version = '1.21'
        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.dict(dockerng_mod.__context__,
                            {'docker.client': client}):
                dockerng_mod.remove_volume('foo')
        client.remove_volume.assert_called_once_with('foo')

    @skipIf(_docker_py_version() < (
        1, 5, 0
    ), 'docker module must be installed to run this test or is too old. >=1.5.0'
            )
    def test_inspect_volume(self, *args):
        '''
        test inspect volume.
        '''
        __salt__ = {
            'config.get': Mock(),
            'mine.send': Mock(),
        }
        client = Mock()
        client.api_version = '1.21'
        with patch.dict(dockerng_mod.__dict__, {'__salt__': __salt__}):
            with patch.dict(dockerng_mod.__context__,
                            {'docker.client': client}):
                dockerng_mod.inspect_volume('foo')
        client.inspect_volume.assert_called_once_with('foo')
Exemple #23
0
    'Name,Owner,Encoding,Collate,Ctype,Access privileges,Tablespace\n'
    'template1,postgres,LATIN1,en_US,en_US'
    ',"{=c/postgres,postgres=CTc/postgres}",pg_default\n'
    'template0,postgres,LATIN1,en_US,en_US'
    ',"{=c/postgres,postgres=CTc/postgres}",pg_default\n'
    'postgres,postgres,LATIN1,en_US,en_US,,pg_default\n'
    'test_db,postgres,LATIN1,en_US,en_US,,pg_default')

test_list_schema_csv = (
    'name,owner,acl\n'
    'public,postgres,"{postgres=UC/postgres,=UC/postgres}"\n'
    'pg_toast,postgres,""')

if NO_MOCK is False:
    SALT_STUB = {
        'config.option': Mock(),
        'cmd.run_all': Mock(),
        'file.chown': Mock(),
        'file.remove': Mock(),
    }
else:
    SALT_STUB = {}


@skipIf(NO_MOCK, NO_MOCK_REASON)
@patch.multiple(postgres,
                __grains__={'os_family': 'Linux'},
                __salt__=SALT_STUB)
@patch('salt.utils.which', Mock(return_value='/usr/bin/pgsql'))
class PostgresTestCase(TestCase):
    def test_run_psql(self):
Exemple #24
0
def mock_json_response(data):
    response = MagicMock()
    response.json = MagicMock(return_value=data)
    return Mock(return_value=response)
Exemple #25
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)
Exemple #26
0
# Import Salt Testing libs
from salttesting import skipIf, TestCase
from salttesting.helpers import ensure_in_syspath
from salttesting.mock import NO_MOCK, NO_MOCK_REASON, Mock, patch
ensure_in_syspath('../../')

# Import salt libs
from salt.modules import postgres
postgres.__grains__ = None  # in order to stub it w/patch below
postgres.__salt__ = None  # in order to stub it w/patch below

if NO_MOCK is False:
    SALT_STUB = {
        'config.option': Mock(),
        'cmd.run_all': Mock(),
        'file.chown': Mock(),
        'file.remove': Mock(),
    }
else:
    SALT_STUB = {}


@skipIf(NO_MOCK, NO_MOCK_REASON)
class PostgresTestCase(TestCase):
    @patch.multiple(postgres,
                    __grains__={'os_family': 'Linux'},
                    __salt__=SALT_STUB)
    def test_run_psql(self):
        postgres._run_psql('echo "hi"')
        cmd = SALT_STUB['cmd.run_all']
Exemple #27
0
class PostgresTestCase(TestCase):
    def test_run_psql(self):
        postgres._run_psql('echo "hi"')
        cmd = SALT_STUB['cmd.run_all']

        self.assertEqual('postgres', cmd.call_args[1]['runas'])

    @patch('salt.modules.postgres._run_psql',
           Mock(return_value={'retcode': 0}))
    def test_db_alter(self):
        postgres.db_alter('dbname',
                          user='******',
                          host='testhost',
                          port='testport',
                          maintenance_db='maint_db',
                          password='******',
                          tablespace='testspace',
                          owner='otheruser',
                          runas='foo')
        postgres._run_psql.assert_has_calls([
            call([
                '/usr/bin/pgsql', '--no-align', '--no-readline',
                '--no-password', '--username', 'testuser', '--host',
                'testhost', '--port', 'testport', '--dbname', 'maint_db', '-c',
                'ALTER DATABASE "dbname" OWNER TO "otheruser"'
            ],
                 host='testhost',
                 user='******',
                 password='******',
                 runas='foo',
                 port='testport'),
            call([
                '/usr/bin/pgsql', '--no-align', '--no-readline',
                '--no-password', '--username', 'testuser', '--host',
                'testhost', '--port', 'testport', '--dbname', 'maint_db', '-c',
                'ALTER DATABASE "dbname" SET TABLESPACE "testspace"'
            ],
                 host='testhost',
                 user='******',
                 password='******',
                 runas='foo',
                 port='testport')
        ])

    @patch('salt.modules.postgres.owner_to',
           Mock(return_value={'retcode': None}))
    def test_db_alter_owner_recurse(self):
        postgres.db_alter('dbname',
                          user='******',
                          host='testhost',
                          port='testport',
                          maintenance_db='maint_db',
                          password='******',
                          tablespace='testspace',
                          owner='otheruser',
                          owner_recurse=True,
                          runas='foo')
        postgres.owner_to.assert_called_once_with('dbname',
                                                  'otheruser',
                                                  user='******',
                                                  host='testhost',
                                                  port='testport',
                                                  password='******',
                                                  runas='foo')

    @patch('salt.modules.postgres._run_psql',
           Mock(return_value={'retcode': 0}))
    def test_db_create(self):
        postgres.db_create('dbname',
                           user='******',
                           host='testhost',
                           port='testport',
                           maintenance_db='maint_db',
                           password='******',
                           tablespace='testspace',
                           owner='otheruser',
                           runas='foo')

        postgres._run_psql.assert_called_once_with([
            '/usr/bin/pgsql', '--no-align', '--no-readline', '--no-password',
            '--username', 'testuser', '--host', 'testhost', '--port',
            'testport', '--dbname', 'maint_db', '-c',
            'CREATE DATABASE "dbname" WITH TABLESPACE = testspace '
            'OWNER = "otheruser"'
        ],
                                                   host='testhost',
                                                   user='******',
                                                   password='******',
                                                   runas='foo',
                                                   port='testport')

    @patch('salt.modules.postgres._run_psql',
           Mock(return_value={
               'retcode': 0,
               'stdout': test_list_db_csv
           }))
    def test_db_exists(self):
        ret = postgres.db_exists('test_db',
                                 user='******',
                                 host='testhost',
                                 port='testport',
                                 maintenance_db='maint_db',
                                 password='******',
                                 runas='foo')
        self.assertTrue(ret)

    @patch('salt.modules.postgres._run_psql',
           Mock(return_value={
               'retcode': 0,
               'stdout': test_list_db_csv
           }))
    def test_db_list(self):
        ret = postgres.db_list(user='******',
                               host='testhost',
                               port='testport',
                               maintenance_db='maint_db',
                               password='******',
                               runas='foo')
        self.assertDictEqual(
            ret, {
                'test_db': {
                    'Encoding': 'LATIN1',
                    'Ctype': 'en_US',
                    'Tablespace': 'pg_default',
                    'Collate': 'en_US',
                    'Owner': 'postgres',
                    'Access privileges': ''
                },
                'template1': {
                    'Encoding': 'LATIN1',
                    'Ctype': 'en_US',
                    'Tablespace': 'pg_default',
                    'Collate': 'en_US',
                    'Owner': 'postgres',
                    'Access privileges':
                    ('{=c/postgres,postgres=CTc/postgres}')
                },
                'template0': {
                    'Encoding': 'LATIN1',
                    'Ctype': 'en_US',
                    'Tablespace': 'pg_default',
                    'Collate': 'en_US',
                    'Owner': 'postgres',
                    'Access privileges':
                    ('{=c/postgres,postgres=CTc/postgres}')
                },
                'postgres': {
                    'Encoding': 'LATIN1',
                    'Ctype': 'en_US',
                    'Tablespace': 'pg_default',
                    'Collate': 'en_US',
                    'Owner': 'postgres',
                    'Access privileges': ''
                }
            })

    @patch('salt.modules.postgres._run_psql',
           Mock(return_value={'retcode': 0}))
    def test_db_remove(self):
        postgres.db_remove('test_db',
                           user='******',
                           host='testhost',
                           port='testport',
                           maintenance_db='maint_db',
                           password='******',
                           runas='foo')
        postgres._run_psql.assert_called_once_with([
            '/usr/bin/pgsql', '--no-align', '--no-readline', '--no-password',
            '--username', 'testuser', '--host', 'testhost', '--port',
            'testport', '--dbname', 'maint_db', '-c', 'DROP DATABASE "test_db"'
        ],
                                                   host='testhost',
                                                   user='******',
                                                   password='******',
                                                   runas='foo',
                                                   port='testport')

    @patch('salt.modules.postgres._run_psql',
           Mock(return_value={'retcode': 0}))
    @patch('salt.modules.postgres.user_exists', Mock(return_value=False))
    def test_group_create(self):
        postgres.group_create('testgroup',
                              user='******',
                              host='testhost',
                              port='testport',
                              maintenance_db='maint_db',
                              password='******',
                              createdb=False,
                              createuser=False,
                              encrypted=False,
                              superuser=False,
                              replication=False,
                              rolepassword='******',
                              groups='testgroup',
                              runas='foo')
        # postgres._run_psql.call_args[0][0] will contain the list of CLI args.
        # The first 13 elements of this list are initial args used in all (or
        # virtually all) commands run through _run_psql(), so the actual SQL
        # query will be in the 14th argument.
        self.assertTrue(
            postgres._run_psql.call_args[0][0][13].startswith('CREATE ROLE'))

    @patch('salt.modules.postgres._run_psql',
           Mock(return_value={'retcode': 0}))
    @patch('salt.modules.postgres.user_exists', Mock(return_value=True))
    def test_group_remove(self):
        postgres.group_remove('testgroup',
                              user='******',
                              host='testhost',
                              port='testport',
                              maintenance_db='maint_db',
                              password='******',
                              runas='foo')
        postgres._run_psql.assert_called_once_with([
            '/usr/bin/pgsql', '--no-align', '--no-readline', '--no-password',
            '--username', 'testuser', '--host', 'testhost', '--port',
            'testport', '--dbname', 'maint_db', '-c', 'DROP ROLE "testgroup"'
        ],
                                                   host='testhost',
                                                   user='******',
                                                   password='******',
                                                   runas='foo',
                                                   port='testport')

    @patch('salt.modules.postgres._run_psql',
           Mock(return_value={'retcode': 0}))
    @patch('salt.modules.postgres.role_get',
           Mock(return_value={'superuser': False}))
    def test_group_update(self):
        postgres.group_update('testgroup',
                              user='******',
                              host='testhost',
                              port='testport',
                              maintenance_db='maint_db',
                              password='******',
                              createdb=False,
                              createuser=False,
                              encrypted=False,
                              replication=False,
                              rolepassword='******',
                              groups='testgroup',
                              runas='foo')
        # postgres._run_psql.call_args[0][0] will contain the list of CLI args.
        # The first 13 elements of this list are initial args used in all (or
        # virtually all) commands run through _run_psql(), so the actual SQL
        # query will be in the 14th argument.
        self.assertTrue(
            re.match('ALTER.* "testgroup" .* UNENCRYPTED PASSWORD',
                     postgres._run_psql.call_args[0][0][13]))

    @patch('salt.modules.postgres._run_psql',
           Mock(return_value={'retcode': 0}))
    @patch('salt.modules.postgres.user_exists', Mock(return_value=False))
    def test_user_create(self):
        postgres.user_create('testuser',
                             user='******',
                             host='testhost',
                             port='testport',
                             maintenance_db='maint_test',
                             password='******',
                             login=True,
                             createdb=False,
                             createroles=False,
                             createuser=False,
                             encrypted=False,
                             superuser=False,
                             replication=False,
                             rolepassword='******',
                             groups='test_groups',
                             runas='foo')
        # postgres._run_psql.call_args[0][0] will contain the list of CLI args.
        # The first 13 elements of this list are initial args used in all (or
        # virtually all) commands run through _run_psql(), so the actual SQL
        # query will be in the 14th argument.
        call = postgres._run_psql.call_args[0][0][13]
        self.assertTrue(re.match('CREATE ROLE "testuser"', call))
        for i in ('INHERIT NOCREATEDB NOCREATEROLE '
                  'NOSUPERUSER NOREPLICATION LOGIN UNENCRYPTED PASSWORD'
                  ).split():
            self.assertTrue(i in call, '{0} not in {1}'.format(i, call))

    @patch('salt.modules.postgres._run_psql',
           Mock(return_value={'retcode': 0}))
    @patch('salt.modules.postgres.version', Mock(return_value='9.1'))
    @patch('salt.modules.postgres.psql_query',
           Mock(return_value=[{
               'name': 'test_user',
               'superuser': '******',
               'inherits privileges': 't',
               'can create roles': 't',
               'can create databases': 't',
               'can update system catalogs': 't',
               'can login': '******',
               'replication': None,
               'password': '******',
               'connections': '-1',
               'defaults variables': None
           }]))
    def test_user_exists(self):
        ret = postgres.user_exists('test_user',
                                   user='******',
                                   host='test_host',
                                   port='test_port',
                                   maintenance_db='maint_db',
                                   password='******',
                                   runas='foo')
        self.assertTrue(ret)

    @patch('salt.modules.postgres._run_psql',
           Mock(return_value={'retcode': 0}))
    @patch('salt.modules.postgres.version', Mock(return_value='9.1'))
    @patch('salt.modules.postgres.psql_query',
           Mock(return_value=[{
               'name': 'test_user',
               'superuser': '******',
               'inherits privileges': 't',
               'can create roles': 't',
               'can create databases': 't',
               'can update system catalogs': 't',
               'can login': '******',
               'replication': None,
               'connections': '-1',
               'defaults variables': None
           }]))
    def test_user_list(self):
        ret = postgres.user_list('test_user',
                                 host='test_host',
                                 port='test_port',
                                 maintenance_db='maint_db',
                                 password='******',
                                 runas='foo')

        self.assertDictEqual(
            ret, {
                'test_user': {
                    'superuser': True,
                    'defaults variables': None,
                    'can create databases': True,
                    'can create roles': True,
                    'connections': None,
                    'replication': None,
                    'expiry time': None,
                    'can login': True,
                    'can update system catalogs': True,
                    'groups': [],
                    'inherits privileges': True
                }
            })

    @patch('salt.modules.postgres._run_psql',
           Mock(return_value={'retcode': 0}))
    @patch('salt.modules.postgres.version', Mock(return_value='9.1'))
    @patch('salt.modules.postgres.user_exists', Mock(return_value=True))
    def test_user_remove(self):
        postgres.user_remove('testuser',
                             user='******',
                             host='testhost',
                             port='testport',
                             maintenance_db='maint_db',
                             password='******',
                             runas='foo')
        postgres._run_psql.assert_called_once_with([
            '/usr/bin/pgsql', '--no-align', '--no-readline', '--no-password',
            '--username', 'testuser', '--host', 'testhost', '--port',
            'testport', '--dbname', 'maint_db', '-c', 'DROP ROLE "testuser"'
        ],
                                                   host='testhost',
                                                   port='testport',
                                                   user='******',
                                                   password='******',
                                                   runas='foo')

    @patch('salt.modules.postgres._run_psql',
           Mock(return_value={'retcode': 0}))
    @patch('salt.modules.postgres.role_get',
           Mock(return_value={'superuser': False}))
    def test_user_update(self):
        postgres.user_update('test_username',
                             user='******',
                             host='test_host',
                             port='test_port',
                             maintenance_db='test_maint',
                             password='******',
                             createdb=False,
                             createroles=False,
                             createuser=False,
                             encrypted=False,
                             inherit=True,
                             login=True,
                             replication=False,
                             rolepassword='******',
                             groups='test_groups',
                             runas='foo')
        # postgres._run_psql.call_args[0][0] will contain the list of CLI args.
        # The first 13 elements of this list are initial args used in all (or
        # virtually all) commands run through _run_psql(), so the actual SQL
        # query will be in the 14th argument.
        self.assertTrue(
            re.match(
                'ALTER ROLE "test_username" WITH  INHERIT NOCREATEDB '
                'NOCREATEROLE NOREPLICATION LOGIN '
                'UNENCRYPTED PASSWORD [\'"]{0,5}test_role_pass[\'"]{0,5};'
                ' GRANT "test_groups" TO "test_username"',
                postgres._run_psql.call_args[0][0][13]))

    @patch('salt.modules.postgres._run_psql',
           Mock(return_value={'retcode': 0}))
    @patch('salt.modules.postgres.role_get',
           Mock(return_value={'superuser': False}))
    def test_user_update2(self):
        postgres.user_update('test_username',
                             user='******',
                             host='test_host',
                             port='test_port',
                             maintenance_db='test_maint',
                             password='******',
                             createdb=False,
                             createroles=True,
                             createuser=False,
                             encrypted=False,
                             inherit=True,
                             login=True,
                             replication=False,
                             groups='test_groups',
                             runas='foo')
        # postgres._run_psql.call_args[0][0] will contain the list of CLI args.
        # The first 13 elements of this list are initial args used in all (or
        # virtually all) commands run through _run_psql(), so the actual SQL
        # query will be in the 14th argument.
        self.assertTrue(
            re.match(
                'ALTER ROLE "test_username" WITH  INHERIT NOCREATEDB '
                'CREATEROLE NOREPLICATION LOGIN;'
                ' GRANT "test_groups" TO "test_username"',
                postgres._run_psql.call_args[0][0][13]))

    @patch('salt.modules.postgres._run_psql',
           Mock(return_value={'retcode': 0}))
    @patch('salt.modules.postgres.role_get',
           Mock(return_value={'superuser': False}))
    def test_user_update3(self):
        postgres.user_update('test_username',
                             user='******',
                             host='test_host',
                             port='test_port',
                             maintenance_db='test_maint',
                             password='******',
                             createdb=False,
                             createroles=True,
                             createuser=False,
                             encrypted=False,
                             inherit=True,
                             login=True,
                             rolepassword=False,
                             replication=False,
                             groups='test_groups',
                             runas='foo')
        # postgres._run_psql.call_args[0][0] will contain the list of CLI args.
        # The first 13 elements of this list are initial args used in all (or
        # virtually all) commands run through _run_psql(), so the actual SQL
        # query will be in the 14th argument.
        self.assertTrue(
            re.match(
                'ALTER ROLE "test_username" WITH  INHERIT NOCREATEDB '
                'CREATEROLE NOREPLICATION LOGIN NOPASSWORD;'
                ' GRANT "test_groups" TO "test_username"',
                postgres._run_psql.call_args[0][0][13]))

    @patch('salt.modules.postgres._run_psql',
           Mock(return_value={'retcode': 0}))
    @patch('salt.modules.postgres.role_get',
           Mock(return_value={'superuser': False}))
    def test_user_update_encrypted_passwd(self):
        postgres.user_update('test_username',
                             user='******',
                             host='test_host',
                             port='test_port',
                             maintenance_db='test_maint',
                             password='******',
                             createdb=False,
                             createroles=True,
                             createuser=False,
                             encrypted=True,
                             inherit=True,
                             login=True,
                             rolepassword='******',
                             replication=False,
                             groups='test_groups',
                             runas='foo')
        # postgres._run_psql.call_args[0][0] will contain the list of CLI args.
        # The first 13 elements of this list are initial args used in all (or
        # virtually all) commands run through _run_psql(), so the actual SQL
        # query will be in the 14th argument.
        self.assertTrue(
            re.match(
                'ALTER ROLE "test_username" WITH  INHERIT NOCREATEDB '
                'CREATEROLE NOREPLICATION LOGIN '
                'ENCRYPTED PASSWORD '
                '[\'"]{0,5}md531c27e68d3771c392b52102c01be1da1[\'"]{0,5}'
                '; GRANT "test_groups" TO "test_username"',
                postgres._run_psql.call_args[0][0][13]))

    @patch('salt.modules.postgres._run_psql',
           Mock(return_value={
               'retcode': 0,
               'stdout': '9.1.9'
           }))
    def test_version(self):
        postgres.version(user='******',
                         host='test_host',
                         port='test_port',
                         maintenance_db='test_maint',
                         password='******',
                         runas='foo')
        # postgres._run_psql.call_args[0][0] will contain the list of CLI args.
        # The first 13 elements of this list are initial args used in all (or
        # virtually all) commands run through _run_psql(), so the actual SQL
        # query will be in the 14th argument.
        self.assertTrue(
            re.match('SELECT setting FROM pg_catalog.pg_settings',
                     postgres._run_psql.call_args[0][0][13]))

    @patch('salt.modules.postgres.psql_query',
           Mock(return_value=[{
               'extname': "foo",
               'extversion': "1"
           }]))
    def test_installed_extensions(self):
        exts = postgres.installed_extensions()
        self.assertEqual(exts, {'foo': {'extversion': '1', 'extname': 'foo'}})

    @patch('salt.modules.postgres.psql_query',
           Mock(return_value=[{
               'name': "foo",
               'default_version': "1"
           }]))
    def test_available_extensions(self):
        exts = postgres.available_extensions()
        self.assertEqual(exts,
                         {'foo': {
                             'default_version': '1',
                             'name': 'foo'
                         }})

    @patch('salt.modules.postgres.installed_extensions',
           Mock(side_effect=[{}, {}]))
    @patch('salt.modules.postgres._psql_prepare_and_run',
           Mock(return_value=None))
    @patch('salt.modules.postgres.available_extensions',
           Mock(return_value={'foo': {
               'default_version': '1',
               'name': 'foo'
           }}))
    def test_drop_extension2(self):
        self.assertEqual(postgres.drop_extension('foo'), True)

    @patch('salt.modules.postgres.installed_extensions',
           Mock(side_effect=[{
               'foo': {
                   'extversion': '1',
                   'extname': 'foo'
               }
           }, {}]))
    @patch('salt.modules.postgres._psql_prepare_and_run',
           Mock(return_value=None))
    @patch('salt.modules.postgres.available_extensions',
           Mock(return_value={'foo': {
               'default_version': '1',
               'name': 'foo'
           }}))
    def test_drop_extension3(self):
        self.assertEqual(postgres.drop_extension('foo'), True)

    @patch('salt.modules.postgres.installed_extensions',
           Mock(side_effect=[{
               'foo': {
                   'extversion': '1',
                   'extname': 'foo'
               }
           }, {
               'foo': {
                   'extversion': '1',
                   'extname': 'foo'
               }
           }]))
    @patch('salt.modules.postgres._psql_prepare_and_run',
           Mock(return_value=None))
    @patch('salt.modules.postgres.available_extensions',
           Mock(return_value={'foo': {
               'default_version': '1',
               'name': 'foo'
           }}))
    def test_drop_extension1(self):
        self.assertEqual(postgres.drop_extension('foo'), False)

    @patch('salt.modules.postgres.installed_extensions',
           Mock(return_value={
               'foo': {
                   'extversion': '0.8',
                   'extrelocatable': 't',
                   'schema_name': 'foo',
                   'extname': 'foo'
               }
           }, ))
    @patch(
        'salt.modules.postgres.available_extensions',
        Mock(return_value={'foo': {
            'default_version': '1.4',
            'name': 'foo'
        }}))
    def test_create_mtdata(self):
        ret = postgres.create_metadata('foo', schema='bar', ext_version='1.4')
        self.assertTrue(postgres._EXTENSION_INSTALLED in ret)
        self.assertTrue(postgres._EXTENSION_TO_UPGRADE in ret)
        self.assertTrue(postgres._EXTENSION_TO_MOVE in ret)
        ret = postgres.create_metadata('foo', schema='foo', ext_version='0.4')
        self.assertTrue(postgres._EXTENSION_INSTALLED in ret)
        self.assertFalse(postgres._EXTENSION_TO_UPGRADE in ret)
        self.assertFalse(postgres._EXTENSION_TO_MOVE in ret)
        ret = postgres.create_metadata('foo')
        self.assertTrue(postgres._EXTENSION_INSTALLED in ret)
        self.assertFalse(postgres._EXTENSION_TO_UPGRADE in ret)
        self.assertFalse(postgres._EXTENSION_TO_MOVE in ret)
        ret = postgres.create_metadata('foobar')
        self.assertTrue(postgres._EXTENSION_NOT_INSTALLED in ret)
        self.assertFalse(postgres._EXTENSION_INSTALLED in ret)
        self.assertFalse(postgres._EXTENSION_TO_UPGRADE in ret)
        self.assertFalse(postgres._EXTENSION_TO_MOVE in ret)

    @patch(
        'salt.modules.postgres.create_metadata',
        Mock(side_effect=[
            # create succeeded
            [postgres._EXTENSION_NOT_INSTALLED],
            [postgres._EXTENSION_INSTALLED],
            [postgres._EXTENSION_NOT_INSTALLED],
            [postgres._EXTENSION_INSTALLED],
            # create failed
            [postgres._EXTENSION_NOT_INSTALLED],
            [postgres._EXTENSION_NOT_INSTALLED],
            # move+upgrade succeeded
            [
                postgres._EXTENSION_TO_MOVE, postgres._EXTENSION_TO_UPGRADE,
                postgres._EXTENSION_INSTALLED
            ],
            [postgres._EXTENSION_INSTALLED],
            # move succeeded
            [postgres._EXTENSION_TO_MOVE, postgres._EXTENSION_INSTALLED],
            [postgres._EXTENSION_INSTALLED],
            # upgrade succeeded
            [postgres._EXTENSION_TO_UPGRADE, postgres._EXTENSION_INSTALLED],
            [postgres._EXTENSION_INSTALLED],
            # upgrade failed
            [postgres._EXTENSION_TO_UPGRADE, postgres._EXTENSION_INSTALLED],
            [postgres._EXTENSION_TO_UPGRADE, postgres._EXTENSION_INSTALLED],
            # move failed
            [postgres._EXTENSION_TO_MOVE, postgres._EXTENSION_INSTALLED],
            [postgres._EXTENSION_TO_MOVE, postgres._EXTENSION_INSTALLED],
        ]))
    @patch('salt.modules.postgres._psql_prepare_and_run',
           Mock(return_value=None))
    @patch(
        'salt.modules.postgres.available_extensions',
        Mock(return_value={'foo': {
            'default_version': '1.4',
            'name': 'foo'
        }}))
    def test_create_extension_newerthan(self):
        '''
        scenario of creating upgrading extensions with possible schema and
        version specifications
        '''
        self.assertTrue(postgres.create_extension('foo'))
        self.assertTrue(
            re.match('CREATE EXTENSION IF NOT EXISTS "foo" ;',
                     postgres._psql_prepare_and_run.call_args[0][0][1]))
        self.assertTrue(
            postgres.create_extension('foo',
                                      schema='a',
                                      ext_version='b',
                                      from_version='c'))
        self.assertTrue(
            re.match(
                'CREATE EXTENSION IF NOT EXISTS "foo" '
                'WITH SCHEMA "a" VERSION b FROM c ;',
                postgres._psql_prepare_and_run.call_args[0][0][1]))
        self.assertFalse(postgres.create_extension('foo'))
        ret = postgres.create_extension('foo', ext_version='a', schema='b')
        self.assertTrue(ret)
        self.assertTrue(
            re.match(
                'ALTER EXTENSION "foo" SET SCHEMA "b";'
                ' ALTER EXTENSION "foo" UPDATE TO a;',
                postgres._psql_prepare_and_run.call_args[0][0][1]))
        ret = postgres.create_extension('foo', ext_version='a', schema='b')
        self.assertTrue(ret)
        self.assertTrue(
            re.match('ALTER EXTENSION "foo" SET SCHEMA "b";',
                     postgres._psql_prepare_and_run.call_args[0][0][1]))
        ret = postgres.create_extension('foo', ext_version='a', schema='b')
        self.assertTrue(ret)
        self.assertTrue(
            re.match('ALTER EXTENSION "foo" UPDATE TO a;',
                     postgres._psql_prepare_and_run.call_args[0][0][1]))
        self.assertFalse(
            postgres.create_extension('foo', ext_version='a', schema='b'))
        self.assertFalse(
            postgres.create_extension('foo', ext_version='a', schema='b'))

    def test_encrypt_passwords(self):
        self.assertEqual(postgres._maybe_encrypt_password('foo', 'bar', False),
                         'bar')
        self.assertEqual(postgres._maybe_encrypt_password('foo', 'bar', True),
                         'md596948aad3fcae80c08a35c9b5958cd89')

    @patch('salt.modules.postgres._run_psql',
           Mock(return_value={
               'retcode': 0,
               'stdout': test_list_schema_csv
           }))
    def test_schema_list(self):
        ret = postgres.schema_list('maint_db',
                                   db_user='******',
                                   db_host='testhost',
                                   db_port='testport',
                                   db_password='******')
        self.assertDictEqual(
            ret, {
                'public': {
                    'acl': '{postgres=UC/postgres,=UC/postgres}',
                    'owner': 'postgres'
                },
                'pg_toast': {
                    'acl': '',
                    'owner': 'postgres'
                }
            })

    @patch('salt.modules.postgres._run_psql',
           Mock(return_value={'retcode': 0}))
    @patch('salt.modules.postgres.psql_query',
           Mock(return_value=[{
               'name': 'public',
               'acl': '{postgres=UC/postgres,=UC/postgres}',
               'owner': 'postgres'
           }]))
    def test_schema_exists(self):
        ret = postgres.schema_exists('template1', 'public')
        self.assertTrue(ret)

    @patch('salt.modules.postgres._run_psql',
           Mock(return_value={'retcode': 0}))
    @patch('salt.modules.postgres.psql_query',
           Mock(return_value=[{
               'name': 'public',
               'acl': '{postgres=UC/postgres,=UC/postgres}',
               'owner': 'postgres'
           }]))
    def test_schema_get(self):
        ret = postgres.schema_get('template1', 'public')
        self.assertTrue(ret)

    @patch('salt.modules.postgres._run_psql',
           Mock(return_value={'retcode': 0}))
    @patch('salt.modules.postgres.psql_query',
           Mock(return_value=[{
               'name': 'public',
               'acl': '{postgres=UC/postgres,=UC/postgres}',
               'owner': 'postgres'
           }]))
    def test_schema_get_again(self):
        ret = postgres.schema_get('template1', 'pg_toast')
        self.assertFalse(ret)

    @patch('salt.modules.postgres._run_psql',
           Mock(return_value={'retcode': 0}))
    @patch('salt.modules.postgres.schema_exists', Mock(return_value=False))
    def test_schema_create(self):
        postgres.schema_create('maint_db',
                               'testschema',
                               user='******',
                               db_host='testhost',
                               db_port='testport',
                               db_user='******',
                               db_password='******')
        postgres._run_psql.assert_called_once_with([
            '/usr/bin/pgsql', '--no-align', '--no-readline', '--no-password',
            '--username', 'testuser', '--host', 'testhost', '--port',
            'testport', '--dbname', 'maint_db', '-c',
            'CREATE SCHEMA "testschema"'
        ],
                                                   host='testhost',
                                                   port='testport',
                                                   password='******',
                                                   user='******',
                                                   runas='user')

    @patch('salt.modules.postgres.schema_exists', Mock(return_value=True))
    def test_schema_create2(self):
        ret = postgres.schema_create('test_db',
                                     'test_schema',
                                     user='******',
                                     db_host='test_host',
                                     db_port='test_port',
                                     db_user='******',
                                     db_password='******')
        self.assertFalse(ret)

    @patch('salt.modules.postgres._run_psql',
           Mock(return_value={'retcode': 0}))
    @patch('salt.modules.postgres.schema_exists', Mock(return_value=True))
    def test_schema_remove(self):
        postgres.schema_remove('maint_db',
                               'testschema',
                               user='******',
                               db_host='testhost',
                               db_port='testport',
                               db_user='******',
                               db_password='******')
        postgres._run_psql.assert_called_once_with([
            '/usr/bin/pgsql', '--no-align', '--no-readline', '--no-password',
            '--username', 'testuser', '--host', 'testhost', '--port',
            'testport', '--dbname', 'maint_db', '-c',
            'DROP SCHEMA "testschema"'
        ],
                                                   host='testhost',
                                                   port='testport',
                                                   password='******',
                                                   user='******',
                                                   runas='user')

    @patch('salt.modules.postgres.schema_exists', Mock(return_value=False))
    def test_schema_remove2(self):
        ret = postgres.schema_remove('test_db',
                                     'test_schema',
                                     user='******',
                                     db_host='test_host',
                                     db_port='test_port',
                                     db_user='******',
                                     db_password='******')
        self.assertFalse(ret)
# Import Salt Testing libs
from salttesting import skipIf, TestCase
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')

# wmi and pythoncom modules are platform specific...
wmi = new.module('wmi')
sys.modules['wmi'] = wmi

pythoncom = new.module('pythoncom')
sys.modules['pythoncom'] = pythoncom

from salttesting.mock import NO_MOCK, NO_MOCK_REASON, Mock, patch, ANY

if NO_MOCK is False:
    WMI = Mock()
    wmi.WMI = Mock(return_value=WMI)
    pythoncom.CoInitialize = Mock()
    pythoncom.CoUninitialize = Mock()

# This is imported late so mock can do its job
import salt.modules.win_status as status


@skipIf(NO_MOCK, NO_MOCK_REASON)
class TestProcsBase(TestCase):
    def __init__(self, *args, **kwargs):
        TestCase.__init__(self, *args, **kwargs)
        self.__processes = []

    def add_process(self,
 def call_procs(self):
     WMI.win32_process = Mock(return_value=self.__processes)
     self.result = status.procs()
Exemple #30
0
class PostgresExtensionTestCase(TestCase):
    @patch.dict(
        SALT_STUB, {
            'postgres.create_metadata':
            Mock(side_effect=[
                [postgresmod._EXTENSION_NOT_INSTALLED],
                [
                    postgresmod._EXTENSION_TO_MOVE,
                    postgresmod._EXTENSION_INSTALLED
                ],
            ]),
            'postgres.create_extension':
            Mock(side_effect=[
                False,
                False,
            ]),
        })
    def test_present_failed(self):
        '''
        scenario of creating upgrading extensions with possible schema and
        version specifications
        '''
        ret = postgres_extension.present('foo')
        self.assertEqual(
            ret,
            {
                'comment': 'Failed to install extension foo',
                'changes': {},
                'name': 'foo',
                'result': False
            },
        )
        ret = postgres_extension.present('foo')
        self.assertEqual(
            ret, {
                'comment': 'Failed to upgrade extension foo',
                'changes': {},
                'name': 'foo',
                'result': False
            })

    @patch.dict(
        SALT_STUB, {
            'postgres.create_metadata':
            Mock(side_effect=[
                [postgresmod._EXTENSION_NOT_INSTALLED],
                [postgresmod._EXTENSION_INSTALLED],
                [
                    postgresmod._EXTENSION_TO_MOVE,
                    postgresmod._EXTENSION_INSTALLED
                ],
            ]),
            'postgres.create_extension':
            Mock(side_effect=[
                True,
                True,
                True,
            ]),
        })
    def test_present(self):
        '''
        scenario of creating upgrading extensions with possible schema and
        version specifications
        '''
        ret = postgres_extension.present('foo')
        self.assertEqual(
            ret, {
                'comment': 'The extension foo has been installed',
                'changes': {},
                'name': 'foo',
                'result': True
            })
        ret = postgres_extension.present('foo')
        self.assertEqual(
            ret, {
                'comment': 'Extention foo is already present',
                'changes': {},
                'name': 'foo',
                'result': True
            })
        ret = postgres_extension.present('foo')
        self.assertEqual(
            ret, {
                'comment': 'The extension foo has been upgradeed',
                'changes': {},
                'name': 'foo',
                'result': True
            })

    @patch.dict(OPTS, {'test': True})
    @patch.dict(
        SALT_STUB, {
            'postgres.create_metadata':
            Mock(side_effect=[
                [postgresmod._EXTENSION_NOT_INSTALLED],
                [postgresmod._EXTENSION_INSTALLED],
                [
                    postgresmod._EXTENSION_TO_MOVE,
                    postgresmod._EXTENSION_INSTALLED
                ],
            ]),
            'postgres.create_extension':
            Mock(side_effect=[
                True,
                True,
                True,
            ]),
        })
    def test_presenttest(self):
        '''
        scenario of creating upgrading extensions with possible schema and
        version specifications
        '''
        ret = postgres_extension.present('foo')
        self.assertEqual(
            ret, {
                'comment': 'Extension foo is set to be installed',
                'changes': {},
                'name': 'foo',
                'result': None
            })
        ret = postgres_extension.present('foo')
        self.assertEqual(
            ret, {
                'comment': "Extension foo is set to be created",
                'changes': {},
                'name': 'foo',
                'result': None
            })
        ret = postgres_extension.present('foo')
        self.assertEqual(
            ret, {
                'comment': "Extension foo is set to be upgraded",
                'changes': {},
                'name': 'foo',
                'result': None
            })

    @patch.dict(
        SALT_STUB, {
            'postgres.is_installed_extension': Mock(side_effect=[
                True,
                False,
            ]),
            'postgres.drop_extension': Mock(side_effect=[
                True,
                True,
            ]),
        })
    def test_absent(self):
        '''
        scenario of creating upgrading extensions with possible schema and
        version specifications
        '''
        ret = postgres_extension.absent('foo')
        self.assertEqual(
            ret, {
                'comment': 'Extension foo has been removed',
                'changes': {
                    'foo': 'Absent'
                },
                'name': 'foo',
                'result': True
            })
        ret = postgres_extension.absent('foo')
        self.assertEqual(
            ret, {
                'comment': ('Extension foo is not present, '
                            'so it cannot be removed'),
                'changes': {},
                'name':
                'foo',
                'result':
                True
            })

    @patch.dict(OPTS, {'test': False})
    @patch.dict(
        SALT_STUB, {
            'postgres.is_installed_extension': Mock(side_effect=[
                True,
                True,
            ]),
            'postgres.drop_extension': Mock(side_effect=[
                False,
                False,
            ]),
        })
    def test_absent_failed(self):
        '''
        scenario of creating upgrading extensions with possible schema and
        version specifications
        '''
        ret = postgres_extension.absent('foo')
        self.assertEqual(
            ret, {
                'comment': 'Extension foo failed to be removed',
                'changes': {},
                'name': 'foo',
                'result': False
            })

    @patch.dict(OPTS, {'test': True})
    @patch.dict(
        SALT_STUB, {
            'postgres.is_installed_extension': Mock(side_effect=[
                True,
                True,
            ]),
            'postgres.drop_extension': Mock(side_effect=[
                False,
                False,
            ]),
        })
    def test_absent_failedtest(self):
        ret = postgres_extension.absent('foo')
        self.assertEqual(
            ret, {
                'comment': 'Extension foo is set to be removed',
                'changes': {},
                'name': 'foo',
                'result': None
            })