Example #1
0
    def _from_dict_value(cls, class_, value, validator):
        # validate raw input
        if validator is cls.SOFT_VALIDATION:
            if issubclass(class_, Unicode) and not isinstance(value, basestring):
                raise ValidationError(value)
            if issubclass(class_, Unicode) and not isinstance(value, unicode):
                # Note that String is a subclass of Unicode
                if not (issubclass(class_, String) and isinstance(value, str)):
                    value = ProtocolBase.from_string(class_, value)

            elif issubclass(class_, Decimal) and not isinstance(value,
                                                            (int, long, float)):
                raise ValidationError(value)

            elif issubclass(class_, DateTime) and not (
                                isinstance(value, unicode) and
                                         class_.validate_string(class_, value)):
                raise ValidationError(value)

        # get native type
        if issubclass(class_, ComplexModelBase):
            retval = cls._doc_to_object(class_, value, validator)

        elif issubclass(class_, DateTime):
            retval = ProtocolBase.from_string(class_, value)

        else:
            retval = value

        # validate native type
        if validator is cls.SOFT_VALIDATION and \
                                     not class_.validate_native(class_, retval):
            raise ValidationError(retval)

        return retval
Example #2
0
    def _from_dict_value(cls, class_, value, validator):
        # validate raw input
        if validator is cls.SOFT_VALIDATION:
            if issubclass(class_, Unicode) and not isinstance(value, basestring):
                raise ValidationError(value)
            if issubclass(class_, Unicode) and not isinstance(value, unicode):
                # Note that String is a subclass of Unicode
                if not (issubclass(class_, String) and isinstance(value, str)):
                    value = ProtocolBase.from_string(class_, value)

            elif issubclass(class_, Decimal) and not isinstance(value,
                                                            (int, long, float)):
                raise ValidationError(value)

            elif issubclass(class_, DateTime) and not (
                                isinstance(value, unicode) and
                                         class_.validate_string(class_, value)):
                raise ValidationError(value)

        # get native type
        if issubclass(class_, ComplexModelBase):
            retval = cls._doc_to_object(class_, value, validator)

        elif issubclass(class_, DateTime):
            retval = ProtocolBase.from_string(class_, value)

        else:
            retval = value

        # validate native type
        if validator is cls.SOFT_VALIDATION and \
                                     not class_.validate_native(class_, retval):
            raise ValidationError(retval)

        return retval
Example #3
0
    def test_duration_xml_duration(self):
        dur = datetime.timedelta(days=5 + 30 + 365, hours=1, minutes=1,
                                                   seconds=12, microseconds=8e5)

        str1 = 'P400DT3672.8S'
        str2 = 'P1Y1M5DT1H1M12.8S'

        self.assertEquals(dur, ProtocolBase.from_string(Duration, str1))
        self.assertEquals(dur, ProtocolBase.from_string(Duration, str2))

        self.assertEquals(dur, ProtocolBase.from_string(Duration, ProtocolBase.to_string(Duration, dur)))
Example #4
0
    def test_limits(self):
        try:
            ProtocolBase.from_string(Integer, "1" * (Integer.__max_str_len__ + 1))
        except:
            pass
        else:
            raise Exception("must fail.")

        ProtocolBase.from_string(UnsignedInteger, "-1") # This is not supposed to fail.

        try:
            UnsignedInteger.validate_native(-1) # This is supposed to fail.
        except:
            pass
        else:
            raise Exception("must fail.")
Example #5
0
    def test_date(self):
        n = datetime.date(2011,12,13)

        ret = ProtocolBase.to_string(Date, n)
        self.assertEquals(ret, n.isoformat())

        dt = ProtocolBase.from_string(Date, ret)
        self.assertEquals(n, dt)
Example #6
0
    def test_time(self):
        n = datetime.time(1, 2, 3, 4)

        ret = ProtocolBase.to_string(Time, n)
        self.assertEquals(ret, n.isoformat())

        dt = ProtocolBase.from_string(Time, ret)
        self.assertEquals(n, dt)
Example #7
0
    def test_duration_xml_duration(self):
        dur = datetime.timedelta(days=5 + 30 + 365,
                                 hours=1,
                                 minutes=1,
                                 seconds=12,
                                 microseconds=8e5)

        str1 = 'P400DT3672.8S'
        str2 = 'P1Y1M5DT1H1M12.8S'

        self.assertEquals(dur, ProtocolBase.from_string(Duration, str1))
        self.assertEquals(dur, ProtocolBase.from_string(Duration, str2))

        self.assertEquals(
            dur,
            ProtocolBase.from_string(Duration,
                                     ProtocolBase.to_string(Duration, dur)))
Example #8
0
    def test_date(self):
        n = datetime.date(2011, 12, 13)

        ret = ProtocolBase.to_string(Date, n)
        self.assertEquals(ret, n.isoformat())

        dt = ProtocolBase.from_string(Date, ret)
        self.assertEquals(n, dt)
Example #9
0
    def test_time(self):
        n = datetime.time(1, 2, 3, 4)

        ret = ProtocolBase.to_string(Time, n)
        self.assertEquals(ret, n.isoformat())

        dt = ProtocolBase.from_string(Time, ret)
        self.assertEquals(n, dt)
Example #10
0
    def test_limits(self):
        try:
            ProtocolBase.from_string(Integer,
                                     "1" * (Integer.__max_str_len__ + 1))
        except:
            pass
        else:
            raise Exception("must fail.")

        ProtocolBase.from_string(UnsignedInteger,
                                 "-1")  # This is not supposed to fail.

        try:
            UnsignedInteger.validate_native(-1)  # This is supposed to fail.
        except:
            pass
        else:
            raise Exception("must fail.")
Example #11
0
    def flat_dict_to_object(cls, doc, inst_class, validator=None, hier_delim="_"):
        """Converts a flat dict to a native python object.

        See :func:`spyne.model.complex.ComplexModelBase.get_flat_type_info`.
        """

        simple_type_info = inst_class.get_simple_type_info(inst_class)
        inst = inst_class.get_deserialization_instance()

        # this is for validating cls.Attributes.{min,max}_occurs
        frequencies = defaultdict(lambda: defaultdict(int))

        for orig_k, v in doc.items():
            k = RE_HTTP_ARRAY_INDEX.sub("", orig_k)
            member = simple_type_info.get(k, None)
            if member is None:
                logger.debug("discarding field %r" % k)
                continue

            value = getattr(inst, k, None)
            if value is None:
                value = []

            # extract native values from the list of strings that come from the
            # http dict.
            for v2 in v:
                if (validator is cls.SOFT_VALIDATION and not
                                  member.type.validate_string(member.type, v2)):
                    raise ValidationError(v2)

                if issubclass(member.type, (File, ByteArray)):
                    if isinstance(v2, str) or isinstance(v2, unicode):
                        native_v2 = ProtocolBase.from_string(member.type, v2)
                    else:
                        native_v2 = v2
                else:
                    native_v2 = ProtocolBase.from_string(member.type, v2)

                if (validator is cls.SOFT_VALIDATION and not
                            member.type.validate_native(member.type, native_v2)):
                    raise ValidationError(v2)

                value.append(native_v2)

            # assign the native value to the relevant class in the nested object
            # structure.
            ccls, cinst = inst_class, inst
            ctype_info = inst_class.get_flat_type_info(inst_class)

            idx, nidx = 0, 0
            pkey = member.path[0]
            cfreq_key = inst_class, idx

            indexes = deque(RE_HTTP_ARRAY_INDEX.findall(orig_k))
            for i in range(len(member.path) - 1):
                pkey = member.path[i]
                nidx = 0

                ncls, ninst = ctype_info[pkey], getattr(cinst, pkey, None)

                mo = ncls.Attributes.max_occurs
                if ninst is None:
                    ninst = ncls.get_deserialization_instance()
                    if mo > 1:
                        ninst = [ninst]
                    setattr(cinst, pkey, ninst)
                    frequencies[cfreq_key][pkey] += 1

                if mo > 1:
                    if len(indexes) == 0:
                        raise ValidationError(orig_k,
                                               "%r requires index information.")

                    nidx = int(indexes.popleft())

                    if nidx > len(ninst) or nidx < 0:
                        raise ValidationError(orig_k,
                                            "%%r Invalid array index %d." % idx)

                    if nidx == len(ninst):
                        ninst.append(ncls.get_deserialization_instance())
                        frequencies[cfreq_key][pkey] += 1

                    cinst = ninst[nidx]

                else:
                    cinst = ninst

                cfreq_key = cfreq_key + (ncls, nidx)
                ccls, idx = ncls, nidx
                ctype_info = ncls._type_info

            frequencies[cfreq_key][member.path[-1]] += len(value)

            if member.type.Attributes.max_occurs > 1:
                v = getattr(cinst, member.path[-1], None)
                if v is None:
                    setattr(cinst, member.path[-1], value)
                else:
                    v.extend(value)
                logger.debug("\tset array   %r(%r) = %r" %
                                                    (member.path, pkey, value))
            else:
                setattr(cinst, member.path[-1], value[0])
                logger.debug("\tset default %r(%r) = %r" %
                                                    (member.path, pkey, value))

        if validator is cls.SOFT_VALIDATION:
            for k, d in frequencies.items():
                check_freq_dict(k[-2], d)

        return inst
Example #12
0
    def flat_dict_to_object(cls, doc, inst_class, validator=None, hier_delim="_"):
        """Converts a flat dict to a native python object.

        See :func:`spyne.model.complex.ComplexModelBase.get_flat_type_info`.
        """

        simple_type_info = inst_class.get_simple_type_info(inst_class)
        inst = inst_class.get_deserialization_instance()

        # this is for validating cls.Attributes.{min,max}_occurs
        frequencies = defaultdict(lambda: defaultdict(int))

        for orig_k, v in doc.items():
            k = RE_HTTP_ARRAY_INDEX.sub("", orig_k)
            member = simple_type_info.get(k, None)
            if member is None:
                logger.debug("discarding field %r" % k)
                continue

            value = getattr(inst, k, None)
            if value is None:
                value = []

            # extract native values from the list of strings that come from the
            # http dict.
            for v2 in v:
                if (validator is cls.SOFT_VALIDATION and not
                                  member.type.validate_string(member.type, v2)):
                    raise ValidationError(v2)

                if issubclass(member.type, (File, ByteArray)):
                    if isinstance(v2, str) or isinstance(v2, unicode):
                        native_v2 = ProtocolBase.from_string(member.type, v2)
                    else:
                        native_v2 = v2
                else:
                    native_v2 = ProtocolBase.from_string(member.type, v2)

                if (validator is cls.SOFT_VALIDATION and not
                            member.type.validate_native(member.type, native_v2)):
                    raise ValidationError(v2)

                value.append(native_v2)

            # assign the native value to the relevant class in the nested object
            # structure.
            ccls, cinst = inst_class, inst
            ctype_info = inst_class.get_flat_type_info(inst_class)

            idx, nidx = 0, 0
            pkey = member.path[0]
            cfreq_key = inst_class, idx

            indexes = deque(RE_HTTP_ARRAY_INDEX.findall(orig_k))
            for i in range(len(member.path) - 1):
                pkey = member.path[i]
                nidx = 0

                ncls, ninst = ctype_info[pkey], getattr(cinst, pkey, None)

                mo = ncls.Attributes.max_occurs
                if ninst is None:
                    ninst = ncls.get_deserialization_instance()
                    if mo > 1:
                        ninst = [ninst]
                    setattr(cinst, pkey, ninst)
                    frequencies[cfreq_key][pkey] += 1

                if mo > 1:
                    if len(indexes) == 0:
                        raise ValidationError(orig_k,
                                               "%r requires index information.")

                    nidx = int(indexes.popleft())

                    if nidx > len(ninst) or nidx < 0:
                        raise ValidationError(orig_k,
                                            "%%r Invalid array index %d." % idx)

                    if nidx == len(ninst):
                        ninst.append(ncls.get_deserialization_instance())
                        frequencies[cfreq_key][pkey] += 1

                    cinst = ninst[nidx]

                else:
                    cinst = ninst

                cfreq_key = cfreq_key + (ncls, nidx)
                ccls, idx = ncls, nidx
                ctype_info = ncls._type_info

            frequencies[cfreq_key][member.path[-1]] += len(value)

            if member.type.Attributes.max_occurs > 1:
                v = getattr(cinst, member.path[-1], None)
                if v is None:
                    setattr(cinst, member.path[-1], value)
                else:
                    v.extend(value)
                logger.debug("\tset array   %r(%r) = %r" %
                                                    (member.path, pkey, value))
            else:
                setattr(cinst, member.path[-1], value[0])
                logger.debug("\tset default %r(%r) = %r" %
                                                    (member.path, pkey, value))

        if validator is cls.SOFT_VALIDATION:
            for k, d in frequencies.items():
                check_freq_dict(k[-2], d)

        return inst