How to use the salt.ext.six.text_type function in salt

To help you get started, we’ve selected a few salt examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github saltstack / salt / tests / integration / shell / test_key.py View on Github external
def _add_user(self):
        '''
        helper method to add user
        '''
        try:
            add_user = self.run_call('user.add {0} createhome=False'.format(USERA))
            add_pwd = self.run_call('shadow.set_password {0} \'{1}\''.format(USERA,
                                    USERA_PWD if salt.utils.platform.is_darwin() else HASHED_USERA_PWD))
            self.assertTrue(add_user)
            self.assertTrue(add_pwd)
            user_list = self.run_call('user.list_users')
            self.assertIn(USERA, six.text_type(user_list))
        except AssertionError:
            self.run_call('user.delete {0} remove=True'.format(USERA))
            self.skipTest(
                'Could not add user or password, skipping test'
                )
github saltstack / salt / tests / unit / utils / test_ssdp.py View on Github external
def test_get_masters_map_error_handling(self):
        '''
        Test getting map handles timeout network exception
        :return:
        '''
        _socket = MagicMock()
        response = {}
        error_msg = 'fake testing timeout just had happened'
        with patch('salt.utils.ssdp.socket', _socket):
            clnt = ssdp.SSDPDiscoveryClient()
            clnt._socket.recvfrom = MagicMock(side_effect=Exception(error_msg))
            clnt.log = MagicMock()
            clnt._collect_masters_map(response=response)
            assert clnt.log.error.called
            assert 'Discovery master collection failure' in clnt.log.error.call_args[0][0]
            assert error_msg == six.text_type(clnt.log.error.call_args[0][1])
            assert not response
github saltstack / salt / tests / unit / modules / test_localemod.py View on Github external
def test_set_locale_with_no_systemd_unknown(self):
        '''
        Test setting current system locale without systemd on unknown system.
        :return:
        '''
        with pytest.raises(CommandExecutionError) as err:
            localemod.set_locale('de_DE.utf8')
        assert 'Unsupported platform' in six.text_type(err.value)
github saltstack / salt / salt / returners / elasticsearch_return.py View on Github external
if job_fun in STATE_FUNCTIONS:
        # Init the state counts
        if options['states_count']:
            counts = {
                'suceeded': 0,
                'failed':   0,
            }

        # Prepend each state execution key in ret['return'] with a zero-padded
        # version of the '__run_num__' field allowing the states to be ordered
        # more easily. Change the index to be
        # index to be '-ordered' so as not to clash with the unsorted
        # index data format
        if options['states_order_output'] and isinstance(ret['return'], dict):
            index = '{0}-ordered'.format(index)
            max_chars = len(six.text_type(len(ret['return'])))

            for uid, data in six.iteritems(ret['return']):
                # Skip keys we've already prefixed
                if uid.startswith(tuple('0123456789')):
                    continue

                # Store the function being called as it's a useful key to search
                decoded_uid = uid.split('_|-')
                ret['return'][uid]['_func'] = '{0}.{1}'.format(
                    decoded_uid[0],
                    decoded_uid[-1]
                )

                # Prefix the key with the run order so it can be sorted
                new_uid = '{0}_|-{1}'.format(
                    six.text_type(data['__run_num__']).zfill(max_chars),
github saltstack / salt / salt / output / highstate.py View on Github external
clikwargs = {}
                for item in cliargs:
                    if isinstance(item, dict) and '__kwarg__' in item:
                        clikwargs = item.copy()

                exclude = clikwargs.get(
                    'exclude', __opts__.get('state_output_exclude', [])
                )
                if isinstance(exclude, six.string_types):
                    exclude = six.text_type(exclude).split(',')

                terse = clikwargs.get(
                    'terse', __opts__.get('state_output_terse', [])
                )
                if isinstance(terse, six.string_types):
                    terse = six.text_type(terse).split(',')

                if six.text_type(ret['result']) in terse:
                    msg = _format_terse(tcolor, comps, ret, colors, tabular)
                    hstrs.append(msg)
                    continue
                if six.text_type(ret['result']) in exclude:
                    continue

            elif any((
                state_output.startswith('terse'),
                state_output.startswith('mixed') and ret['result'] is not False,  # only non-error'd
                state_output.startswith('changes') and ret['result'] and not schanged  # non-error'd non-changed
            )):
                # Print this chunk in a terse way and continue in the loop
                msg = _format_terse(tcolor, comps, ret, colors, tabular)
                hstrs.append(msg)
github saltstack / salt / salt / modules / saltcheck.py View on Github external
def __assert_less(expected, returned):
        '''
        Test if a value is less than the returned value
        '''
        result = "Pass"
        try:
            assert (expected < returned), "{0} not False".format(returned)
        except AssertionError as err:
            result = "Fail: " + six.text_type(err)
        return result
github saltstack / salt / salt / states / openvswitch_port.py View on Github external
def _check_vxlan():
        interface_options = __salt__['openvswitch.interface_get_options'](name)
        interface_type = __salt__['openvswitch.interface_get_type'](name)
        if not 0 <= id <= 2**64:
            ret['result'] = False
            ret['comment'] = comments['comment_vxlan_invalid_id']
        elif not __salt__['dig.check_ip'](remote):
            ret['result'] = False
            ret['comment'] = comments['comment_invalid_ip']
        elif interface_options and interface_type and name in port_list:
            opt_port = 'dst_port=\"' + six.text_type(dst_port) + '\", ' if 0 < dst_port <= 65535 else ''
            interface_attroptions = '{{{0}key=\"'.format(opt_port) + six.text_type(id) + '\", remote_ip=\"' + six.text_type(remote) + '\"}'
            try:
                if interface_type[0] == 'vxlan' and interface_options[0] == interface_attroptions:
                    ret['result'] = True
                    ret['comment'] = comments['comment_vxlan_interface_exists']
            except KeyError:
                pass
github saltstack / salt / salt / modules / nilrt_ip.py View on Github external
def _dict_to_string(dictionary):
    '''
    converts a dictionary object into a list of strings
    '''
    ret = ''
    for key, val in sorted(dictionary.items()):
        if isinstance(val, dict):
            for line in _dict_to_string(val):
                ret += six.text_type(key) + '-' + line + '\n'
        elif isinstance(val, list):
            text = ' '.join([six.text_type(item) for item in val])
            ret += six.text_type(key) + ': ' + text + '\n'
        else:
            ret += six.text_type(key) + ': ' + six.text_type(val) + '\n'
    return ret.splitlines()
github saltstack / salt / salt / modules / apache.py View on Github external
:param conf: defined config structure
    :param slot: name of section container if needed
    '''
    ret = cStringIO()
    if isinstance(conf, six.string_types):
        if slot:
            print('{0} {1}'.format(slot, conf), file=ret, end='')
        else:
            print('{0}'.format(conf), file=ret, end='')
    elif isinstance(conf, list):
        is_section = False
        for item in conf:
            if 'this' in item:
                is_section = True
                slot_this = six.text_type(item['this'])
        if is_section:
            print('<{0} {1}>'.format(slot, slot_this), file=ret)
            for item in conf:
                for key, val in item.items():
                    if key != 'this':
                        print(_parse_config(val, six.text_type(key)), file=ret)
            print(''.format(slot), file=ret)
        else:
            for value in conf:
                print(_parse_config(value, six.text_type(slot)), file=ret)
    elif isinstance(conf, dict):
        try:
            print('<{0} {1}>'.format(slot, conf['this']), file=ret)
        except KeyError:
            raise SaltException('Apache section container "<{0}>" expects attribute. '
                                'Specify it using key "this".'.format(slot))
github saltstack / salt / salt / cloud / clouds / aliyun.py View on Github external
def get_image(vm_):
    '''
    Return the image object to use
    '''
    images = avail_images()
    vm_image = six.text_type(config.get_cloud_config_value(
        'image', vm_, __opts__, search_global=False
    ))

    if not vm_image:
        raise SaltCloudNotFound('No image specified for this VM.')

    if vm_image and six.text_type(vm_image) in images:
        return images[vm_image]['ImageId']
    raise SaltCloudNotFound(
        'The specified image, \'{0}\', could not be found.'.format(vm_image)
    )