Пример #1
0
def test_handle_aliases_type_error():
    argument_spec = {
        'name': {
            'type': 'str',
            'aliases': 'surname'
        },
    }

    params = {
        'name': 'foo',
    }

    with pytest.raises(TypeError) as te:
        _handle_aliases(argument_spec, params)
        assert 'internal error: required and default are mutually exclusive' in to_native(
            te.error)
Пример #2
0
def test_handle_aliases_value_error():
    argument_spec = {
        'name': {
            'type': 'str',
            'aliases': ['surname', 'nick'],
            'default': 'bob',
            'required': True
        },
    }

    params = {
        'name': 'foo',
    }

    with pytest.raises(ValueError) as ve:
        _handle_aliases(argument_spec, params)
        assert 'internal error: aliases must be a list or tuple' == to_native(
            ve.error)
Пример #3
0
def test_handle_aliases_no_aliases():
    argument_spec = {
        'name': {
            'type': 'str'
        },
    }

    params = {'name': 'foo', 'path': 'bar'}

    expected = {}
    result = _handle_aliases(argument_spec, params)

    assert expected == result
Пример #4
0
def test_handle_aliases_basic():
    argument_spec = {
        'name': {
            'type': 'str',
            'aliases': ['surname', 'nick']
        },
    }

    params = {
        'name': 'foo',
        'path': 'bar',
        'surname': 'foo',
        'nick': 'foo',
    }

    expected = {'surname': 'name', 'nick': 'name'}
    result = _handle_aliases(argument_spec, params)

    assert expected == result
Пример #5
0
    def validate(self, parameters, *args, **kwargs):
        """Validate ``parameters`` against argument spec.

        Error messages in the :class:`ValidationResult` may contain no_log values and should be
        sanitized with :func:`~ansible.module_utils.common.parameters.sanitize_keys` before logging or displaying.

        :arg parameters: Parameters to validate against the argument spec
        :type parameters: dict[str, dict]

        :return: :class:`ValidationResult` containing validated parameters.

        :Simple Example:

            .. code-block:: text

                argument_spec = {
                    'name': {'type': 'str'},
                    'age': {'type': 'int'},
                }

                parameters = {
                    'name': 'bo',
                    'age': '42',
                }

                validator = ArgumentSpecValidator(argument_spec)
                result = validator.validate(parameters)

                if result.error_messages:
                    sys.exit("Validation failed: {0}".format(", ".join(result.error_messages))

                valid_params = result.validated_parameters
        """

        result = ValidationResult(parameters)

        result._no_log_values.update(
            set_fallbacks(self.argument_spec, result._validated_parameters))

        alias_warnings = []
        alias_deprecations = []
        try:
            result._aliases.update(
                _handle_aliases(self.argument_spec,
                                result._validated_parameters, alias_warnings,
                                alias_deprecations))
        except (TypeError, ValueError) as e:
            result.errors.append(AliasError(to_native(e)))

        legal_inputs = _get_legal_inputs(self.argument_spec,
                                         result._validated_parameters,
                                         result._aliases)

        for option, alias in alias_warnings:
            result._warnings.append({'option': option, 'alias': alias})

        for deprecation in alias_deprecations:
            result._deprecations.append({
                'name':
                deprecation['name'],
                'version':
                deprecation.get('version'),
                'date':
                deprecation.get('date'),
                'collection_name':
                deprecation.get('collection_name'),
            })

        try:
            result._no_log_values.update(
                _list_no_log_values(self.argument_spec,
                                    result._validated_parameters))
        except TypeError as te:
            result.errors.append(NoLogError(to_native(te)))

        try:
            result._unsupported_parameters.update(
                _get_unsupported_parameters(self.argument_spec,
                                            result._validated_parameters,
                                            legal_inputs))
        except TypeError as te:
            result.errors.append(RequiredDefaultError(to_native(te)))
        except ValueError as ve:
            result.errors.append(AliasError(to_native(ve)))

        try:
            check_mutually_exclusive(self._mutually_exclusive,
                                     result._validated_parameters)
        except TypeError as te:
            result.errors.append(MutuallyExclusiveError(to_native(te)))

        result._no_log_values.update(
            _set_defaults(self.argument_spec, result._validated_parameters,
                          False))

        try:
            check_required_arguments(self.argument_spec,
                                     result._validated_parameters)
        except TypeError as e:
            result.errors.append(RequiredError(to_native(e)))

        _validate_argument_types(self.argument_spec,
                                 result._validated_parameters,
                                 errors=result.errors)
        _validate_argument_values(self.argument_spec,
                                  result._validated_parameters,
                                  errors=result.errors)

        for check in _ADDITIONAL_CHECKS:
            try:
                check['func'](getattr(self,
                                      "_{attr}".format(attr=check['attr'])),
                              result._validated_parameters)
            except TypeError as te:
                result.errors.append(check['err'](to_native(te)))

        result._no_log_values.update(
            _set_defaults(self.argument_spec, result._validated_parameters))

        _validate_sub_spec(
            self.argument_spec,
            result._validated_parameters,
            errors=result.errors,
            no_log_values=result._no_log_values,
            unsupported_parameters=result._unsupported_parameters)

        if result._unsupported_parameters:
            flattened_names = []
            for item in result._unsupported_parameters:
                if isinstance(item, tuple):
                    flattened_names.append(".".join(item))
                else:
                    flattened_names.append(item)

            unsupported_string = ", ".join(sorted(list(flattened_names)))
            supported_string = ", ".join(self._valid_parameter_names)
            result.errors.append(
                UnsupportedError(
                    "{0}. Supported parameters include: {1}.".format(
                        unsupported_string, supported_string)))

        return result
Пример #6
0
    def validate(self, parameters, *args, **kwargs):
        """Validate module parameters against argument spec. Returns a
        ValidationResult object.

        Error messages in the ValidationResult may contain no_log values and should be
        sanitized before logging or displaying.

        :Example:

        validator = ArgumentSpecValidator(argument_spec)
        result = validator.validate(parameters)

        if result.error_messages:
            sys.exit("Validation failed: {0}".format(", ".join(result.error_messages))

        valid_params = result.validated_parameters

        :param argument_spec: Specification of parameters, type, and valid values
        :type argument_spec: dict

        :param parameters: Parameters provided to the role
        :type parameters: dict

        :return: Object containing validated parameters.
        :rtype: ValidationResult
        """

        result = ValidationResult(parameters)

        result._no_log_values.update(
            set_fallbacks(self.argument_spec, result._validated_parameters))

        alias_warnings = []
        alias_deprecations = []
        try:
            aliases = _handle_aliases(self.argument_spec,
                                      result._validated_parameters,
                                      alias_warnings, alias_deprecations)
        except (TypeError, ValueError) as e:
            aliases = {}
            result.errors.append(AliasError(to_native(e)))

        legal_inputs = _get_legal_inputs(self.argument_spec,
                                         result._validated_parameters, aliases)

        for option, alias in alias_warnings:
            result._warnings.append({'option': option, 'alias': alias})

        for deprecation in alias_deprecations:
            result._deprecations.append({
                'name':
                deprecation['name'],
                'version':
                deprecation.get('version'),
                'date':
                deprecation.get('date'),
                'collection_name':
                deprecation.get('collection_name'),
            })

        try:
            result._no_log_values.update(
                _list_no_log_values(self.argument_spec,
                                    result._validated_parameters))
        except TypeError as te:
            result.errors.append(NoLogError(to_native(te)))

        try:
            result._unsupported_parameters.update(
                _get_unsupported_parameters(self.argument_spec,
                                            result._validated_parameters,
                                            legal_inputs))
        except TypeError as te:
            result.errors.append(RequiredDefaultError(to_native(te)))
        except ValueError as ve:
            result.errors.append(AliasError(to_native(ve)))

        try:
            check_mutually_exclusive(self._mutually_exclusive,
                                     result._validated_parameters)
        except TypeError as te:
            result.errors.append(MutuallyExclusiveError(to_native(te)))

        result._no_log_values.update(
            _set_defaults(self.argument_spec, result._validated_parameters,
                          False))

        try:
            check_required_arguments(self.argument_spec,
                                     result._validated_parameters)
        except TypeError as e:
            result.errors.append(RequiredError(to_native(e)))

        _validate_argument_types(self.argument_spec,
                                 result._validated_parameters,
                                 errors=result.errors)
        _validate_argument_values(self.argument_spec,
                                  result._validated_parameters,
                                  errors=result.errors)

        for check in _ADDITIONAL_CHECKS:
            try:
                check['func'](getattr(self,
                                      "_{attr}".format(attr=check['attr'])),
                              result._validated_parameters)
            except TypeError as te:
                result.errors.append(check['err'](to_native(te)))

        result._no_log_values.update(
            _set_defaults(self.argument_spec, result._validated_parameters))

        _validate_sub_spec(
            self.argument_spec,
            result._validated_parameters,
            errors=result.errors,
            no_log_values=result._no_log_values,
            unsupported_parameters=result._unsupported_parameters)

        if result._unsupported_parameters:
            flattened_names = []
            for item in result._unsupported_parameters:
                if isinstance(item, tuple):
                    flattened_names.append(".".join(item))
                else:
                    flattened_names.append(item)

            unsupported_string = ", ".join(sorted(list(flattened_names)))
            supported_string = ", ".join(self._valid_parameter_names)
            result.errors.append(
                UnsupportedError(
                    "{0}. Supported parameters include: {1}.".format(
                        unsupported_string, supported_string)))

        return result