Ejemplo n.º 1
0
 def __get_opts_fields(self, declared_fields):
     '''Return only those field_name:field_obj pairs specified in the fields
     option of class Meta.
     '''
     # Convert obj to a dict
     if not isinstance(self.opts.fields, (list, tuple)):
         raise ValueError("`fields` option must be a list or tuple.")
     obj_marshallable = utils.to_marshallable_type(self.obj)
     if isinstance(obj_marshallable, (list, tuple)):  # Homogeneous list
         if len(obj_marshallable) > 0:
             obj_dict = utils.to_marshallable_type(obj_marshallable[0])
         else:  # Nothing to serialize
             return declared_fields
     else:
         obj_dict = obj_marshallable
     new = OrderedDict()
     for key in self.opts.fields:
         if key in declared_fields:
             new[key] = declared_fields[key]
         else:
             try:
                 attribute_type = type(obj_dict[key])
             except KeyError:
                 raise AttributeError(
                     '"{0}" is not a valid field for {1}.'.format(key, self.obj))
             # map key -> field (default to Raw)
             new[key] = self.TYPE_MAPPING.get(attribute_type, fields.Raw)()
     return new
Ejemplo n.º 2
0
    def test_marshallable(self):
        class ObjContainer(object):
            contained = {"foo": 1}
            def __marshallable__(self):
                return self.contained

        obj = ObjContainer()
        assert_equal(utils.to_marshallable_type(obj), {"foo": 1})
Ejemplo n.º 3
0
def test_marshallable():
    class ObjContainer(object):
        contained = {'foo': 1}

        def __marshallable__(self):
            return self.contained

    obj = ObjContainer()
    assert utils.to_marshallable_type(obj) == {'foo': 1}
Ejemplo n.º 4
0
    def test_marshallable(self):
        class ObjContainer(object):
            contained = {"foo": 1}

            def __marshallable__(self):
                return self.contained

        obj = ObjContainer()
        assert_equal(utils.to_marshallable_type(obj), {"foo": 1})
Ejemplo n.º 5
0
    def __filter_fields(self, field_names, obj, many=False):
        """Return only those field_name:field_obj pairs specified by
        ``field_names``.

        :param set field_names: Field names to include in the final
            return dictionary.
        :returns: An dict of field_name:field_obj pairs.
        """
        # Convert obj to a dict
        obj_marshallable = utils.to_marshallable_type(obj,
                                                      field_names=field_names)
        if obj_marshallable and many:
            try:  # Homogeneous collection
                obj_prototype = obj_marshallable[0]
            except IndexError:  # Nothing to serialize
                return self.declared_fields
            obj_dict = utils.to_marshallable_type(obj_prototype,
                                                  field_names=field_names)
        else:
            obj_dict = obj_marshallable
        ret = self.dict_class()
        for key in field_names:
            if key in self.declared_fields:
                ret[key] = self.declared_fields[key]
            else:
                if obj_dict:
                    try:
                        attribute_type = type(obj_dict[key])
                    except KeyError:
                        raise AttributeError(
                            '"{0}" is not a valid field for {1}.'.format(
                                key, obj))
                    field_obj = self.TYPE_MAPPING.get(attribute_type,
                                                      fields.Field)()
                else:  # Object is None
                    field_obj = fields.Field()
                # map key -> field (default to Raw)
                ret[key] = field_obj
        return ret
Ejemplo n.º 6
0
 def test_to_marshallable_type(self):
     class Foo(object):
         CLASS_VAR = 'bar'
         def __init__(self):
             self.attribute = 'baz'
         @property
         def prop(self):
             return 42
     obj = Foo()
     u_dict = utils.to_marshallable_type(obj)
     assert_equal(u_dict['CLASS_VAR'], Foo.CLASS_VAR)
     assert_equal(u_dict['attribute'], obj.attribute)
     assert_equal(u_dict['prop'], obj.prop)
Ejemplo n.º 7
0
    def __filter_fields(self, field_names, obj):
        """Return only those field_name:field_obj pairs specified by
        ``field_names``.

        :param set field_names: Field names to include in the final
            return dictionary.
        :returns: An OrderedDict of field_name:field_obj pairs.
        """
        # Convert obj to a dict
        obj_marshallable = utils.to_marshallable_type(obj,
            field_names=field_names)
        if obj_marshallable and self.many:
            try:  # Homogeneous collection
                obj_prototype = obj_marshallable[0]
            except IndexError:  # Nothing to serialize
                return self.declared_fields
            obj_dict = utils.to_marshallable_type(obj_prototype,
                field_names=field_names)
        else:
            obj_dict = obj_marshallable
        ret = OrderedDict()
        for key in field_names:
            if key in self.declared_fields:
                ret[key] = self.declared_fields[key]
            else:
                if obj_dict:
                    try:
                        attribute_type = type(obj_dict[key])
                    except KeyError:
                        raise AttributeError(
                            '"{0}" is not a valid field for {1}.'.format(key, obj))
                    field_obj = self.TYPE_MAPPING.get(attribute_type, fields.Field)()
                else:  # Object is None
                    field_obj = fields.Field()
                # map key -> field (default to Raw)
                ret[key] = field_obj
        return ret
Ejemplo n.º 8
0
def test_to_marshallable_type():
    class Foo(object):
        CLASS_VAR = 'bar'

        def __init__(self):
            self.attribute = 'baz'

        @property
        def prop(self):
            return 42

    obj = Foo()
    u_dict = utils.to_marshallable_type(obj)
    assert u_dict['CLASS_VAR'] == Foo.CLASS_VAR
    assert u_dict['attribute'] == obj.attribute
    assert u_dict['prop'] == obj.prop
Ejemplo n.º 9
0
def test_to_marshallable_type_none():
    assert utils.to_marshallable_type(None) is None
Ejemplo n.º 10
0
def test_to_marshallable_type_with_namedtuple():
    p = PointNT(24, 42)
    result = utils.to_marshallable_type(p)
    assert result['x'] == p.x
    assert result['y'] == p.y
Ejemplo n.º 11
0
def test_to_marshallable_type_none():
    assert utils.to_marshallable_type(None) is None
Ejemplo n.º 12
0
 def _serialize(self, value, attr, obj):
     try:
         data = utils.to_marshallable_type(obj)
         return self.src_str.format(**data)
     except (TypeError, IndexError) as error:
         raise MarshallingError(getattr(self, 'error', None) or error)
Ejemplo n.º 13
0
def test_to_marshallable_type_list():
    assert utils.to_marshallable_type(['foo', 'bar']) == ['foo', 'bar']
Ejemplo n.º 14
0
def test_to_marshallable_type_generator():
    gen = (e for e in ['foo', 'bar'])
    assert utils.to_marshallable_type(gen) == ['foo', 'bar']
Ejemplo n.º 15
0
def test_to_marshallable_type_generator():
    gen = (e for e in ['foo', 'bar'])
    assert utils.to_marshallable_type(gen) == ['foo', 'bar']
Ejemplo n.º 16
0
 def test_to_marshallable_type_none(self):
     assert_equal(utils.to_marshallable_type(None), None)
Ejemplo n.º 17
0
 def output(self, key, obj):
     try:
         data = utils.to_marshallable_type(obj)
         return self.src_str.format(**data)
     except (TypeError, IndexError) as error:
         raise MarshallingError(error)
Ejemplo n.º 18
0
def test_to_marshallable_type_list():
    assert utils.to_marshallable_type(['foo', 'bar']) == ['foo', 'bar']
Ejemplo n.º 19
0
 def _serialize(self, value, attr, obj):
     try:
         data = utils.to_marshallable_type(obj)
         return self.src_str.format(**data)
     except (TypeError, IndexError) as error:
         self.fail('format')
Ejemplo n.º 20
0
 def test_to_marshallable_type(self):
     u = User("Foo", "*****@*****.**")
     assert_equal(utils.to_marshallable_type(u), u.__dict__)
Ejemplo n.º 21
0
 def output(self, key, obj):
     try:
         data = utils.to_marshallable_type(obj)
         return self.src_str.format(**data)
     except (TypeError, IndexError) as error:
         raise MarshallingError(error)
Ejemplo n.º 22
0
 def test_to_marshallable_type_list(self):
     assert_equal(utils.to_marshallable_type(['foo', 'bar']), ['foo', 'bar'])
Ejemplo n.º 23
0
 def test_to_marshallable_type_generator(self):
     gen = (e for e in ['foo', 'bar'])
     assert_equal(utils.to_marshallable_type(gen), ['foo', 'bar'])
Ejemplo n.º 24
0
 def _serialize(self, value, attr, obj):
     try:
         data = utils.to_marshallable_type(obj)
         return self.src_str.format(**data)
     except (TypeError, IndexError) as error:
         self.fail('format')
Ejemplo n.º 25
0
def test_to_marshallable_type_with_namedtuple():
    p = PointNT(24, 42)
    result = utils.to_marshallable_type(p)
    assert result['x'] == p.x
    assert result['y'] == p.y