class ASerializer(Serializer): a = MethodField() b = MethodField('add_9') def get_a(self, obj): return obj.a + 5 def add_9(self, obj): return obj.a + 9
def test_method_field(self): class FakeSerializer(object): def get_a(self, obj): return obj.a def z_sub_1(self, obj): return obj.z - 1 serializer = FakeSerializer() fn = MethodField().as_getter('a', serializer) self.assertEqual(fn(Obj(a=3)), 3) fn = MethodField('z_sub_1').as_getter('a', serializer) self.assertEqual(fn(Obj(z=3)), 2) self.assertTrue(MethodField.getter_takes_serializer)
class ASerializer(Serializer): _cls = Obj a = MethodField() b = MethodField('add_9', 'sub_9') def get_a(self, obj): return obj.a + 5 def set_a(self, obj, value): obj.a = value - 5 def add_9(self, obj): return obj.b + 9 def sub_9(self, obj, value): obj.b = value - 9
class JsonSchemaEndpointsSerializer(serpy.Serializer): basePath = LiteralField('/' + BASE_PATH) swagger = LiteralField('2.0') host = LambdaField(lambda *args: request.url_root.replace('http://', ''). replace('https://', '').rstrip('/')) paths = MethodField() definitions = serpy.Field() info = LambdaField(lambda s, o: JsonSchemaInfo(o).data) securityDefinitions = LambdaField( lambda s, o: SecurityDefinitionsSerializer(o).data) security = LiteralField([{'basicAuth': []}]) def get_paths(self, obj): return {k: SwaggerPathSerializer(v).data for k, v in obj.paths.items()}
def test_method_field(self): class FakeSerializer(object): def get_a(self, obj): return obj.a def set_a(self, obj, value): obj.a = value def z_sub_1(self, obj): return obj.z - 1 def z_add_1(self, obj, value): obj.z = value + 1 serializer = FakeSerializer() field = MethodField() fn = field.as_getter('a', serializer) self.assertEqual(fn(Obj(a=3)), 3) fn = field.as_setter('a', serializer) o = Obj(a=-1) fn(o, 3) self.assertEqual(o.a, 3) field = MethodField('z_sub_1', 'z_add_1') fn = field.as_getter('z', serializer) self.assertEqual(fn(Obj(z=3)), 2) fn = field.as_setter('z', serializer) o = Obj(a=-1) fn(o, 2) self.assertEqual(o.z, 3) self.assertTrue(MethodField.getter_takes_serializer) self.assertTrue(MethodField.setter_takes_serializer)
class ASerializer(Serializer): context = StrField(label='@context') content = MethodField(label='@content') def get_content(self, obj): return obj.content
class ASerializer(Serializer): a = MethodField() def get_a(self, obj): return obj.a
class ASerializer(Serializer): a = MethodField(required=False) def get_a(self, obj): return obj.a
class SwaggerPathSerializer(serpy.Serializer): # Hack since for the moment we only handle 'get' method. TODO, find a way to remove this hack get = MethodField(method='get_methods') def get_methods(self, obj): return SwaggerMethodSerializer(obj.methods.get('get')).data