Example #1
0
    def test_log_repr_dict_values_full(self):
        from spyne.model import AnyDict
        from spyne.util.web import log_repr

        t = AnyDict(logged='values-full')

        assert log_repr({1: 1, 2: 2, 3: 3}, t) == "{(...): 1, (...): 2, (...): 3}"
        assert log_repr([1, 2, 3], t) == "[1, 2, 3]"
Example #2
0
    def test_log_repr_dict_keys_full(self):
        from spyne.model import AnyDict
        from spyne.util.web import log_repr

        t = AnyDict(logged='keys-full')

        assert log_repr({1: 1, 2: 2, 3: 3}, t) == "{1: (...), 2: (...), 3: (...)}"
        assert log_repr([1, 2, 3], t) == "[1, 2, 3]"
Example #3
0
    def test_log_repr_dict_keys_full(self):
        from spyne.model import AnyDict
        from spyne.util.web import log_repr

        t = AnyDict(logged='keys-full')

        assert log_repr({1: 1, 2: 2, 3: 3}, t) == "{1: (...), 2: (...), 3: (...)}"
        assert log_repr([1, 2, 3], t) == "[1, 2, 3]"
Example #4
0
    def test_log_repr_dict_values_full(self):
        from spyne.model import AnyDict
        from spyne.util.web import log_repr

        t = AnyDict(logged='values-full')

        assert log_repr({1: 1, 2: 2, 3: 3}, t) == "{(...): 1, (...): 2, (...): 3}"
        assert log_repr([1, 2, 3], t) == "[1, 2, 3]"
Example #5
0
    def test_log_repr_dict_values(self):
        from spyne.model import AnyDict
        from spyne.util.web import log_repr

        t = AnyDict(logged='values')

        assert log_repr({1: 1}, t) == "{(...): 1}"

        assert log_repr([1], t) == "[1]"
Example #6
0
    def test_log_repr_dict_values(self):
        from spyne.model import AnyDict
        from spyne.util.web import log_repr

        t = AnyDict(logged='values')

        assert log_repr({1: 1}, t) == "{(...): 1}"

        assert log_repr([1], t) == "[1]"
Example #7
0
    def test_log_repr_simple(self):
        from spyne.model.complex import ComplexModel
        from spyne.model.primitive import String
        from spyne.util.web import log_repr

        class Z(ComplexModel):
            z=String

        l = MAX_STRING_FIELD_LENGTH + 100
        print(log_repr(Z(z="a" * l)))
        print("Z(z='%s'(...))" % ('a' * MAX_STRING_FIELD_LENGTH))

        assert log_repr(Z(z="a" * l)) == "Z(z='%s'(...))" % \
                                                ('a' * MAX_STRING_FIELD_LENGTH)
        assert log_repr(['a','b','c'], Array(String)) ==  "['a', 'b', (...)]"
Example #8
0
    def test_log_repr_simple(self):
        from spyne.model.complex import ComplexModel
        from spyne.model.primitive import String
        from spyne.util.web import log_repr

        class Z(ComplexModel):
            z=String

        l = MAX_STRING_FIELD_LENGTH + 100
        print(log_repr(Z(z="a" * l)))
        print("Z(z='%s'(...))" % ('a' * MAX_STRING_FIELD_LENGTH))

        assert log_repr(Z(z="a" * l)) == "Z(z='%s'(...))" % \
                                                ('a' * MAX_STRING_FIELD_LENGTH)
        assert log_repr(['a','b','c'], Array(String)) ==  "['a', 'b', 'c']"
Example #9
0
    def to_cloth(self,
                 ctx,
                 cls,
                 inst,
                 cloth,
                 parent,
                 name=None,
                 from_arr=False,
                 **kwargs):
        prot_name = self.__class__.__name__

        if cloth is None:
            return self.to_parent(ctx, cls, inst, parent, name, **kwargs)

        cls, switched = self.get_polymorphic_target(cls, inst)

        # if there's a subprotocol, switch to it
        subprot = getattr(cls.Attributes, 'prot', None)
        if subprot is not None and not (subprot is self):
            self._enter_cloth(ctx, cloth, parent)
            return subprot.subserialize(ctx, cls, inst, parent, name, **kwargs)

        # if instance is None, use the default factory to generate one
        _df = cls.Attributes.default_factory
        if inst is None and callable(_df):
            inst = _df()

        # if instance is still None, use the default value
        if inst is None:
            inst = cls.Attributes.default

        retval = None
        if inst is None:
            identifier = "%s.%s" % (prot_name, "null_to_cloth")
            logger_s.debug("Writing %s using %s for %s.", name, identifier,
                           cls.get_type_name())

            ctx.protocol.tags.add(id(cloth))
            if cls.Attributes.min_occurs > 0:
                parent.write(cloth)

        else:
            if not from_arr and cls.Attributes.max_occurs > 1:
                return self.array_to_cloth(ctx,
                                           cls,
                                           inst,
                                           cloth,
                                           parent,
                                           name=name)

            handler = self.rendering_handlers[cls]

            identifier = "%s.%s" % (prot_name, handler.__name__)
            logger_s.debug("Writing %s using %s for %s. Inst: %r",
                           name, identifier, cls.get_type_name(),
                           log_repr(inst, cls))

            retval = handler(ctx, cls, inst, cloth, parent, name=name)

        return retval
Example #10
0
 def validate_native(cls, inst):
     for k, v in inst.items():
         if not isinstance(k, six.string_types):
             raise ValidationError(type(k), "Invalid key type %r")
         if not isinstance(v, list):
             raise ValidationError(type(v), "Invalid value type %r")
         # log_repr prevents too much data going in the logs.
         if not len({type(subv) for subv in v}) == 1:
             raise ValidationError(log_repr(v), "List %s is not uniform")
     return True
Example #11
0
    def test_log_repr(self):
        from spyne.model.complex import ComplexModel
        from spyne.model.primitive import Integer
        from spyne.model.primitive import String
        from spyne.util.web import log_repr

        class Z(ComplexModel):
            z=String

        assert 128 > MAX_STRING_FIELD_LENGTH
        assert log_repr(Z(z="a"*128)) == "Z(z='%s'(...))" % ('a' * MAX_STRING_FIELD_LENGTH)
Example #12
0
    def to_cloth(self, ctx, cls, inst, cloth, parent, name=None, from_arr=False,
                                                                      **kwargs):
        prot_name = self.__class__.__name__
        cls_attrs = self.get_cls_attrs(cls)

        if cloth is None:
            logger_c.debug("No cloth fround, switching to to_parent...")
            return self.to_parent(ctx, cls, inst, parent, name, **kwargs)

        cls, switched = self.get_polymorphic_target(cls, inst)

        # if there's a subprotocol, switch to it
        subprot = cls_attrs.prot
        if subprot is not None and not (subprot is self):
            self._enter_cloth(ctx, cloth, parent)
            return subprot.subserialize(ctx, cls, inst, parent, name, **kwargs)

        # if instance is None, use the default factory to generate one
        _df = cls_attrs.default_factory
        if inst is None and callable(_df):
            inst = _df()

        # if instance is still None, use the default value
        if inst is None:
            inst = cls_attrs.default

        if inst is None:
            if cls.Attributes.min_occurs > 0:
                self._enter_cloth(ctx, cloth, parent)
                identifier = "%s.%s" % (prot_name, "null_to_cloth")
                logger_s.debug("Writing '%s' using %s type: %s.", name,
                                                identifier, cls.get_type_name())
                parent.write(cloth)

            else:
                logger_s.debug("Skipping '%s' type: %s because empty.", name,
                                                            cls.get_type_name())
                self._enter_cloth(ctx, cloth, parent, skip=True)

            return

        if not from_arr and cls.Attributes.max_occurs > 1:
            return self.array_to_cloth(ctx, cls, inst, cloth, parent, name=name)

        handler = self.rendering_handlers[cls]

        identifier = "%s.%s" % (prot_name, handler.__name__)
        logger_s.debug("Writing %s using %s for %s. Inst: %r", name,
                                   identifier, cls.get_type_name(),
                                   log_repr(inst, cls, from_array=from_arr))

        retval = handler(ctx, cls, inst, cloth, parent, name=name)

        return retval
Example #13
0
    def test_log_repr(self):
        from spyne.model.complex import ComplexModel
        from spyne.model.primitive import Integer
        from spyne.model.primitive import String
        from spyne.util.web import log_repr

        class Z(ComplexModel):
            z = String

        assert 128 > MAX_STRING_FIELD_LENGTH
        assert log_repr(Z(z="a" * 128)) == "Z(z='%s'(...))" % ("a" * MAX_STRING_FIELD_LENGTH)
Example #14
0
    def to_cloth(self, ctx, cls, inst, cloth, parent, name=None, from_arr=False,
                                                                      **kwargs):
        prot_name = self.__class__.__name__

        if cloth is None:
            return self.to_parent(ctx, cls, inst, parent, name, **kwargs)

        cls, switched = self.get_polymorphic_target(cls, inst)

        # if there's a subprotocol, switch to it
        subprot = getattr(cls.Attributes, 'prot', None)
        if subprot is not None and not (subprot is self):
            self._enter_cloth(ctx, cloth, parent)
            return subprot.subserialize(ctx, cls, inst, parent, name, **kwargs)

        # if instance is None, use the default factory to generate one
        _df = cls.Attributes.default_factory
        if inst is None and callable(_df):
            inst = _df()

        # if instance is still None, use the default value
        if inst is None:
            inst = cls.Attributes.default

        retval = None
        if inst is None:
            identifier = "%s.%s" % (prot_name, "null_to_cloth")
            logger_s.debug("Writing %s using %s for %s.", name,
                                                identifier, cls.get_type_name())

            ctx.protocol.tags.add(id(cloth))
            if cls.Attributes.min_occurs > 0:
                parent.write(cloth)

            return

        if not from_arr and cls.Attributes.max_occurs > 1:
            return self.array_to_cloth(ctx, cls, inst, cloth, parent, name=name)

        handler = self.rendering_handlers[cls]

        identifier = "%s.%s" % (prot_name, handler.__name__)
        logger_s.debug("Writing %s using %s for %s. Inst: %r", name,
                                   identifier, cls.get_type_name(),
                                   log_repr(inst, cls, from_array=from_arr))

        retval = handler(ctx, cls, inst, cloth, parent, name=name)

        return retval
Example #15
0
    def test_log_repr_complex(self):
        from spyne.model import ByteArray
        from spyne.model import File
        from spyne.model.complex import ComplexModel
        from spyne.model.primitive import String
        from spyne.util.web import log_repr

        class Z(ComplexModel):
            _type_info = [
                ('f', File(logged=False)),
                ('t', ByteArray(logged=False)),
                ('z', Array(String)),
            ]
        l = MAX_STRING_FIELD_LENGTH + 100
        val = Z(z=["abc"] * l, t=['t'], f=File.Value(name='aaa', data=['t']))
        print(repr(val))

        assert log_repr(val) == "Z(z=['abc', 'abc', (...)])"
Example #16
0
    def test_log_repr_complex(self):
        from spyne.model import ByteArray
        from spyne.model import File
        from spyne.model.complex import ComplexModel
        from spyne.model.primitive import String
        from spyne.util.web import log_repr

        class Z(ComplexModel):
            _type_info = [
                ('f', File(logged=False)),
                ('t', ByteArray(logged=False)),
                ('z', Array(String)),
            ]
        l = MAX_STRING_FIELD_LENGTH + 100
        val = Z(z=["abc"] * l, t=['t'], f=File.Value(name='aaa', data=['t']))
        print(repr(val))

        assert log_repr(val) == "Z(z=['abc', 'abc', (...)])"
Example #17
0
    def test_log_repr_dict_vanilla(self):
        from spyne.model import AnyDict
        from spyne.util.web import log_repr

        t = AnyDict

        assert log_repr({1: 1}, t) == "{1: 1}"
        assert log_repr({1: 1, 2: 2}, t) == "{1: 1, 2: 2}"
        assert log_repr({1: 1, 2: 2, 3: 3}, t) == "{1: 1, 2: 2, (...)}"

        assert log_repr([1], t) == "[1]"
        assert log_repr([1, 2], t) == "[1, 2]"
        assert log_repr([1, 2, 3], t) == "[1, 2, (...)]"
Example #18
0
    def test_log_repr_dict_vanilla(self):
        from spyne.model import AnyDict
        from spyne.util.web import log_repr

        t = AnyDict

        assert log_repr({1: 1}, t) == "{1: 1}"
        assert log_repr({1: 1, 2: 2}, t) == "{1: 1, 2: 2}"
        assert log_repr({1: 1, 2: 2, 3: 3}, t) == "{1: 1, 2: 2, (...)}"

        assert log_repr([1], t) == "[1]"
        assert log_repr([1, 2], t) == "[1, 2]"
        assert log_repr([1, 2, 3], t) == "[1, 2, (...)]"
Example #19
0
    def to_parent(self, ctx, cls, inst, parent, name, nosubprot=False, **kwargs):
        prot_name = self.__class__.__name__

        cls, switched = self.get_polymorphic_target(cls, inst)

        # if there is a subprotocol, switch to it
        subprot = getattr(cls.Attributes, "prot", None)
        if subprot is not None and not nosubprot and not (subprot in ctx.protocol.prot_stack):
            logger.debug("Subprot from %r to %r", self, subprot)
            return self.to_subprot(ctx, cls, inst, parent, name, subprot, **kwargs)

        # if there is a class cloth, switch to it
        ret, cor_handle = self.check_class_cloths(ctx, cls, inst, parent, name, **kwargs)
        if ret:
            return cor_handle

        # if instance is None, use the default factory to generate one
        _df = cls.Attributes.default_factory
        if inst is None and callable(_df):
            inst = _df()

        # if instance is still None, use the default value
        if inst is None:
            inst = cls.Attributes.default

        # if instance is still None, use the global null handler to serialize it
        if inst is None and self.use_global_null_handler:
            identifier = prot_name + ".null_to_parent"
            logger.debug("Writing %s using %s for %s.", name, identifier, cls.get_type_name())
            return self.null_to_parent(ctx, cls, inst, parent, name, **kwargs)

        # if requested, ignore wrappers
        if self.ignore_wrappers and issubclass(cls, ComplexModelBase):
            cls, inst = self.strip_wrappers(cls, inst)

        # if cls is an iterable of values and it's not been iterated on, do it
        from_arr = kwargs.get("from_arr", False)
        if not from_arr and cls.Attributes.max_occurs > 1:
            return self.array_to_parent(ctx, cls, inst, parent, name, **kwargs)

        # fetch the serializer for the class at hand
        try:
            handler = self.serialization_handlers[cls]
        except KeyError:
            # if this protocol uncapable of serializing this class
            if self.ignore_uncap:
                logger.debug("Ignore uncap %r", name)
                return  # ignore it if requested

            # raise the error otherwise
            logger.error("%r is missing handler for %r for field %r", self, cls, name)
            raise

        # push the instance at hand to instance stack. this makes it easier for
        # protocols to make decisions based on parents of instances at hand.
        ctx.outprot_ctx.inst_stack.append((cls, inst))

        # finally, serialize the value. retval is the coroutine handle if any
        identifier = "%s.%s" % (prot_name, handler.__name__)
        logger.debug("Writing %s using %s for %s. Inst: %r", name, identifier, cls.get_type_name(), log_repr(inst, cls))

        retval = handler(ctx, cls, inst, parent, name, **kwargs)

        # FIXME: to_parent must be made to a coroutine for the below to remain
        #        consistent when Iterable.Push is used.
        ctx.outprot_ctx.inst_stack.pop()

        return retval
Example #20
0
    def to_parent(self,
                  ctx,
                  cls,
                  inst,
                  parent,
                  name,
                  nosubprot=False,
                  **kwargs):
        prot_name = self.__class__.__name__

        cls, switched = self.get_polymorphic_target(cls, inst)

        # if there is a subprotocol, switch to it
        subprot = getattr(cls.Attributes, 'prot', None)
        if subprot is not None and not nosubprot and not \
                                           (subprot in ctx.protocol.prot_stack):
            logger.debug("Subprot from %r to %r", self, subprot)
            return self.to_subprot(ctx, cls, inst, parent, name, subprot,
                                   **kwargs)

        # if there is a class cloth, switch to it
        ret, cor_handle = self.check_class_cloths(ctx, cls, inst, parent, name,
                                                  **kwargs)
        if ret:
            return cor_handle

        # if instance is None, use the default factory to generate one
        _df = cls.Attributes.default_factory
        if inst is None and callable(_df):
            inst = _df()

        # if instance is still None, use the default value
        if inst is None:
            inst = cls.Attributes.default

        # if instance is still None, use the global null handler to serialize it
        if inst is None and self.use_global_null_handler:
            identifier = prot_name + '.null_to_parent'
            logger.debug("Writing %s using %s for %s.", name, identifier,
                         cls.get_type_name())
            return self.null_to_parent(ctx, cls, inst, parent, name, **kwargs)

        # if requested, ignore wrappers
        if self.ignore_wrappers and issubclass(cls, ComplexModelBase):
            cls, inst = self.strip_wrappers(cls, inst)

        # if cls is an iterable of values and it's not being iterated on, do it
        from_arr = kwargs.get('from_arr', False)
        if not from_arr and cls.Attributes.max_occurs > 1:
            return self.array_to_parent(ctx, cls, inst, parent, name, **kwargs)

        # fetch the serializer for the class at hand
        try:
            handler = self.serialization_handlers[cls]
        except KeyError:
            # if this protocol uncapable of serializing this class
            if self.ignore_uncap:
                logger.debug("Ignore uncap %r", name)
                return  # ignore it if requested

            # raise the error otherwise
            logger.error("%r is missing handler for %r for field %r", self,
                         cls, name)
            raise

        # push the instance at hand to instance stack. this makes it easier for
        # protocols to make decisions based on parents of instances at hand.
        ctx.outprot_ctx.inst_stack.append((cls, inst, from_arr))

        # finally, serialize the value. retval is the coroutine handle if any
        identifier = "%s.%s" % (prot_name, handler.__name__)
        log_str = log_repr(inst, cls, from_array=kwargs.get('from_arr', None))
        logger.debug("Writing %s using %s for %s. Inst: %r", name, identifier,
                     cls.get_type_name(), log_str)

        retval = handler(ctx, cls, inst, parent, name, **kwargs)

        # FIXME: to_parent must be made to a coroutine for the below to remain
        #        consistent when Iterable.Push is used.
        ctx.outprot_ctx.inst_stack.pop()

        return retval