Exemplo n.º 1
0
    def Push_ItemFromJson(self, item, always_include_optional,
                          process_additional_data):
        item_attributes = set(
            [name for name in six.iterkeys(item) if name[0] != '_'])

        result = Object()

        # url
        try:
            self._ApplyOptionalChild(item, "url", result,
                                     self.Push_url_ItemFromJson,
                                     always_include_optional)
            item_attributes.discard("url")

        except:
            _ProcessException("url")

        # Additional data
        if process_additional_data:
            self._ProcessAdditionalData(item, result, exclude_names={"url"})
        elif item_attributes:
            raise ValidationException(
                "The item contains extraneous data: {}".format(', '.join([
                    "'{}'".format(item_attribute)
                    for item_attribute in item_attributes
                ])))

        Push_TypeInfo.ValidateItem(
            result,
            recurse=False,
            require_exact_match=not process_additional_data,
            exclude_names=["url"])
        return result
Exemplo n.º 2
0
    def _DeserializeItemImpl(type_info, item, **custom_kwargs):
        # custom_kwargs:
        #   type_info type          Key         Value       Default             Desc
        #   ----------------------  ----------  ----------  ------------------  ----------------
        #   DirectoryTypeInfo       normalize   Boolean     True                Applies os.path.realpath and os.path.normpath to the string
        #   FilenameTypeInfo        normalize   Boolean     True                Applies os.path.realpath and os.path.normpath to the string

        regex_strings = RegularExpressionVisitor.Accept(type_info)

        for regex_index, regex_string in enumerate(regex_strings):
            if isinstance(regex_string, tuple):
                regex_string, regex_flags = regex_string
            else:
                regex_flags = re.DOTALL | re.MULTILINE

            if not regex_string.startswith('^'):
                regex_string = "^{}".format(regex_string)
            if not regex_string.endswith('$'):
                regex_string = "{}$".format(regex_string)

            potential_match = re.match(regex_string, item, regex_flags)
            if potential_match:
                return _DeserializationVisitor.Accept(type_info, item, custom_kwargs, potential_match, regex_index)

        # If here, we didn't find anything
        error = "'{}' is not a valid '{}' string".format(item, type_info.Desc)

        if type_info.ConstraintsDesc:
            error += " - {}".format(type_info.ConstraintsDesc)

        raise ValidationException(error)
Exemplo n.º 3
0
    def Pushed_ItemFromJson(self, item, always_include_optional,
                            process_additional_data):
        item_attributes = set(
            [name for name in six.iterkeys(item) if name[0] != '_'])

        result = Object()

        # changes
        try:
            these_items = getattr(item, "get", lambda a, b: b)("changes",
                                                               DoesNotExist)
            if these_items == DoesNotExist:
                these_items = []

            Pushed_changes_TypeInfo.ValidateArity(these_items)

            these_results = []

            for this_index, this_item in enumerate(these_items):
                try:
                    these_results.append(
                        self.Pushed_changes_ItemFromJson(
                            this_item, always_include_optional,
                            process_additional_data))
                except:
                    _ProcessException("Index {}".format(this_index))

            setattr(result, "changes", these_results)
            item_attributes.remove("changes")

        except:
            _ProcessException("changes")

        # Additional data
        if process_additional_data:
            self._ProcessAdditionalData(item,
                                        result,
                                        exclude_names={"changes"})
        elif item_attributes:
            raise ValidationException(
                "The item contains extraneous data: {}".format(', '.join([
                    "'{}'".format(item_attribute)
                    for item_attribute in item_attributes
                ])))

        Pushed_TypeInfo.ValidateItem(
            result,
            recurse=False,
            require_exact_match=not process_additional_data,
            exclude_names=["changes"])
        return result
Exemplo n.º 4
0
    def __call__(self, wrapped, instance, args, kwargs):
        if self._args_to_kwargs_func is None:
            # Create a function that will map all positional arguments into the keyboard map
            if sys.version_info[0] == 2:
                arg_info = inspect.getargspec(wrapped)
            else:
                arg_info = inspect.getfullargspec(wrapped)

            arg_defaults = arg_info.defaults or []
            optional_args = arg_info.args[len(arg_info.args) -
                                          len(arg_defaults):]

            if self.Preconditions:
                first_optional_arg_index = len(
                    arg_info.args) - len(optional_args)

                # Ensure that the precondition names match the function argument names
                precondition_names = set(six.iterkeys(self.Preconditions))
                missing = []

                for index, arg in enumerate(arg_info.args):
                    if arg in precondition_names:
                        precondition_names.remove(arg)
                    elif index < first_optional_arg_index:
                        missing.append(arg)
                    else:
                        # Create a TypeInfo object based on the default
                        default_value = arg_defaults[index -
                                                     first_optional_arg_index]

                        these_kwargs = {
                            "arity": '?',
                        }

                        if default_value == '':
                            these_kwargs["min_length"] = 0

                        self.Preconditions[
                            arg] = CreateFundamentalFromPythonType(
                                type(default_value), **these_kwargs)

                # Capture all errors
                errors = []

                errors += [
                    "A precondition was not provided for '{}'".format(arg)
                    for arg in missing
                ]
                errors += [
                    "A precondition was provided for '{}'".format(arg)
                    for arg in precondition_names
                ]

                if errors:
                    raise Exception(
                        textwrap.dedent("""\
                                        Constraint configuration for '{}' is not valid:
                                        {}
                                        """).format(
                            wrapped,
                            '\n'.join([
                                "    - {}".format(error) for error in errors
                            ]),
                        ))

            # ----------------------------------------------------------------------
            def ArgsToKwargs(args, kwargs):
                # Copy the position args into the kwargs map
                assert len(args) <= len(arg_info.args)

                index = 0
                while index < len(args):
                    kwargs[arg_info.args[index]] = args[index]
                    index += 1

                # Copy the optional args
                for arg, default_value in six.moves.zip(
                        optional_args, arg_defaults):
                    if arg not in kwargs:
                        kwargs[arg] = default_value

                        # Default parameter values in python arg string in that it is better
                        # to provide a None value in the function signature rather than an empty
                        # list when the arity is '*', as that empty list may be modified within
                        # the function itself. However, parameter validation requires an empty list
                        # rather than None. Handle that wonkiness here by providing the actual value.
                        if (default_value is None and arg in self.Preconditions
                                and self.Preconditions[arg] is not None):
                            if self.Preconditions[arg].Arity.IsCollection:
                                kwargs[arg] = []
                            elif isinstance(self.Preconditions[arg],
                                            DictTypeInfo):
                                kwargs[arg] = {}

                return kwargs

            # ----------------------------------------------------------------------

            self._args_to_kwargs_func = ArgsToKwargs

        # Validate the arguments
        kwargs = self._args_to_kwargs_func(args, kwargs)

        if self.Preconditions:
            assert len(kwargs) == len(self.Preconditions)

            for k, v in six.iteritems(kwargs):
                assert k in self.Preconditions, k

                type_info = self.Preconditions[k]
                if type_info is None:
                    continue

                result = type_info.ValidateNoThrow(v)
                if result is not None:
                    raise ValidationException(
                        "Validation for the arg '{}' failed - {}".format(
                            k, result))

        # Invoke the function
        func_result = wrapped(**kwargs)

        # Validate postconditions
        for postcondition in self.Postconditions:
            if postcondition is None:
                continue

            result = postcondition.ValidateNoThrow(func_result)
            if result is not None:
                raise ValidationException(
                    "Validation for the result failed - {}".format(result))

        return func_result
Exemplo n.º 5
0
    def Pushed_changes_ItemFromJson(self, item, always_include_optional,
                                    process_additional_data):
        item_attributes = set(
            [name for name in six.iterkeys(item) if name[0] != '_'])

        result = Object()

        # modified
        try:
            these_items = getattr(item, "get", lambda a, b: b)("modified",
                                                               DoesNotExist)
            if these_items == DoesNotExist:
                these_items = []

            Pushed_changes_modified_TypeInfo.ValidateArity(these_items)

            these_results = []

            for this_index, this_item in enumerate(these_items):
                try:
                    these_results.append(
                        self.Pushed_changes_modified_ItemFromJson(this_item))
                except:
                    _ProcessException("Index {}".format(this_index))

            setattr(result, "modified", these_results)
            item_attributes.discard("modified")

        except:
            _ProcessException("modified")

        # added
        try:
            these_items = getattr(item, "get", lambda a, b: b)("added",
                                                               DoesNotExist)
            if these_items == DoesNotExist:
                these_items = []

            Pushed_changes_added_TypeInfo.ValidateArity(these_items)

            these_results = []

            for this_index, this_item in enumerate(these_items):
                try:
                    these_results.append(
                        self.Pushed_changes_added_ItemFromJson(this_item))
                except:
                    _ProcessException("Index {}".format(this_index))

            setattr(result, "added", these_results)
            item_attributes.discard("added")

        except:
            _ProcessException("added")

        # removed
        try:
            these_items = getattr(item, "get", lambda a, b: b)("removed",
                                                               DoesNotExist)
            if these_items == DoesNotExist:
                these_items = []

            Pushed_changes_removed_TypeInfo.ValidateArity(these_items)

            these_results = []

            for this_index, this_item in enumerate(these_items):
                try:
                    these_results.append(
                        self.Pushed_changes_removed_ItemFromJson(this_item))
                except:
                    _ProcessException("Index {}".format(this_index))

            setattr(result, "removed", these_results)
            item_attributes.discard("removed")

        except:
            _ProcessException("removed")

        # id
        try:
            this_item = getattr(item, "get", lambda a, b: b)("id",
                                                             DoesNotExist)

            ChangeInfo_id_TypeInfo.ValidateArityCount(
                1 if this_item != DoesNotExist else 0)
            setattr(result, "id", self.ChangeInfo_id_ItemFromJson(this_item))
            item_attributes.remove("id")

        except:
            _ProcessException("id")

        # author
        try:
            this_item = getattr(item, "get", lambda a, b: b)("author",
                                                             DoesNotExist)

            ChangeInfo_author_TypeInfo.ValidateArityCount(
                1 if this_item != DoesNotExist else 0)
            setattr(result, "author",
                    self.ChangeInfo_author_ItemFromJson(this_item))
            item_attributes.remove("author")

        except:
            _ProcessException("author")

        # date
        try:
            this_item = getattr(item, "get", lambda a, b: b)("date",
                                                             DoesNotExist)

            ChangeInfo_date_TypeInfo.ValidateArityCount(
                1 if this_item != DoesNotExist else 0)
            setattr(result, "date",
                    self.ChangeInfo_date_ItemFromJson(this_item))
            item_attributes.remove("date")

        except:
            _ProcessException("date")

        # description
        try:
            this_item = getattr(item, "get", lambda a, b: b)("description",
                                                             DoesNotExist)

            ChangeInfo_description_TypeInfo.ValidateArityCount(
                1 if this_item != DoesNotExist else 0)
            setattr(result, "description",
                    self.ChangeInfo_description_ItemFromJson(this_item))
            item_attributes.remove("description")

        except:
            _ProcessException("description")

        # branch
        try:
            this_item = getattr(item, "get", lambda a, b: b)("branch",
                                                             DoesNotExist)

            ChangeInfo_branch_TypeInfo.ValidateArityCount(
                1 if this_item != DoesNotExist else 0)
            setattr(result, "branch",
                    self.ChangeInfo_branch_ItemFromJson(this_item))
            item_attributes.remove("branch")

        except:
            _ProcessException("branch")

        # Additional data
        if process_additional_data:
            self._ProcessAdditionalData(item,
                                        result,
                                        exclude_names={
                                            "modified", "added", "removed",
                                            "id", "author", "date",
                                            "description", "branch"
                                        })
        elif item_attributes:
            raise ValidationException(
                "The item contains extraneous data: {}".format(', '.join([
                    "'{}'".format(item_attribute)
                    for item_attribute in item_attributes
                ])))

        Pushed_changes_TypeInfo.ValidateItem(
            result,
            recurse=False,
            require_exact_match=not process_additional_data,
            exclude_names=[
                "modified", "added", "removed", "id", "author", "date",
                "description", "branch"
            ])
        return result
Exemplo n.º 6
0
    def ChangeInfo_ItemFromJson(self, item, always_include_optional,
                                process_additional_data):
        item_attributes = set(
            [name for name in six.iterkeys(item) if name[0] != '_'])

        result = Object()

        # id
        try:
            this_item = getattr(item, "get", lambda a, b: b)("id",
                                                             DoesNotExist)

            ChangeInfo_id_TypeInfo.ValidateArityCount(
                1 if this_item != DoesNotExist else 0)
            setattr(result, "id", self.ChangeInfo_id_ItemFromJson(this_item))
            item_attributes.remove("id")

        except:
            _ProcessException("id")

        # author
        try:
            this_item = getattr(item, "get", lambda a, b: b)("author",
                                                             DoesNotExist)

            ChangeInfo_author_TypeInfo.ValidateArityCount(
                1 if this_item != DoesNotExist else 0)
            setattr(result, "author",
                    self.ChangeInfo_author_ItemFromJson(this_item))
            item_attributes.remove("author")

        except:
            _ProcessException("author")

        # date
        try:
            this_item = getattr(item, "get", lambda a, b: b)("date",
                                                             DoesNotExist)

            ChangeInfo_date_TypeInfo.ValidateArityCount(
                1 if this_item != DoesNotExist else 0)
            setattr(result, "date",
                    self.ChangeInfo_date_ItemFromJson(this_item))
            item_attributes.remove("date")

        except:
            _ProcessException("date")

        # description
        try:
            this_item = getattr(item, "get", lambda a, b: b)("description",
                                                             DoesNotExist)

            ChangeInfo_description_TypeInfo.ValidateArityCount(
                1 if this_item != DoesNotExist else 0)
            setattr(result, "description",
                    self.ChangeInfo_description_ItemFromJson(this_item))
            item_attributes.remove("description")

        except:
            _ProcessException("description")

        # branch
        try:
            this_item = getattr(item, "get", lambda a, b: b)("branch",
                                                             DoesNotExist)

            ChangeInfo_branch_TypeInfo.ValidateArityCount(
                1 if this_item != DoesNotExist else 0)
            setattr(result, "branch",
                    self.ChangeInfo_branch_ItemFromJson(this_item))
            item_attributes.remove("branch")

        except:
            _ProcessException("branch")

        # Additional data
        if process_additional_data:
            self._ProcessAdditionalData(item,
                                        result,
                                        exclude_names={
                                            "id", "author", "date",
                                            "description", "branch"
                                        })
        elif item_attributes:
            raise ValidationException(
                "The item contains extraneous data: {}".format(', '.join([
                    "'{}'".format(item_attribute)
                    for item_attribute in item_attributes
                ])))

        ChangeInfo_TypeInfo.ValidateItem(
            result,
            recurse=False,
            require_exact_match=not process_additional_data,
            exclude_names=["id", "author", "date", "description", "branch"])
        return result