Exemple #1
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,
         validate_ip_addrs=False,
         name='cont',
         labels=['LABEL1', 'LABEL2'],
         client_timeout=60)
 def add_process(self, pid=100, cmd="cmd", name="name", user="******", user_domain="domain", get_owner_result=0):
     process = Mock()
     process.GetOwner = Mock(return_value=(user_domain, get_owner_result, user))
     process.ProcessId = pid
     process.CommandLine = cmd
     process.Name = name
     self.__processes.append(process)
Exemple #3
0
 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',
     )
Exemple #4
0
    def test_check_mine_cache_is_refreshed_on_container_change_event(self, _):
        '''
        Every command that might modify docker containers state.
        Should trig an update on ``mine.send``
        '''

        for command_name, args in (('create', ()),
                                   ('rm_', ()),
                                   ('kill', ()),
                                   ('pause', ()),
                                   ('signal_', ('KILL',)),
                                   ('start', ()),
                                   ('stop', ()),
                                   ('unpause', ()),
                                   ('_run', ('command',)),
                                   ('_script', ('command',)),
                                   ):
            mine_send = Mock()
            command = getattr(dockerng_mod, command_name)
            docker_client = MagicMock()
            docker_client.api_version = '1.12'
            with patch.dict(dockerng_mod.__salt__,
                            {'mine.send': mine_send,
                             'container_resource.run': MagicMock(),
                             'cp.cache_file': MagicMock(return_value=False)}):
                with patch.dict(dockerng_mod.__context__,
                                {'docker.client': docker_client}):
                    command('container', *args)
            mine_send.assert_called_with('dockerng.ps', verbose=True, all=True,
                                         host=True)
    def test_with_user(self):
        config = {'states': ['device'], 'user': '******'}

        mock = Mock(return_value='* daemon started successfully *\nList of devices attached\nHTC\tdevice',)
        with patch.dict(adb.__salt__, {'cmd.run': mock}):
            ret = adb.beacon(config)
            mock.assert_called_once_with('adb devices', runas='fred')
            self.assertEqual(ret, [{'device': 'HTC', 'state': 'device', 'tag': 'device'}])
Exemple #6
0
    def test_screen_state(self):
        config = {'screen_event': True, 'user': '******'}

        mock = Mock(return_value=0)
        with patch.dict(glxinfo.__salt__, {'cmd.retcode': mock}):
            ret = glxinfo.beacon(config)
            self.assertEqual(ret, [{'tag': 'screen_event', 'screen_available': True}])
            mock.assert_called_once_with('DISPLAY=:0 glxinfo', runas='frank', python_shell=True)
Exemple #7
0
 def test_wait_success_absent_container(self):
     client = Mock()
     client.api_version = '1.21'
     dockerng_inspect_container = Mock(side_effect=CommandExecutionError)
     with patch.object(dockerng_mod, 'inspect_container',
                       dockerng_inspect_container):
         with patch.dict(dockerng_mod.__context__,
                         {'docker.client': client}):
             dockerng_mod._clear_context()
             result = dockerng_mod.wait('foo', ignore_already_stopped=True)
     self.assertEqual(result, {'result': True,
                               'comment': "Container 'foo' absent"})
Exemple #8
0
 def test_validate_input_min_docker_py(self):
     docker_mock = Mock()
     docker_mock.version_info = (1, 0, 0)
     dockerng_mod.docker = None
     with patch.dict(dockerng_mod.VALID_CREATE_OPTS['command'],
                     {'path': 'Config:Cmd',
                      'image_path': 'Config:Cmd',
                      'min_docker_py': (999, 0, 0)}):
         with patch.object(dockerng_mod, 'docker', docker_mock):
             self.assertRaisesRegexp(SaltInvocationError,
                                     "The 'command' parameter requires at"
                                     " least docker-py 999.0.0.*$",
                                     dockerng_state._validate_input,
                                     {'command': 'echo boom'})
Exemple #9
0
    def test_call_success(self):
        '''
        test module calling inside containers
        '''
        ret = None
        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
            })
        client = Mock()
        client.put_archive = Mock()

        with patch.dict(dockerng_mod.__opts__, {'cachedir': '/tmp'}):
            with patch.dict(dockerng_mod.__salt__, {'dockerng.run_all': docker_run_all_mock,
                                                    'dockerng.copy_to': docker_copy_to_mock}):
                with 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)
Exemple #10
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 #11
0
 def add_process(
         self,
         pid=100,
         cmd='cmd',
         name='name',
         user='******',
         user_domain='domain',
         get_owner_result=0):
     process = Mock()
     process.GetOwner = Mock(
         return_value=(user_domain, get_owner_result, user)
     )
     process.ProcessId = pid
     process.CommandLine = cmd
     process.Name = name
     self.__processes.append(process)
Exemple #12
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')
Exemple #13
0
 def test_wait_fails_on_exit_status(self):
     client = Mock()
     client.api_version = '1.21'
     client.wait = Mock(return_value=1)
     dockerng_inspect_container = Mock(side_effect=[
         {'State': {'Running': True}},
         {'State': {'Stopped': True}}])
     with patch.object(dockerng_mod, 'inspect_container',
                       dockerng_inspect_container):
         with patch.dict(dockerng_mod.__context__,
                         {'docker.client': client}):
             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'}})
Exemple #14
0
 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']}])
     with patch.dict(dockerng_mod.__context__,
                     {'docker.client': client}):
         dockerng_mod._clear_context()
         result = dockerng_mod.images()
     self.assertEqual(result,
                      {'sha256:abcdefg': {'RepoTags': ['image:latest']}})
Exemple #15
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 #16
0
 def test_wait_success_already_stopped(self):
     client = Mock()
     client.api_version = '1.21'
     client.wait = Mock(return_value=0)
     dockerng_inspect_container = Mock(side_effect=[
         {'State': {'Stopped': True}},
         {'State': {'Stopped': True}},
     ])
     with patch.object(dockerng_mod, 'inspect_container',
                       dockerng_inspect_container):
         with patch.dict(dockerng_mod.__context__,
                         {'docker.client': client}):
             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'}})
Exemple #17
0
 def test_volume_absent(self):
     '''
     Test dockerng.volume_absent
     '''
     dockerng_remove_volume = Mock(return_value='removed')
     __salt__ = {'dockerng.remove_volume': dockerng_remove_volume,
                 'dockerng.volumes': Mock(return_value={
                     'Volumes': [{'Name': 'volume_foo'}]}),
                 }
     with patch.dict(dockerng_state.__dict__,
                     {'__salt__': __salt__}):
         ret = dockerng_state.volume_absent(
             'volume_foo',
             )
     dockerng_remove_volume.assert_called_with('volume_foo')
     self.assertEqual(ret, {'name': 'volume_foo',
                            'comment': '',
                            'changes': {'removed': 'removed'},
                            'result': True})
Exemple #18
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]},
     )
Exemple #19
0
 def test_volume_present(self):
     '''
     Test dockerng.volume_present
     '''
     dockerng_create_volume = Mock(return_value='created')
     __salt__ = {'dockerng.create_volume': dockerng_create_volume,
                 'dockerng.volumes': Mock(return_value={'Volumes': []}),
                 }
     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(ret, {'name': 'volume_foo',
                            'comment': '',
                            'changes': {'created': 'created'},
                            'result': True})
Exemple #20
0
    def test_running_with_no_predifined_volume(self):
        '''
        Test dockerng.running function with an image
        that doens't have VOLUME defined.

        The ``binds`` argument, should create a container
        with respective volumes extracted from ``binds``.
        '''
        dockerng_create = Mock()
        dockerng_start = Mock()
        __salt__ = {'dockerng.list_containers': MagicMock(),
                    'dockerng.list_tags': MagicMock(),
                    'dockerng.pull': MagicMock(),
                    'dockerng.state': MagicMock(),
                    'dockerng.inspect_image': MagicMock(),
                    'dockerng.create': dockerng_create,
                    'dockerng.start': dockerng_start,
                    }
        with patch.dict(dockerng_state.__dict__,
                        {'__salt__': __salt__}):
            dockerng_state.running(
                'cont',
                image='image:latest',
                binds=['/host-0:/container-0:ro'])
        dockerng_create.assert_called_with(
            'image:latest',
            validate_input=False,
            name='cont',
            binds={'/host-0': {'bind': '/container-0', 'ro': True}},
            volumes=['/container-0'],
            validate_ip_addrs=False,
            client_timeout=60)
        dockerng_start.assert_called_with('cont')
Exemple #21
0
 def test_network_present(self):
     '''
     Test dockerng.network_present
     '''
     dockerng_create_network = Mock(return_value='created')
     dockerng_connect_container_to_network = Mock(return_value='connected')
     dockerng_inspect_container = Mock(return_value={'Id': 'abcd'})
     __salt__ = {'dockerng.create_network': dockerng_create_network,
                 'dockerng.inspect_container': dockerng_inspect_container,
                 'dockerng.connect_container_to_network': dockerng_connect_container_to_network,
                 'dockerng.networks': Mock(return_value=[]),
                 }
     with patch.dict(dockerng_state.__dict__,
                     {'__salt__': __salt__}):
         ret = dockerng_state.network_present(
             'network_foo',
             containers=['container'],
             )
     dockerng_create_network.assert_called_with('network_foo', driver=None)
     dockerng_connect_container_to_network.assert_called_with('abcd',
                                                              'network_foo')
     self.assertEqual(ret, {'name': 'network_foo',
                            'comment': '',
                            'changes': {'connected': 'connected',
                                        'created': 'created'},
                            'result': True})
Exemple #22
0
    def test_running_with_predifined_volume(self):
        '''
        Test dockerng.running function with an image
        that already have VOLUME defined.

        The ``binds`` argument, shouldn't have side effects on
        container creation.
        '''
        dockerng_create = Mock()
        dockerng_start = Mock()
        dockerng_history = MagicMock(return_value=['VOLUME /container-0'])
        __salt__ = {'dockerng.list_containers': MagicMock(),
                    'dockerng.list_tags': MagicMock(),
                    'dockerng.pull': MagicMock(),
                    'dockerng.state': MagicMock(),
                    'dockerng.inspect_image': MagicMock(),
                    'dockerng.create': dockerng_create,
                    'dockerng.start': dockerng_start,
                    'dockerng.history': dockerng_history,
                    }
        with patch.dict(dockerng_state.__dict__,
                        {'__salt__': __salt__}):
            dockerng_state.running(
                'cont',
                image='image:latest',
                binds=['/host-0:/container-0:ro'])
        dockerng_create.assert_called_with(
            'image:latest',
            validate_input=False,
            binds={'/host-0': {'bind': '/container-0', 'ro': True}},
            validate_ip_addrs=False,
            name='cont',
            client_timeout=60)
        dockerng_start.assert_called_with('cont')
Exemple #23
0
 def test_volume_present_with_another_driver(self):
     '''
     Test dockerng.volume_present
     '''
     dockerng_create_volume = Mock(return_value='created')
     dockerng_remove_volume = Mock(return_value='removed')
     __salt__ = {'dockerng.create_volume': dockerng_create_volume,
                 'dockerng.remove_volume': dockerng_remove_volume,
                 'dockerng.volumes': Mock(return_value={
                     'Volumes': [{'Name': 'volume_foo',
                                  'Driver': 'foo'}]}),
                 }
     with patch.dict(dockerng_state.__dict__,
                     {'__salt__': __salt__}):
         ret = dockerng_state.volume_present(
             'volume_foo',
             driver='bar',
             force=True,
             )
     dockerng_remove_volume.assert_called_with('volume_foo')
     dockerng_create_volume.assert_called_with('volume_foo',
                                               driver='bar',
                                               driver_opts=None)
     self.assertEqual(ret, {'name': 'volume_foo',
                            'comment': '',
                            'changes': {'created': 'created',
                                        'removed': 'removed'},
                            'result': True})
Exemple #24
0
    def test_running_with_predifined_ports(self):
        '''
        Test dockerng.running function with an image
        that contains EXPOSE statements.

        The ``port_bindings`` argument, shouldn't have side effect on container
        creation.
        '''
        dockerng_create = Mock()
        dockerng_start = Mock()
        dockerng_history = MagicMock(return_value=['EXPOSE 9797/tcp'])
        __salt__ = {'dockerng.list_containers': MagicMock(),
                    'dockerng.list_tags': MagicMock(),
                    'dockerng.pull': MagicMock(),
                    'dockerng.state': MagicMock(),
                    'dockerng.inspect_image': MagicMock(),
                    'dockerng.create': dockerng_create,
                    'dockerng.start': dockerng_start,
                    'dockerng.history': dockerng_history,
                    }
        with patch.dict(dockerng_state.__dict__,
                        {'__salt__': __salt__}):
            dockerng_state.running(
                'cont',
                image='image:latest',
                port_bindings=['9090:9797/tcp'])
        dockerng_create.assert_called_with(
            'image:latest',
            validate_input=False,
            name='cont',
            port_bindings={9797: [9090]},
            validate_ip_addrs=False,
            client_timeout=60)
        dockerng_start.assert_called_with('cont')
Exemple #25
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'],
     )
Exemple #26
0
 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')
Exemple #27
0
    def test_running_with_predifined_volume(self):
        '''
        Test dockerng.running function with an image
        that already have VOLUME defined.

        The ``binds`` argument, should create a container
        with ``volumes`` extracted from ``binds``.
        '''
        dockerng_create = Mock()
        dockerng_start = Mock()
        dockerng_inspect_image = Mock(return_value={
            'Id': 'abcd',
            'Config': {
                'Config': {
                    'Volumes': ['/host-1']
                }
            },
        })
        __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,
            'dockerng.start': dockerng_start,
        }
        with patch.dict(dockerng_state.__dict__, {'__salt__': __salt__}):
            dockerng_state.running('cont',
                                   image='image:latest',
                                   binds=['/host-0:/container-0:ro'])
        dockerng_create.assert_called_with(
            'image:latest',
            validate_input=False,
            binds={'/host-0': {
                'bind': '/container-0',
                'ro': True
            }},
            volumes=['/container-0'],
            validate_ip_addrs=False,
            name='cont',
            client_timeout=60)
        dockerng_start.assert_called_with('cont')
Exemple #28
0
    def test_image_present_already_local(self):
        '''
        According following sls,

        .. code-block:: yaml

            image:latest:
              dockerng.image_present:
                - force: true

        if ``image:latest`` is already downloaded locally the state
        should not report changes.
        '''
        dockerng_inspect_image = Mock(
            return_value={'Id': 'abcdefghijk'})
        dockerng_pull = Mock(
            return_value={'Layers':
                          {'Already_Pulled': ['abcdefghijk'],
                           'Pulled': []},
                          'Status': 'Image is up to date for image:latest',
                          'Time_Elapsed': 1.1})
        dockerng_list_tags = Mock(
            return_value=['image:latest']
        )
        __salt__ = {'dockerng.list_tags': dockerng_list_tags,
                    'dockerng.pull': dockerng_pull,
                    'dockerng.inspect_image': dockerng_inspect_image,
                    }
        with patch.dict(dockerng_state.__dict__,
                        {'__salt__': __salt__}):
            ret = dockerng_state.image_present('image:latest', force=True)
            self.assertEqual(ret,
                             {'changes': {},
                              'result': True,
                              'comment': "Image 'image:latest' was pulled, "
                              "but there were no changes",
                              'name': 'image:latest',
                              })
Exemple #29
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={},
     )
Exemple #30
0
 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(docker_mod.__dict__, {'__salt__': __salt__}):
         with patch.dict(docker_mod.__context__, {'docker.client': client}):
             self.assertRaises(
                 SaltInvocationError,
                 docker_mod.create,
                 'image',
                 name='ctn',
                 labels=22,
                 validate_input=True,
             )
Exemple #31
0
 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')
Exemple #32
0
 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')
Exemple #33
0
 def test_services(self):
     '''
     Tests services listing.
     :return:
     '''
     with patch(
             'salt.modules.kubernetes.kubernetes') as mock_kubernetes_lib:
         with patch.dict(kubernetes.__salt__,
                         {'config.option': Mock(return_value="")}):
             mock_kubernetes_lib.client.CoreV1Api.return_value = Mock(
                 **{
                     "list_namespaced_service.return_value.to_dict.return_value":
                     {
                         'items': [{
                             'metadata': {
                                 'name': 'mock_service_name'
                             }
                         }]
                     }
                 })
             self.assertEqual(kubernetes.services(), ['mock_service_name'])
             self.assertTrue(kubernetes.kubernetes.client.CoreV1Api().
                             list_namespaced_service().to_dict.called)
Exemple #34
0
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,
            })

    @patch('salt.modules.nginx._urlopen',
           Mock(return_value=MockUrllibStatus()))
    def test_nginx_status_with_arg(self):
        other_path = 'http://localhost/path'
        result = nginx.status(other_path)
        nginx._urlopen.assert_called_once_with(other_path)
Exemple #35
0
    def test_with_startup(self):
        config = {'states': ['device']}

        mock = Mock(
            return_value=
            '* daemon started successfully *\nList of devices attached\nHTC\tdevice',
        )
        with patch.dict(adb.__salt__, {'cmd.run': mock}):
            ret = adb.beacon(config)
            self.assertEqual(ret, [{
                'device': 'HTC',
                'state': 'device',
                'tag': 'device'
            }])
Exemple #36
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'
        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'],
        )
Exemple #37
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'],
     )
Exemple #38
0
    def test_running_with_udp_bindings(self):
        '''
        Check that `ports` contains ports defined from `port_bindings` with
        protocol declaration passed as tuple. As stated by docker-py
        documentation

        https://docker-py.readthedocs.io/en/latest/port-bindings/

        In sls:

        .. code-block:: yaml

            container:
                dockerng.running:
                    - port_bindings:
                        - '9090:9797/udp'

        is equivalent of:

        .. code-block:: yaml

            container:
                dockerng.running:
                    - ports:
                        - 9797/udp
                    - port_bindings:
                        - '9090:9797/udp'
        '''
        dockerng_create = Mock()
        dockerng_start = Mock()
        dockerng_inspect_image = Mock(return_value={
            'Id': 'abcd',
            'Config': {'ExposedPorts': {}}
        })
        __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,
                    'dockerng.start': dockerng_start,
                    }
        with patch.dict(dockerng_state.__dict__,
                        {'__salt__': __salt__}):
            dockerng_state.running(
                'cont',
                image='image:latest',
                port_bindings=['9090:9797/udp'])
        dockerng_create.assert_called_with(
            'image:latest',
            validate_input=False,
            name='cont',
            ports=[(9797, 'udp')],
            port_bindings={'9797/udp': [9090]},
            validate_ip_addrs=False,
            client_timeout=60)
        dockerng_start.assert_called_with('cont')
Exemple #39
0
 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,
                               )
Exemple #40
0
    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 #41
0
    def test_weird_batteries(self):
        config = {'states': ['device'], 'battery_low': 25}

        out = [
            'List of devices attached\nHTC\tdevice',
            '-9000',
        ]
        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'
            }])
Exemple #42
0
    def test_device_battery_not_found(self):
        config = {'states': ['device'], 'battery_low': 25}

        out = [
            'List of devices attached\nHTC\tdevice',
            '/system/bin/sh: cat: /sys/class/power_supply/*/capacity: No such file or directory',
        ]
        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'
            }])
Exemple #43
0
    def test_running_with_no_predifined_ports(self):
        '''
        Test dockerng.running function with an image
        that doens't have EXPOSE defined.

        The ``port_bindings`` argument, should create a container
        with ``ports`` extracted from ``port_bindings``.
        '''
        dockerng_create = Mock()
        dockerng_start = Mock()
        dockerng_inspect_image = Mock(return_value={
            'Id': 'abcd',
            'Config': {
                'Config': {
                    'ExposedPorts': {}
                }
            },
        })
        __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,
            'dockerng.start': dockerng_start,
        }
        with patch.dict(dockerng_state.__dict__, {'__salt__': __salt__}):
            with patch.dict(dockerng_mod.__salt__,
                            {'dockerng.version': MagicMock(return_value={})}):
                dockerng_state.running('cont',
                                       image='image:latest',
                                       port_bindings=['9090:9797/tcp'])
        dockerng_create.assert_called_with('image:latest',
                                           validate_input=False,
                                           name='cont',
                                           ports=[9797],
                                           port_bindings={9797: [9090]},
                                           validate_ip_addrs=False,
                                           client_timeout=60)
        dockerng_start.assert_called_with('cont')
Exemple #44
0
    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={},
        )
Exemple #45
0
    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')
Exemple #46
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)
Exemple #47
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'},
                       'Image': image_id})
     __salt__ = {'dockerng.list_containers': dockerng_list_containers,
                 'dockerng.inspect_container': dockerng_inspect_container,
                 'dockerng.inspect_image': MagicMock(
                     return_value={'Id': image_id}),
                 'dockerng.list_tags': MagicMock(),
                 'dockerng.pull': MagicMock(),
                 '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'}},
                            'result': True,
                            })
Exemple #48
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={},
     )
 def add_process(self,
                 pid=100,
                 cmd='cmd',
                 name='name',
                 user='******',
                 user_domain='domain',
                 get_owner_result=0):
     process = Mock()
     process.GetOwner = Mock(return_value=(user_domain, get_owner_result,
                                           user))
     process.ProcessId = pid
     process.CommandLine = cmd
     process.Name = name
     self.__processes.append(process)
Exemple #50
0
    def test_screen_state_change(self):
        config = {'screen_event': True, 'user': '******'}

        mock = Mock(side_effect=[255, 0])
        with patch.dict(glxinfo.__salt__, {'cmd.retcode': mock}):
            ret = glxinfo.beacon(config)
            self.assertEqual(ret, [{
                'tag': 'screen_event',
                'screen_available': False
            }])

            ret = glxinfo.beacon(config)
            self.assertEqual(ret, [{
                'tag': 'screen_event',
                'screen_available': True
            }])
Exemple #51
0
 def test_volume_present_with_another_driver(self):
     '''
     Test dockerng.volume_present
     '''
     dockerng_create_volume = Mock(return_value='created')
     dockerng_remove_volume = Mock(return_value='removed')
     __salt__ = {
         'dockerng.create_volume':
         dockerng_create_volume,
         'dockerng.remove_volume':
         dockerng_remove_volume,
         'dockerng.volumes':
         Mock(return_value={
             'Volumes': [{
                 'Name': 'volume_foo',
                 'Driver': 'foo'
             }]
         }),
     }
     with patch.dict(dockerng_state.__dict__, {'__salt__': __salt__}):
         ret = dockerng_state.volume_present(
             'volume_foo',
             driver='bar',
             force=True,
         )
     dockerng_remove_volume.assert_called_with('volume_foo')
     dockerng_create_volume.assert_called_with('volume_foo',
                                               driver='bar',
                                               driver_opts=None)
     self.assertEqual(
         ret, {
             'name': 'volume_foo',
             'comment': '',
             'changes': {
                 'created': 'created',
                 'removed': 'removed'
             },
             'result': True
         })
Exemple #52
0
 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
                                  }
                              }})
Exemple #53
0
 def test_network_absent(self):
     '''
     Test dockerng.network_absent
     '''
     dockerng_remove_network = Mock(return_value='removed')
     dockerng_disconnect_container_from_network = Mock(return_value='disconnected')
     __salt__ = {'dockerng.remove_network': dockerng_remove_network,
                 'dockerng.disconnect_container_from_network': dockerng_disconnect_container_from_network,
                 'dockerng.networks': Mock(return_value=[{'Containers': {'container': {}}}]),
                 }
     with patch.dict(dockerng_state.__dict__,
                     {'__salt__': __salt__}):
         ret = dockerng_state.network_absent(
             'network_foo',
             )
     dockerng_disconnect_container_from_network.assert_called_with('container',
                                                                   'network_foo')
     dockerng_remove_network.assert_called_with('network_foo')
     self.assertEqual(ret, {'name': 'network_foo',
                            'comment': '',
                            'changes': {'disconnected': 'disconnected',
                                        'removed': 'removed'},
                            'result': True})
Exemple #54
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 #55
0
 def test_version_parse_problem(self, popen_mock):
     '''
     Test with invalid context data. The context value must be a dict, so
     this should raise a SaltInvocationError.
     '''
     popen_mock.return_value = Mock(
         communicate=lambda *args, **kwargs: ('invalid', None),
         pid=lambda: 12345,
         retcode=0
     )
     # Test without context dict passed
     self.assertIsNone(_systemd.version())
     # 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.assertIsNone(_systemd.version(context))
     self.assertEqual(context, {})
Exemple #56
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 #57
0
 def test_network_present(self):
     '''
     Test dockerng.network_present
     '''
     dockerng_create_network = Mock(return_value='created')
     dockerng_connect_container_to_network = Mock(return_value='connected')
     __salt__ = {'dockerng.create_network': dockerng_create_network,
                 'dockerng.connect_container_to_network': dockerng_connect_container_to_network,
                 'dockerng.networks': Mock(return_value=[]),
                 }
     with patch.dict(dockerng_state.__dict__,
                     {'__salt__': __salt__}):
         ret = dockerng_state.network_present(
             'network_foo',
             containers=['container'],
             )
     dockerng_create_network.assert_called_with('network_foo', driver=None)
     dockerng_connect_container_to_network.assert_called_with('container',
                                                              'network_foo')
     self.assertEqual(ret, {'name': 'network_foo',
                            'comment': '',
                            'changes': {'connected': 'connected',
                                        'created': 'created'},
                            'result': True})
Exemple #58
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 #59
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 #60
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'
            }])