Example #1
0
    def generate_settings(entry_point, nested_args, delimiter='-'):
        """Unifies all input into a single dict of Ansible extra-vars

        :param entry_point: All input will be nested under this key
        :param nested_args: dict. these values will be nested
            example:
                {
                    foo-bar: value1,
                    foo2: value2
                    foo-another-bar: value3
                }
        :param delimiter: character to split keys by.
        :return: dict. nest input with keys splitted by delimiter

        >>> VarsDictManager.generate_settings(
        ... 'entry_point', {'foo-bar': 'value1',
        ...                 'foo2': 'value2',
        ...                 'foo-another-bar': 'value3'})
        {'entry_point': {'foo': {'bar': 'value1', 'another':\
 {'bar': 'value3'}}, 'foo2': 'value2'}}
        """
        vars_dict = {entry_point: {}}
        try:
            for _name, argument in nested_args.items():
                dict_utils.dict_insert(vars_dict[entry_point], argument,
                                       *_name.split(delimiter))

        # handle errors here and provide more output for user if required
        except exceptions.IRKeyNotFoundException as key_exception:
            if key_exception and key_exception.key.startswith("private."):
                raise exceptions.IRPrivateSettingsMissingException(
                    key_exception.key)
            else:
                raise
        return vars_dict
Example #2
0
    def resolve(self, value):
        if isinstance(value, str):
            value = value.split(',')

        results_dict = {}
        for item in value:
            item = item.strip()
            key, _value = item.split('=')
            dict_utils.dict_insert(results_dict, _value, *key.split("."))
        return results_dict
Example #3
0
    def resolve(self, value):
        if isinstance(value, str):
            value = value.split(',')

        results_dict = {}
        for item in value:
            item = item.strip()
            key, _value = item.split('=')
            dict_utils.dict_insert(results_dict, _value, *key.split("."))
        return results_dict
Example #4
0
    def _resolve(self, value):
        if isinstance(value, string_types):
            value = value.split(',')

        results_dict = {}
        for item in value:
            data = item.strip().split('=')
            if len(data) > 2:
                raise ValueError(
                    'Wrong number of arguments are provided {}'.format(data))
            key, _value = data
            dict_utils.dict_insert(results_dict, _value, *key.split("."))
        return results_dict
Example #5
0
    def _resolve(self, value, skip_nested_split=False):
        if isinstance(value, string_types):
            value = value.split(',')

        results_dict = {}
        for item in value:
            data = item.strip().split('=')
            if len(data) > 2:
                raise ValueError(
                    'Wrong number of arguments are provided {}'.format(data))
            key, _value = data
            if skip_nested_split:
                dict_utils.dict_insert(results_dict, _value, key)
            else:
                dict_utils.dict_insert(results_dict, _value, *key.split('.'))
        return results_dict
Example #6
0
    def _resolve(self, value, skip_nested_split=False):
        if isinstance(value, string_types):
            value = value.split(',')

        results_dict = {}
        for item in value:
            data = item.strip().split('=', 1)
            if len(data) > 2:
                raise ValueError(
                    'Wrong number of arguments are provided {}'.format(data))
            key, _value = data
            if skip_nested_split:
                dict_utils.dict_insert(results_dict, _value, key)
            else:
                # allow escaping the . (dot) in key of nested dictionaries
                keys = [k.replace('\\', '')
                        for k in re.split(r'(?<!\\)\.', key)]
                dict_utils.dict_insert(results_dict, _value, *keys)
        return results_dict
Example #7
0
def test_remove_plugin(plugin_manager_fixture):
    """ Tests the ability to remove a plugin

    :param plugin_manager_fixture: Fixture object which yields
    InfraredPluginManger object
    """

    plugins_conf = {}
    for plugin_dir in ('type1_plugin1', 'type1_plugin2', 'type2_plugin1'):
        plugin_dict = get_plugin_spec_flatten_dict(
            os.path.join(os.path.abspath(SAMPLE_PLUGINS_DIR), plugin_dir))
        dict_insert(
            plugins_conf,
            plugin_dict['dir'],
            plugin_dict['type'],
            plugin_dict['name'],
        )

    plugin_manager = plugin_manager_fixture(plugins_conf)

    for plugin_dir, plugins_cnt in (('type1_plugin1', 2), ('type2_plugin1', 1),
                                    ('type1_plugin2', 0)):
        plugin_dict = get_plugin_spec_flatten_dict(
            os.path.join(SAMPLE_PLUGINS_DIR, plugin_dir))

        assert plugin_dict['name'] in plugin_manager.PLUGINS_DICT, \
            "Can't remove unexisting plugin"

        plugin_manager.remove_plugin(plugin_dict['name'])

        with pytest.raises(KeyError):
            plugin_manager.get_plugin(plugin_name=plugin_dict['name'])

        assert not plugin_in_conf(
            plugins_conf=plugin_manager.config_file,
            plugin_type=plugin_dict['type'],
            plugin_name=plugin_dict['name']), \
            "Plugin wasn't removed from conf file."
        assert len(plugin_manager.PLUGINS_DICT) == plugins_cnt
Example #8
0
def test_remove_plugin(plugin_manager_fixture):
    """ Tests the ability to remove a plugin

    :param plugin_manager_fixture: Fixture object which yields
    InfraredPluginManger object
    """

    plugins_conf = {}
    for plugin_dir in ('type1_plugin1', 'type1_plugin2', 'type2_plugin1'):
        plugin_dict = get_plugin_spec_flatten_dict(
            os.path.join(os.path.abspath(SAMPLE_PLUGINS_DIR), plugin_dir))
        dict_insert(plugins_conf,
                    plugin_dict['dir'],
                    plugin_dict['type'],
                    plugin_dict['name'],)

    plugin_manager = plugin_manager_fixture(plugins_conf)

    for plugin_dir, plugins_cnt in (
            ('type1_plugin1', 2),
            ('type2_plugin1', 1),
            ('type1_plugin2', 0)):
        plugin_dict = get_plugin_spec_flatten_dict(
            os.path.join(SAMPLE_PLUGINS_DIR, plugin_dir))

        assert plugin_dict['name'] in plugin_manager.PLUGINS_DICT, \
            "Can't remove unexisting plugin"

        plugin_manager.remove_plugin(plugin_dict['name'])

        with pytest.raises(KeyError):
            plugin_manager.get_plugin(plugin_name=plugin_dict['name'])

        assert not plugin_in_conf(
            plugins_conf=plugin_manager.config_file,
            plugin_type=plugin_dict['type'],
            plugin_name=plugin_dict['name']), \
            "Plugin wasn't removed from conf file."
        assert len(plugin_manager.PLUGINS_DICT) == plugins_cnt
Example #9
0
    def merge_extra_vars(vars_dict, extra_vars=None):
        """Extend ``vars_dict`` with ``extra-vars``

        :param vars_dict: Dictionary to merge extra-vars into
        :param extra_vars: List of extra-vars
        """
        for extra_var in extra_vars or []:
            if extra_var.startswith('@'):
                with open(extra_var[1:]) as f_obj:
                    loaded_yml = yaml.load(f_obj)

                dict_utils.dict_merge(
                    vars_dict,
                    loaded_yml,
                    conflict_resolver=dict_utils.ConflictResolver.
                    unique_append_list_resolver)

            else:
                if '=' not in extra_var:
                    raise exceptions.IRExtraVarsException(extra_var)
                key, value = extra_var.split("=")
                dict_utils.dict_insert(vars_dict, value, *key.split("."))
Example #10
0
    def generate_settings(entry_point,
                          nested_args,
                          delimiter='-'):
        """Unifies all input into a single dict of Ansible extra-vars

        :param entry_point: All input will be nested under this key
        :param nested_args: dict. these values will be nested
            example:
                {
                    foo-bar: value1,
                    foo2: value2
                    foo-another-bar: value3
                }
        :param delimiter: character to split keys by.
        :return: dict. nest input with keys splitted by delimiter

        >>> VarsDictManager.generate_settings(
        ... 'entry_point', {'foo-bar': 'value1',
        ...                 'foo2': 'value2',
        ...                 'foo-another-bar': 'value3'})
        {'entry_point': {'foo': {'bar': 'value1', 'another':\
 {'bar': 'value3'}}, 'foo2': 'value2'}}
        """
        vars_dict = {entry_point: {}}
        try:
            for _name, argument in nested_args.items():
                dict_utils.dict_insert(vars_dict[entry_point],
                                       argument,
                                       *_name.split(delimiter))

        # handle errors here and provide more output for user if required
        except exceptions.IRKeyNotFoundException as key_exception:
            if key_exception and key_exception.key.startswith("private."):
                raise exceptions.IRPrivateSettingsMissingException(
                    key_exception.key)
            else:
                raise
        return vars_dict
Example #11
0
def test_dict_insert(tested, val, key, expected):
    from infrared.core.utils import dict_utils
    dict_utils.dict_insert(tested, val, *key)
    assert tested == expected
Example #12
0
def test_dict_insert(tested, val, key, expected):
    from infrared.core.utils import dict_utils
    dict_utils.dict_insert(tested, val, *key)
    assert tested == expected