Exemplo n.º 1
0
    def test_non_registered_complex_type(self):
        class TempType(types.Base):
            __registry__ = None

        self.assertFalse(types.iscomplex(TempType))
        types.registry.register(TempType)
        self.assertTrue(types.iscomplex(TempType))
Exemplo n.º 2
0
    def test_non_registered_complex_type(self):
        class TempType(types.Base):
            __registry__ = None

        self.assertFalse(types.iscomplex(TempType))
        types.registry.register(TempType)
        self.assertTrue(types.iscomplex(TempType))
Exemplo n.º 3
0
    def test_validate(self):
        class ComplexType(object):
            attr = int

        class MyWS(object):
            @expose(int)
            @validate(int, int, int)
            def add(self, a, b, c=0):
                return a + b + c

            @expose(bool)
            @validate(ComplexType)
            def setcplx(self, obj):
                pass

        MyWS.add._wsme_definition.resolve_types(wsme.types.registry)
        MyWS.setcplx._wsme_definition.resolve_types(wsme.types.registry)
        args = MyWS.add._wsme_definition.arguments

        assert args[0].name == 'a'
        assert args[0].datatype == int
        assert args[0].mandatory
        assert args[0].default is None

        assert args[1].name == 'b'
        assert args[1].datatype == int
        assert args[1].mandatory
        assert args[1].default is None

        assert args[2].name == 'c'
        assert args[2].datatype == int
        assert not args[2].mandatory
        assert args[2].default == 0

        assert types.iscomplex(ComplexType)
Exemplo n.º 4
0
    def test_validate(self):
        class ComplexType(object):
            attr = int

        class MyWS(object):
            @expose(int)
            @validate(int, int, int)
            def add(self, a, b, c=0):
                return a + b + c

            @expose(bool)
            @validate(ComplexType)
            def setcplx(self, obj):
                pass

        MyWS.add._wsme_definition.resolve_types(wsme.types.registry)
        MyWS.setcplx._wsme_definition.resolve_types(wsme.types.registry)
        args = MyWS.add._wsme_definition.arguments

        assert args[0].name == 'a'
        assert args[0].datatype == int
        assert args[0].mandatory
        assert args[0].default is None

        assert args[1].name == 'b'
        assert args[1].datatype == int
        assert args[1].mandatory
        assert args[1].default is None

        assert args[2].name == 'c'
        assert args[2].datatype == int
        assert not args[2].mandatory
        assert args[2].default == 0

        assert types.iscomplex(ComplexType)
Exemplo n.º 5
0
def array_from_params(datatype, params, path, hit_paths):
    if hasattr(params, 'getall'):
        # webob multidict
        def getall(params, path):
            return params.getall(path)
    elif hasattr(params, 'getlist'):
        # werkzeug multidict
        def getall(params, path):  # noqa
            return params.getlist(path)
    if path in params:
        hit_paths.add(path)
        return [
            from_param(datatype.item_type, value)
            for value in getall(params, path)]

    if iscomplex(datatype.item_type):
        attributes = set()
        r = re.compile('^%s\.(?P<attrname>[^\.])' % re.escape(path))
        for p in params.keys():
            m = r.match(p)
            if m:
                attributes.add(m.group('attrname'))
        if attributes:
            value = []
            for attrdef in list_attributes(datatype.item_type):
                attrpath = '%s.%s' % (path, attrdef.key)
                hit_paths.add(attrpath)
                attrvalues = getall(params, attrpath)
                if len(value) < len(attrvalues):
                    value[-1:] = [
                        datatype.item_type()
                        for i in moves.range(len(attrvalues) - len(value))
                    ]
                for i, attrvalue in enumerate(attrvalues):
                    setattr(
                        value[i],
                        attrdef.key,
                        from_param(attrdef.datatype, attrvalue)
                    )
            return value

    indexes = set()
    r = re.compile('^%s\[(?P<index>\d+)\]' % re.escape(path))

    for p in params.keys():
        m = r.match(p)
        if m:
            indexes.add(int(m.group('index')))

    if not indexes:
        return Unset

    indexes = list(indexes)
    indexes.sort()

    return [from_params(datatype.item_type, params,
                        '%s[%s]' % (path, index), hit_paths)
            for index in indexes]
Exemplo n.º 6
0
def array_from_params(datatype, params, path, hit_paths):
    if hasattr(params, 'getall'):
        # webob multidict
        def getall(params, path):
            return params.getall(path)
    elif hasattr(params, 'getlist'):
        # werkzeug multidict
        def getall(params, path):  # noqa
            return params.getlist(path)

    if path in params:
        hit_paths.add(path)
        return [
            from_param(datatype.item_type, value)
            for value in getall(params, path)
        ]

    if iscomplex(datatype.item_type):
        attributes = set()
        r = re.compile(r'^%s\.(?P<attrname>[^\.])' % re.escape(path))
        for p in params.keys():
            m = r.match(p)
            if m:
                attributes.add(m.group('attrname'))
        if attributes:
            value = []
            for attrdef in list_attributes(datatype.item_type):
                attrpath = '%s.%s' % (path, attrdef.key)
                hit_paths.add(attrpath)
                attrvalues = getall(params, attrpath)
                if len(value) < len(attrvalues):
                    value[-1:] = [
                        datatype.item_type()
                        for i in moves.range(len(attrvalues) - len(value))
                    ]
                for i, attrvalue in enumerate(attrvalues):
                    setattr(value[i], attrdef.key,
                            from_param(attrdef.datatype, attrvalue))
            return value

    indexes = set()
    r = re.compile(r'^%s\[(?P<index>\d+)\]' % re.escape(path))

    for p in params.keys():
        m = r.match(p)
        if m:
            indexes.add(int(m.group('index')))

    if not indexes:
        return Unset

    indexes = list(indexes)
    indexes.sort()

    return [
        from_params(datatype.item_type, params, '%s[%s]' % (path, index),
                    hit_paths) for index in indexes
    ]
Exemplo n.º 7
0
def getdesc(root, host_url=''):
    methods = {}

    for path, funcdef in root.getapi():
        method = funcdef.extra_options.get('method', None)
        name = '_'.join(path)
        if method is not None:
            path = path[:-1]
        else:
            method = 'GET'
            for argdef in funcdef.arguments:
                if types.iscomplex(argdef.datatype) \
                        or types.isarray(argdef.datatype) \
                        or types.isdict(argdef.datatype):
                    method = 'POST'
                    break

        required_params = []
        optional_params = []
        for argdef in funcdef.arguments:
            if method == 'GET' and argdef.mandatory:
                required_params.append(argdef.name)
            else:
                optional_params.append(argdef.name)

        methods[name] = {
            'method': method,
            'path': '/'.join(path)
        }
        if required_params:
            methods[name]['required_params'] = required_params
        if optional_params:
            methods[name]['optional_params'] = optional_params
        if funcdef.doc:
            methods[name]['documentation'] = funcdef.doc

    formats = []
    for p in root.protocols:
        if p.name == 'restxml':
            formats.append('xml')
        if p.name == 'restjson':
            formats.append('json')

    api = {
        'base_url': host_url + root._webpath,
        'version': '0.1',
        'name': getattr(root, 'name', 'name'),
        'authority': '',
        'formats': [
            'json',
            'xml'
        ],
        'methods': methods
    }

    return json.dumps(api, indent=4)
Exemplo n.º 8
0
def tojson(datatype, value):
    if value is None:
        return value
    if iscomplex(datatype):
        d = {}
        for attrdef in list_attributes(datatype):
            attrvalue = getattr(value, attrdef.key)
            if attrvalue is not Unset:
                d[attrdef.name] = tojson(attrdef.datatype, attrvalue)
        value = d
    elif isusertype(datatype):
        value = tojson(datatype.basetype, datatype.tobasetype(value))
    return value
Exemplo n.º 9
0
def fromjson(datatype, value):
    if value is None:
        return None
    if iscomplex(datatype):
        newvalue = datatype()
        for attrdef in list_attributes(datatype):
            if attrdef.name in value:
                setattr(newvalue, attrdef.key,
                        fromjson(attrdef.datatype, value[attrdef.name]))
        value = newvalue
    elif isusertype(datatype):
        value = datatype.frombasetype(fromjson(datatype.basetype, value))
    return value
Exemplo n.º 10
0
def tojson(datatype, value):
    if value is None:
        return value
    if iscomplex(datatype):
        d = {}
        for attrdef in list_attributes(datatype):
            attrvalue = getattr(value, attrdef.key)
            if attrvalue is not Unset:
                d[attrdef.name] = tojson(attrdef.datatype, attrvalue)
        value = d
    elif isusertype(datatype):
        value = tojson(datatype.basetype, datatype.tobasetype(value))
    return value
Exemplo n.º 11
0
def fromjson(datatype, value):
    if value is None:
        return None
    if iscomplex(datatype):
        newvalue = datatype()
        for attrdef in list_attributes(datatype):
            if attrdef.name in value:
                setattr(newvalue, attrdef.key,
                        fromjson(attrdef.datatype, value[attrdef.name]))
        value = newvalue
    elif isusertype(datatype):
        value = datatype.frombasetype(fromjson(datatype.basetype, value))
    return value
Exemplo n.º 12
0
def getdesc(root, host_url=''):
    methods = {}

    for path, funcdef in root.getapi():
        method = funcdef.extra_options.get('method', None)
        name = '_'.join(path)
        if method is not None:
            path = path[:-1]
        else:
            method = 'GET'
            for argdef in funcdef.arguments:
                if types.iscomplex(argdef.datatype) \
                        or types.isarray(argdef.datatype) \
                        or types.isdict(argdef.datatype):
                    method = 'POST'
                    break

        required_params = []
        optional_params = []
        for argdef in funcdef.arguments:
            if method == 'GET' and argdef.mandatory:
                required_params.append(argdef.name)
            else:
                optional_params.append(argdef.name)

        methods[name] = {'method': method, 'path': '/'.join(path)}
        if required_params:
            methods[name]['required_params'] = required_params
        if optional_params:
            methods[name]['optional_params'] = optional_params
        if funcdef.doc:
            methods[name]['documentation'] = funcdef.doc

    formats = []
    for p in root.protocols:
        if p.name == 'restxml':
            formats.append('xml')
        if p.name == 'restjson':
            formats.append('json')

    api = {
        'base_url': host_url + root._webpath,
        'version': '0.1',
        'name': getattr(root, 'name', 'name'),
        'authority': '',
        'formats': ['json', 'xml'],
        'methods': methods
    }

    return json.dumps(api, indent=4)
Exemplo n.º 13
0
def from_params(datatype, params, path, hit_paths):
    if iscomplex(datatype) and datatype is not File:
        objfound = False
        for key in params:
            if key.startswith(path + '.'):
                objfound = True
                break
        if objfound:
            r = datatype()
            for attrdef in list_attributes(datatype):
                value = from_params(attrdef.datatype, params,
                                    '%s.%s' % (path, attrdef.key), hit_paths)
                if value is not Unset:
                    setattr(r, attrdef.key, value)
            return r
    else:
        if path in params:
            hit_paths.add(path)
            return from_param(datatype, params[path])
    return Unset
Exemplo n.º 14
0
def from_params(datatype, params, path, hit_paths):
    if iscomplex(datatype) and datatype is not File:
        objfound = False
        for key in params:
            if key.startswith(path + '.'):
                objfound = True
                break
        if objfound:
            r = datatype()
            for attrdef in list_attributes(datatype):
                value = from_params(
                    attrdef.datatype,
                    params, '%s.%s' % (path, attrdef.key), hit_paths
                )
                if value is not Unset:
                    setattr(r, attrdef.key, value)
            return r
    else:
        if path in params:
            hit_paths.add(path)
            return from_param(datatype, params[path])
    return Unset
Exemplo n.º 15
0
    def get_wm_item_prop(item, isparams=False):
        # Add prop into 'properties' and 'required' in 'Items Object'
        # 'Items Object' can be part of 'Schema Object' or 'Items Object',
        # and can use recursively
        prop_dict = {}
        # TODO(shu-mutou): this should be removed for production.
        # prop_dict['obj'] = inspect.getmembers(item)

        _item = item
        if wtypes.iscomplex(item):
            _item = weakref.ref(item)

        for a, i in inspect.getmembers(_item):
            if a == 'datatype':
                datatype = get_type_str(i, prop_dict)
                if datatype == 'array':
                    # if array, do recursively
                    prop_dict['items'] = inspect_wm_schema(i.item_type)
                elif datatype == 'object':
                    # if obuject, do recursively
                    prop_dict['items'] = inspect_wm_schema(i)
            elif a == 'default' and i:
                    prop_dict[to_swag_key(a)] = i
            elif a == 'name' and isparams:
                prop_dict[to_swag_key(a)] = i
            elif a == 'mandatory' and i:
                prop_dict[to_swag_key(a)] = i
            elif a == 'readonly' and i:
                prop_dict[to_swag_key(a)] = i
            elif a == 'doc' and i is not None:
                prop_dict[to_swag_key(a)] = i

        if isparams and prop_dict['type'] in ['object', 'array']:
            prop_dict['schema'] = {'items': prop_dict['items'],
                                   'type': prop_dict['type']}
            del prop_dict['type']
            del prop_dict['items']
        return prop_dict
Exemplo n.º 16
0
    def get_wm_item_prop(item, isparams=False):
        # Add prop into 'properties' and 'required' in 'Items Object'
        # 'Items Object' can be part of 'Schema Object' or 'Items Object',
        # and can use recursively
        prop_dict = {}
        # TODO(shu-mutou): this should be removed for production.
        # prop_dict['obj'] = inspect.getmembers(item)

        _item = item
        if wtypes.iscomplex(item):
            _item = weakref.ref(item)

        for a, i in inspect.getmembers(_item):
            if a == 'datatype':
                datatype = get_type_str(i, prop_dict)
                if datatype == 'array':
                    # if array, do recursively
                    prop_dict['items'] = inspect_wm_schema(i.item_type)
                elif datatype == 'object':
                    # if obuject, do recursively
                    prop_dict['items'] = inspect_wm_schema(i)
            elif a == 'default' and i:
                    prop_dict[to_swag_key(a)] = i
            elif a == 'name' and isparams:
                prop_dict[to_swag_key(a)] = i
            elif a == 'mandatory' and i:
                prop_dict[to_swag_key(a)] = i
            elif a == 'readonly' and i:
                prop_dict[to_swag_key(a)] = i
            elif a == 'doc' and i is not None:
                prop_dict[to_swag_key(a)] = i

        if isparams and prop_dict['type'] in ['object', 'array']:
            prop_dict['schema'] = {'items': prop_dict['items'],
                                   'type': prop_dict['type']}
            del prop_dict['type']
            del prop_dict['items']
        return prop_dict