Exemple #1
0
    def test_schema_in_docstring_expand_parameters(self, spec):
        def pet_view():
            """Not much to see here.

            ---
            get:
                parameters:
                    - in: query
                      schema: tests.schemas.PetSchema
            post:
                parameters:
                    - in: body
                      schema: tests.schemas.PetSchema
            """
            return '...'

        spec.add_path(path='/pet', view=pet_view)
        p = spec._paths['/pet']
        assert 'get' in p
        get = p['get']
        assert 'parameters' in get
        assert get['parameters'] == swagger.schema2parameters(
            PetSchema, default_in='query')
        post = p['post']
        assert 'parameters' in post
        assert post['parameters'] == swagger.schema2parameters(
            PetSchema, default_in='body')
Exemple #2
0
    def test_schema_body_with_dump_only(self):
        class UserSchema(Schema):
            name = fields.Str()
            email = fields.Email(dump_only=True)

        res_dump = swagger.schema2parameters(UserSchema,
                                             default_in='body',
                                             dump=True)
        assert len(res_dump) == 1
        param = res_dump[0]
        assert param['in'] == 'body'
        assert param['schema'] == swagger.schema2jsonschema(UserSchema,
                                                            dump=True)
        assert set(param['schema']['properties'].keys()) == {'name', 'email'}
        assert param['schema']['properties']['email']['readOnly'] is True

        res_nodump = swagger.schema2parameters(UserSchema,
                                               default_in='body',
                                               dump=False)
        assert len(res_nodump) == 1
        param = res_nodump[0]
        assert param['in'] == 'body'
        assert param['schema'] == swagger.schema2jsonschema(UserSchema,
                                                            dump=False)
        assert set(param['schema']['properties'].keys()) == {'name'}
Exemple #3
0
    def test_schema_query_instance_many_should_raise_exception(self):
        class UserSchema(Schema):
            name = fields.Str()
            email = fields.Email()

        with pytest.raises(AssertionError):
            swagger.schema2parameters(UserSchema(many=True), default_in='query')
    def test_schema_in_docstring_expand_parameters_v3(self, spec_3):
        def pet_view():
            """Not much to see here.

            ---
            get:
                parameters:
                    - in: query
                      schema: tests.schemas.PetSchema
            post:
                parameters:
                    - in: body
                      description: "a pet schema"
                      required: true
                      name: pet
                      schema: tests.schemas.PetSchema
            """
            return '...'

        spec_3.add_path(path='/pet', view=pet_view)
        p = spec_3._paths['/pet']
        assert 'get' in p
        get = p['get']
        assert 'parameters' in get
        assert get['parameters'] == swagger.schema2parameters(
            PetSchema, default_in='query', spec=spec_3)
        post = p['post']
        assert 'parameters' in post
        post_parameters = swagger.schema2parameters(PetSchema,
                                                    default_in='body',
                                                    required=True,
                                                    name='pet',
                                                    description='a pet schema',
                                                    spec=spec_3)
        assert post['parameters'] == post_parameters
    def _endpoint_schemas2swagger_parameters(self, endpoint_schemas):
        parameters = []
        if 'path' in endpoint_schemas:
            parameters += schema2parameters(endpoint_schemas['path'],
                                            default_in="path")

        if 'query' in endpoint_schemas:
            parameters += schema2parameters(endpoint_schemas['query'],
                                            default_in="query")

        if 'header' in endpoint_schemas:
            parameters += schema2parameters(endpoint_schemas['header'],
                                            default_in="header")

        if 'body' in endpoint_schemas:
            parameters += [{
                'in': 'body',
                'name': 'body',
                'required': True,
                'schema': {
                    '$ref':
                    "#/definitions/" + endpoint_schemas['body'].__name__
                }
            }]

        return parameters
Exemple #6
0
def test_swagger_tools_validate():
    spec = APISpec(
        title='Pets',
        version='0.1',
        plugins=['apispec.ext.marshmallow'],
    )

    spec.definition('Category', schema=CategorySchema)
    spec.definition('Pet', schema=PetSchema)

    spec.add_path(
        view=None,
        path='/category/{category_id}',
        operations={
            'get': {
                'parameters': [
                    {'name': 'q', 'in': 'query', 'type': 'string'},
                    {'name': 'category_id', 'in': 'path', 'required': True, 'type': 'string'},
                    field2parameter(
                        field=fields.List(
                            fields.Str(),
                            validate=validate.OneOf(['freddie', 'roger']),
                            location='querystring',
                        ),
                        name='body',
                        use_refs=False,
                    ),
                ] + swagger.schema2parameters(PageSchema, default_in='query'),
                'responses': {
                    200: {
                        'schema': PetSchema,
                        'description': 'A pet',
                    },
                },
            },
            'post': {
                'parameters': (
                    [{'name': 'category_id', 'in': 'path', 'required': True, 'type': 'string'}] +
                    swagger.schema2parameters(CategorySchema, spec=spec, default_in='body')
                ),
                'responses': {
                    201: {
                        'schema': PetSchema,
                        'description': 'A pet',
                    },
                },
            }
        },
    )
    try:
        utils.validate_swagger(spec)
    except exceptions.SwaggerError as error:
        pytest.fail(str(error))
Exemple #7
0
def convert_schemas(d, definitions=None):
    if Schema is None:
        raise RuntimeError('Please install marshmallow and apispec')

    new = {}
    for k, v in d.items():
        if isinstance(v, dict):
            v = convert_schemas(v, definitions)
        if isinstance(v, (list, tuple)):
            new_v = []
            for item in v:
                if isinstance(item, dict):
                    new_v.append(convert_schemas(item, definitions))
                else:
                    new_v.append(item)
            v = new_v
        if inspect.isclass(v) and issubclass(v, Schema):
            definitions[v.__name__] = schema2jsonschema(v)
            ref = {"$ref": "#/definitions/{0}".format(v.__name__)}
            if k == 'parameters':
                new[k] = schema2parameters(v)
                new[k][0]['schema'] = ref
            else:
                new[k] = ref
        else:
            new[k] = v

        if k == 'definitions':
            new['definitions'] = definitions
    return new
Exemple #8
0
 def test_schema_body(self):
     class UserSchema(Schema):
         name = fields.Str()
         email = fields.Email()
     res = swagger.schema2parameters(UserSchema, default_in='body')
     assert len(res) == 1
     param = res[0]
     assert param['in'] == 'body'
     assert param['schema'] == swagger.schema2jsonschema(UserSchema)
Exemple #9
0
 def wrapper(func):
     if not hasattr(func, '__apispec__'):
         func.__apispec__ = {
             'parameters': [],
             'responses': {},
             'docked': {}
         }
     func.__apispec__['responses']['%s' % code] = schema2parameters(
         schema, required=required)[0]
     return func
Exemple #10
0
    def wrapper(func):
        parameters = schema2parameters(schema, **options)
        if not hasattr(func, '__apispec__'):
            func.__apispec__ = {'parameters': [], 'responses': {}}
        func.__apispec__['parameters'].extend(parameters)
        if not hasattr(func, '__schemas__'):
            func.__schemas__ = []
        func.__schemas__.append({'schema': schema, 'locations': locations})

        return func
Exemple #11
0
 def test_schema_query(self):
     class UserSchema(Schema):
         name = fields.Str()
         email = fields.Email()
     res = swagger.schema2parameters(UserSchema, default_in='query')
     assert len(res) == 2
     res.sort(key=lambda param: param['name'])
     assert res[0]['name'] == 'email'
     assert res[0]['in'] == 'query'
     assert res[1]['name'] == 'name'
     assert res[1]['in'] == 'query'
Exemple #12
0
    def test_schema_body_many(self):
        class UserSchema(Schema):
            name = fields.Str()
            email = fields.Email()

        res = swagger.schema2parameters(UserSchema(many=True), default_in='body')
        assert len(res) == 1
        param = res[0]
        assert param['in'] == 'body'
        assert param['schema']['type'] == 'array'
        assert param['schema']['items']['type'] == 'object'
        assert param['schema']['items'] == swagger.schema2jsonschema(UserSchema)
 def wrapper(func):
     if not hasattr(func, '__apispec__'):
         func.__apispec__ = {'parameters': [], 'responses': {}}
     raw_parameters = schema2parameters(schema, required=required)[0]
     # https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#responseObject
     parameters = {
         k: v
         for k, v in raw_parameters.items() if k in VALID_RESPONSE_FIELDS
     }
     if description:
         parameters['description'] = description
     func.__apispec__['responses']['%s' % code] = parameters
     return func
    def wrapper(func):
        parameters = schema2parameters(schema, **options)
        if not hasattr(func, '__apispec__'):
            func.__apispec__ = {'parameters': [], 'responses': {}}
        func.__apispec__['parameters'].extend(parameters)
        if not hasattr(func, '__schemas__'):
            func.__schemas__ = []
        if locations and 'body' in locations:
            body_schema_exists = ('body' in func_schema['locations']
                                  for func_schema in func.__schemas__)
            if any(body_schema_exists):
                raise RuntimeError('Multiple body parameters are not allowed')
        func.__schemas__.append({'schema': schema, 'locations': locations})

        return func
    def parameters_for(self, doc):
        schema = doc['params']

        if not schema:
            return []
        if isinstance(schema, list):
            return schema
        if isinstance(schema, dict) and all(isinstance(field, dict) for field in schema.values()):
            return list(schema.values())

        if 'in' in schema.context and 'json' in schema.context['in']:
            default_location = 'body'
        else:
            default_location = 'query'
        return schema2parameters(schema, default_in=default_location, required=True)
Exemple #16
0
    def _(method):
        """Validate request body through schema
        and fill parameters info fot apispec module
        :param method: aiohttp handler method
        :return: aiohttp handler method
        """
        parameters = None
        if default_in in ('query', 'formData'):
            parameters = schema2parameters(serializer, default_in=default_in)
        elif default_in == 'body':
            parameters = [{
                'name':
                'data',
                'in':
                'body',
                'schema':
                serializer.__class__.__name__.strip('Schema'),
            }]
        if parameters:
            method.apispec = dict(
                parameters=parameters,
                **getattr(method, 'apispec', dict()),
            )

        @functools.wraps(method)
        async def wrapper(self):
            if self.request.headers.get(
                    hdrs.CONTENT_TYPE) == 'application/json':
                self.request.arguments = await self.request.json()
            else:
                self.request.arguments = await self.request.post()

            error_response = text_error_response

            if self.request.headers.get(hdrs.ACCEPT) == 'application/json':
                error_response = web.json_response

            self.request.arguments, errors = serializer.load(
                get_schema_data(serializer, self.request.arguments))

            if errors:
                return error_response(data=errors,
                                      reason='Bad arguments',
                                      status=400)

            return await method(self)

        return wrapper
    def test_schema_in_docstring_expand_parameters_v3(self, spec_3):
        def pet_view():
            """Not much to see here.

            ---
            get:
                parameters:
                    - in: query
                      schema: tests.schemas.PetSchema
                responses:
                    201:
                        description: successful operation
            post:
                requestBody:
                    description: "a pet schema"
                    required: true
                    content:
                        application/json:
                            schema: tests.schemas.PetSchema
                responses:
                    201:
                        description: successful operation
            """
            return '...'

        spec_3.add_path(path='/pet', view=pet_view)
        p = spec_3._paths['/pet']

        assert 'get' in p
        get = p['get']
        assert 'parameters' in get
        assert get['parameters'] == swagger.schema2parameters(
            PetSchema, default_in='query', spec=spec_3)
        for parameter in get['parameters']:
            description = parameter.get('description', False)
            assert description
            name = parameter['name']
            assert description == PetSchema.description[name]

        assert 'post' in p
        post = p['post']
        assert 'requestBody' in post
        post_schema = resolve_schema_dict(spec_3, PetSchema)
        assert post['requestBody']['content']['application/json'][
            'schema'] == post_schema
        assert post['requestBody']['description'] == 'a pet schema'
        assert post['requestBody']['required']
Exemple #18
0
    def wrapper(func):
        parameters = schema2parameters(schema,
                                       default_in=location,
                                       required=required)
        # print(parameters)
        if not hasattr(func, '__apispec__'):
            func.__apispec__ = {
                'parameters': [],
                'responses': {},
                'docked': {}
            }
        func.__apispec__['parameters'].extend(parameters)
        if not hasattr(func, '__schemas__'):
            func.__schemas__ = []
        func.__schemas__.append({'schema': schema, 'location': location})

        return func
def convert_schemas(d, definitions=None):
    """
    Convert Marshmallow schemas to dict definitions

    Also updates the optional definitions argument with any definitions
    entries contained within the schema.
    """
    if Schema is None:
        raise RuntimeError('Please install marshmallow and apispec')

    if definitions is None:
        definitions = {}
    definitions.update(d.get('definitions', {}))

    new = {}
    for k, v in d.items():
        if isinstance(v, dict):
            v = convert_schemas(v, definitions)
        if isinstance(v, (list, tuple)):
            new_v = []
            for item in v:
                if isinstance(item, dict):
                    new_v.append(convert_schemas(item, definitions))
                else:
                    new_v.append(item)
            v = new_v
        if inspect.isclass(v) and issubclass(v, Schema):
            definitions[v.__name__] = schema2jsonschema(v)
            ref = {"$ref": "#/definitions/{0}".format(v.__name__)}
            if k == 'parameters':
                new[k] = schema2parameters(v)
                new[k][0]['schema'] = ref
            else:
                new[k] = ref
        else:
            new[k] = v

    # This key is not permitted anywhere except the very top level.
    if 'definitions' in new:
        del new['definitions']

    return new
Exemple #20
0
 def test_invalid_schema(self):
     with pytest.raises(ValueError):
         swagger.schema2parameters(None)
 def _generate_swagger_definitions_tree(self):
     definitions = {}
     for schema in self.swagger_definition_schemas:
         definitions[schema.__name__] = schema2parameters(
             schema)[0]['schema']
     return definitions
Exemple #22
0
 def test_schema_global_state_untouched_2parameters(self):
     assert RunSchema._declared_fields['sample']._Nested__schema is None
     data = swagger.schema2parameters(RunSchema)
     json.dumps(data)
     assert RunSchema._declared_fields['sample']._Nested__schema is None
Exemple #23
0
         {
             'name': 'category_id',
             'in': 'path',
             'required': True,
             'type': 'string'
         },
         field2parameter(
             field=fields.List(
                 fields.Str(),
                 validate=validate.OneOf(['freddie', 'roger']),
                 location='querystring',
             ),
             name='body',
             use_refs=False,
         ),
     ] + swagger.schema2parameters(PageSchema, default_in='query'),
     'responses': {
         200: {
             'schema': PetSchema,
             'description': 'A pet',
         },
     },
 },
 'post': {
     'parameters': ([{
         'name': 'category_id',
         'in': 'path',
         'required': True,
         'type': 'string'
     }] + swagger.schema2parameters(
         CategorySchema, spec=spec, default_in='body')),