Exemplo n.º 1
0
    def test_blueprint_doc_called_twice(self, app):
        api = Api(app)
        blp = Blueprint('test', __name__, url_prefix='/test')

        @blp.route('/')
        @blp.doc(summary='Dummy func')
        @blp.doc(description='Do dummy stuff')
        def view_func():
            pass

        api.register_blueprint(blp)
        spec = api.spec.to_dict()
        path = spec['paths']['/test/']
        assert path['get']['summary'] == 'Dummy func'
        assert path['get']['description'] == 'Do dummy stuff'
Exemplo n.º 2
0
    def test_blueprint_response_headers(self, app):
        api = Api(app)
        blp = Blueprint('test', 'test', url_prefix='/test')

        headers = {'X-Header': {'description': 'Custom header'}}

        @blp.route('/')
        @blp.response(headers=headers)
        def func():
            pass

        api.register_blueprint(blp)

        get = api.spec.to_dict()['paths']['/test/']['get']
        assert get['responses']['200']['headers'] == headers
Exemplo n.º 3
0
    def test_blueprint_route_parameters(self, app, openapi_version):
        """Check path parameters docs are merged with auto docs"""
        app.config['OPENAPI_VERSION'] = openapi_version
        api = Api(app)
        blp = Blueprint('test', __name__, url_prefix='/test')

        @blp.route('/<int:item_id>',
                   parameters=[
                       'TestParameter',
                       {
                           'name': 'item_id',
                           'in': 'path',
                           'description': 'Item ID'
                       },
                   ])
        def get(item_id):
            pass

        api.register_blueprint(blp)
        spec = api.spec.to_dict()
        params = spec['paths']['/test/{item_id}']['parameters']
        assert len(params) == 2
        if openapi_version == '2.0':
            assert params == [
                build_ref(api.spec, 'parameter', 'TestParameter'),
                {
                    'name': 'item_id',
                    'in': 'path',
                    'required': True,
                    'description': 'Item ID',
                    'format': 'int32',
                    'type': 'integer'
                },
            ]
        else:
            assert params == [
                build_ref(api.spec, 'parameter', 'TestParameter'),
                {
                    'name': 'item_id',
                    'in': 'path',
                    'required': True,
                    'description': 'Item ID',
                    'schema': {
                        'format': 'int32',
                        'type': 'integer'
                    }
                },
            ]
Exemplo n.º 4
0
    def test_blueprint_pagination(self, app, schemas, openapi_version):
        app.config['OPENAPI_VERSION'] = openapi_version
        api = Api(app)
        blp = Blueprint('test', __name__, url_prefix='/test')

        @blp.route('/')
        @blp.arguments(schemas.QueryArgsSchema, location='query')
        @blp.paginate()
        def func():
            """Dummy view func"""

        api.register_blueprint(blp)
        spec = api.spec.to_dict()

        # Check parameters are documented
        parameters = spec['paths']['/test/']['get']['parameters']
        # Page
        assert parameters[0]['name'] == 'page'
        assert parameters[0]['in'] == 'query'
        assert parameters[0]['required'] is False
        if openapi_version == '2.0':
            assert parameters[0]['type'] == 'integer'
            assert parameters[0]['default'] == 1
            assert parameters[0]['minimum'] == 1
        else:
            assert parameters[0]['schema']['type'] == 'integer'
            assert parameters[0]['schema']['default'] == 1
            assert parameters[0]['schema']['minimum'] == 1
        # Page size
        assert parameters[1]['name'] == 'page_size'
        assert parameters[1]['in'] == 'query'
        assert parameters[1]['required'] is False
        if openapi_version == '2.0':
            assert parameters[1]['type'] == 'integer'
            assert parameters[1]['default'] == 10
            assert parameters[1]['minimum'] == 1
            assert parameters[1]['maximum'] == 100
        else:
            assert parameters[1]['schema']['type'] == 'integer'
            assert parameters[1]['schema']['default'] == 10
            assert parameters[1]['schema']['minimum'] == 1
            assert parameters[1]['schema']['maximum'] == 100
        # Other query string parameters
        assert parameters[1]['in'] == 'query'
        assert parameters[2]['name'] == 'arg1'
        assert parameters[2]['in'] == 'query'
        assert parameters[3]['name'] == 'arg2'
        assert parameters[3]['in'] == 'query'
Exemplo n.º 5
0
    def setup_blp(self):
        blp = Blueprint("tests", "tests")

        TestPagination = self.TestPagination
        TestPageSchema = self.TestPageSchema

        class Pets(MethodView):  # pylint: disable=W0612
            @blp.response(TestPageSchema)
            @paginate()
            def get(self):
                """List pets"""
                return TestPagination.query.order_by(TestPagination.id)

        blp.add_url_rule("", "pets", Pets.as_view("pets"))

        self.api.register_blueprint(blp, base_prefix="/pets", url_prefix="/")
Exemplo n.º 6
0
def load_api(rest_api):
    version_bp = Blueprint("version", "version", url_prefix="/", description="Provides versioning information about the app.")

    @version_bp.route("/api/apiversion")
    def api_verison():
        return {"apiversion": "0.1"}

    @version_bp.route("/api/version")
    def version():
        return {"version": "0.0.1 alpha"}
    
    from variance import api
    rest_api.register_blueprint(api.auth.bp, url_prefix="/api/auth")
    rest_api.register_blueprint(api.units.bp, url_prefix="/api/units")

    logging.info("Variance API blueprints loaded.")
Exemplo n.º 7
0
    def test_blueprint_arguments_description(
            self, app, schemas, description, location_map, openapi_version):
        app.config['OPENAPI_VERSION'] = openapi_version
        api = Api(app)
        blp = Blueprint('test', __name__, url_prefix='/test')
        location, _ = location_map

        @blp.route('/')
        @blp.arguments(
            schemas.DocSchema, description=description, location=location)
        def func():
            pass

        api.register_blueprint(blp)
        get = api.spec.to_dict()['paths']['/test/']['get']
        # OAS3 / json, form, files
        if (
                openapi_version == '3.0.2' and
                location in REQUEST_BODY_CONTENT_TYPE
        ):
            # Body parameter in 'requestBody'
            assert 'requestBody' in get
            if description is not None:
                assert get['requestBody']['description'] == description
            else:
                assert 'description' not in get['requestBody']
        # OAS2 / json
        elif location == 'json':
            parameters = get['parameters']
            # One parameter: the schema
            assert len(parameters) == 1
            assert 'schema' in parameters[0]
            assert 'requestBody' not in get
            if description is not None:
                assert parameters[0]['description'] == description
            else:
                assert 'description' not in parameters[0]
        # OAS2-3 / all
        else:
            parameters = get['parameters']
            # One parameter: the 'field' field in DocSchema
            assert len(parameters) == 1
            assert parameters[0]['name'] == 'field'
            assert 'requestBody' not in get
            # Check the description parameter has no impact.
            # Only the description attribute of the field matters
            assert 'description' not in parameters[0]
Exemplo n.º 8
0
    def test_etag_set_etag_method_not_allowed_warning(
            self, app, method, etag_disabled):
        app.config['ETAG_DISABLED'] = etag_disabled
        blp = Blueprint('test', __name__)

        with pytest.warns(None) as record:
            with app.test_request_context('/', method=method):
                blp.set_etag(None)
            if method in HTTP_METHODS_ALLOWING_SET_ETAG:
                assert not record
            else:
                assert len(record) == 1
                assert record[0].category == UserWarning
                assert str(record[0].message) == (
                    'ETag cannot be set on {} request.'
                    .format(method)
                )
Exemplo n.º 9
0
    def test_blueprint_pagination_documents_error_response(
            self, app, openapi_version, error_code):
        app.config['OPENAPI_VERSION'] = openapi_version
        api = Api(app)
        blp = Blueprint('test', __name__, url_prefix='/test')
        blp.PAGINATION_ARGUMENTS_PARSER.DEFAULT_VALIDATION_STATUS = error_code

        @blp.route('/')
        @blp.paginate(Page)
        def func():
            """Dummy view func"""

        api.register_blueprint(blp)
        spec = api.spec.to_dict()
        assert (spec['paths']['/test/']['get']['responses'][str(error_code)] ==
                build_ref(api.spec, 'response',
                          http.HTTPStatus(error_code).name))
Exemplo n.º 10
0
    def test_blueprint_arguments_multiple(self, app, schemas, openapi_version):
        app.config['OPENAPI_VERSION'] = openapi_version
        api = Api(app)
        blp = Blueprint('test', __name__, url_prefix='/test')
        client = app.test_client()

        @blp.route('/', methods=('POST', ))
        @blp.arguments(schemas.DocSchema)
        @blp.arguments(schemas.QueryArgsSchema, location='query')
        def func(document, query_args):
            return {'document': document, 'query_args': query_args}

        api.register_blueprint(blp)
        spec = api.spec.to_dict()

        # Check parameters are documented
        parameters = spec['paths']['/test/']['post']['parameters']
        assert parameters[0]['name'] == 'arg1'
        assert parameters[0]['in'] == 'query'
        assert parameters[1]['name'] == 'arg2'
        assert parameters[1]['in'] == 'query'

        if openapi_version == '2.0':
            assert len(parameters) == 3
            assert parameters[2]['in'] == 'body'
            assert 'schema' in parameters[2]
        else:
            assert len(parameters) == 2
            assert 'schema' in spec['paths']['/test/']['post']['requestBody'][
                'content']['application/json']

        # Check parameters are passed as arguments to view function
        item_data = {'field': 12}
        response = client.post('/test/',
                               data=json.dumps(item_data),
                               content_type='application/json',
                               query_string={'arg1': 'test'})
        assert response.status_code == 200
        assert response.json == {
            'document': {
                'db_field': 12
            },
            'query_args': {
                'arg1': 'test'
            },
        }
Exemplo n.º 11
0
    def test_api_lazy_registers_error_responses(self, app, openapi_version):
        """Test error responses are registered"""
        app.config["OPENAPI_VERSION"] = openapi_version
        api = Api(app)

        # Declare a dummy response to ensure get_response doesn't fail
        response_1 = {"description": "Reponse 1"}
        api.spec.components.response("Response_1", response_1)

        # No route registered -> default errors not registered
        responses = get_responses(api.spec)
        for status in http.HTTPStatus:
            assert status.name not in responses

        # Register routes with all error responses
        blp = Blueprint("test", "test", url_prefix="/test")

        for status in http.HTTPStatus:

            @blp.route(f"/{status.name}")
            @blp.alt_response(400, status.name)
            def test(val):
                pass

        api.register_blueprint(blp)

        # Errors are now registered
        for status in http.HTTPStatus:
            response = responses[status.name]
            assert response["description"] == status.phrase
            empty_body = (100 <= status < 200) or status in (204, 304)
            if openapi_version == "2.0":
                if empty_body:
                    assert "schema" not in response
                else:
                    assert response["schema"] == build_ref(api.spec, "schema", "Error")
            else:
                if empty_body:
                    assert "content" not in response
                else:
                    assert response["content"] == {
                        "application/json": {
                            "schema": build_ref(api.spec, "schema", "Error")
                        }
                    }
Exemplo n.º 12
0
    def test_blueprint_response_response_object(self, app, schemas):
        api = Api(app)
        blp = Blueprint('test', __name__, url_prefix='/test')
        client = app.test_client()

        @blp.route('/response')
        # Schema is ignored when response object is returned
        @blp.response(200, schemas.DocSchema)
        def func_response():
            return flask.jsonify({"test": "test"}), 201, {'X-header': 'test'}

        api.register_blueprint(blp)

        response = client.get('/test/response')
        assert response.status_code == 201
        assert response.status == '201 CREATED'
        assert response.json == {"test": "test"}
        assert response.headers['X-header'] == 'test'
Exemplo n.º 13
0
    def test_etag_verify_check_etag_warning(self, app, method):
        blp = Blueprint('test', __name__)
        old_item = {'item_id': 1, 'db_field': 0}
        old_etag = blp._generate_etag(old_item)

        with mock.patch.object(app.logger, 'warning') as mock_warning:
            with app.test_request_context('/',
                                          method=method,
                                          headers={'If-Match': old_etag}):
                blp._verify_check_etag()
                if method in ['PUT', 'PATCH', 'DELETE']:
                    assert mock_warning.called
                    mock_warning.reset_mock()
                else:
                    assert not mock_warning.called
                blp.check_etag(old_item)
                blp._verify_check_etag()
                assert not mock_warning.called
Exemplo n.º 14
0
    def test_api_lazy_registers_etag_headers(self, app, openapi_version):
        """Test etag headers are registered"""
        app.config["OPENAPI_VERSION"] = openapi_version
        api = Api(app)

        # Declare dummy components to ensure get_* don't fail
        if openapi_version == "3.0.2":
            header_1 = {"description": "Header 1"}
            api.spec.components.header("Header_1", header_1)
        parameter_1 = {"description": "Parameter 1"}
        api.spec.components.parameter("Parameter_1", "header", parameter_1)

        # No route registered -> etag headers not registered
        if openapi_version == "3.0.2":
            headers = get_headers(api.spec)
            assert headers == {"Header_1": header_1}
        parameters = get_parameters(api.spec)
        assert parameters == {
            "Parameter_1": {**parameter_1, "in": "header", "name": "Parameter_1"}
        }

        # Register routes with etag
        blp = Blueprint("test", "test", url_prefix="/test")

        @blp.route("/etag_get", methods=["GET"])
        @blp.etag
        @blp.response(200)
        def test_get(val):
            pass

        @blp.route("/etag_pet", methods=["PUT"])
        @blp.etag
        @blp.response(200)
        def test_put(val):
            pass

        api.register_blueprint(blp)

        if openapi_version == "3.0.2":
            headers = get_headers(api.spec)
            assert headers["ETAG"] == fs_etag.ETAG_HEADER
        parameters = get_parameters(api.spec)
        assert parameters["IF_NONE_MATCH"] == fs_etag.IF_NONE_MATCH_HEADER
        assert parameters["IF_MATCH"] == fs_etag.IF_MATCH_HEADER
Exemplo n.º 15
0
    def test_blueprint_response_schema(self, app, openapi_version, schemas):
        """Check response schema is correctly documented.

        More specifically, check that:
        - plural response is documented as array in the spec
        - schema is document in the right place w.r.t. OpenAPI version
        """
        app.config['OPENAPI_VERSION'] = openapi_version
        api = Api(app)
        blp = Blueprint('test', 'test', url_prefix='/test')

        @blp.route('/schema_many_false')
        @blp.response(schemas.DocSchema(many=False))
        def many_false():
            pass

        @blp.route('/schema_many_true')
        @blp.response(schemas.DocSchema(many=True))
        def many_true():
            pass

        api.register_blueprint(blp)

        paths = api.spec.to_dict()['paths']

        schema_ref = build_ref(api.spec, 'schema', 'Doc')

        response = paths['/test/schema_many_false']['get']['responses']['200']
        if openapi_version == '2.0':
            assert response['schema'] == schema_ref
        else:
            assert (
                response['content']['application/json']['schema'] ==
                schema_ref
            )

        response = paths['/test/schema_many_true']['get']['responses']['200']
        if openapi_version == '2.0':
            assert response['schema']['items'] == schema_ref
        else:
            assert (
                response['content']['application/json']['schema']['items'] ==
                schema_ref
            )
Exemplo n.º 16
0
    def test_etag_set_etag(self, app, schemas, etag_disabled):
        app.config['ETAG_DISABLED'] = etag_disabled
        blp = Blueprint('test', __name__)
        etag_schema = schemas.DocEtagSchema
        item = {'item_id': 1, 'db_field': 0}
        etag = blp._generate_etag(item)
        etag_with_schema = blp._generate_etag(item, etag_schema)

        with app.test_request_context('/'):
            blp.set_etag(item)
            if not etag_disabled:
                assert _get_etag_ctx()['etag'] == etag
                del _get_etag_ctx()['etag']
            else:
                assert 'etag' not in _get_etag_ctx()
        with app.test_request_context('/', headers={'If-None-Match': etag}):
            if not etag_disabled:
                with pytest.raises(NotModified):
                    blp.set_etag(item)
            else:
                blp.set_etag(item)
                assert 'etag' not in _get_etag_ctx()
        with app.test_request_context(
                '/', headers={'If-None-Match': etag_with_schema}):
            if not etag_disabled:
                with pytest.raises(NotModified):
                    blp.set_etag(item, etag_schema)
            else:
                blp.set_etag(item, etag_schema)
                assert 'etag' not in _get_etag_ctx()
        with app.test_request_context('/', headers={'If-None-Match': 'dummy'}):
            if not etag_disabled:
                blp.set_etag(item)
                assert _get_etag_ctx()['etag'] == etag
                del _get_etag_ctx()['etag']
                blp.set_etag(item, etag_schema)
                assert _get_etag_ctx()['etag'] == etag_with_schema
                del _get_etag_ctx()['etag']
            else:
                blp.set_etag(item)
                assert 'etag' not in _get_etag_ctx()
                blp.set_etag(item, etag_schema)
                assert 'etag' not in _get_etag_ctx()
Exemplo n.º 17
0
    def test_api_any_converter(self, app, openapi_version):
        app.config["OPENAPI_VERSION"] = openapi_version
        api = Api(app)
        blp = Blueprint("test", "test", url_prefix="/test")

        @blp.route('/<any(foo, bar, "foo+bar"):val>')
        def test(val):
            pass

        api.register_blueprint(blp)
        spec = api.spec.to_dict()

        schema = {"type": "string", "enum": ["foo", "bar", "foo+bar"]}
        parameter = {"in": "path", "name": "val", "required": True}
        if openapi_version == "2.0":
            parameter.update(schema)
        else:
            parameter["schema"] = schema
        assert spec["paths"]["/test/{val}"]["parameters"] == [parameter]
Exemplo n.º 18
0
    def test_api_any_converter(self, app, openapi_version):
        app.config['OPENAPI_VERSION'] = openapi_version
        api = Api(app)
        blp = Blueprint('test', 'test', url_prefix='/test')

        @blp.route('/<any(foo, bar, "foo+bar"):val>')
        def test(val):
            pass

        api.register_blueprint(blp)
        spec = api.spec.to_dict()

        schema = {'type': 'string', 'enum': ['foo', 'bar', 'foo+bar']}
        parameter = {'in': 'path', 'name': 'val', 'required': True}
        if openapi_version == '2.0':
            parameter.update(schema)
        else:
            parameter['schema'] = schema
        assert spec['paths']['/test/{val}']['parameters'] == [parameter]
Exemplo n.º 19
0
    def test_blueprint_doc_merged_after_prepare_doc(self, app):
        app.config['OPENAPI_VERSION'] = '3.0.2'
        api = Api(app)
        blp = Blueprint('test', __name__, url_prefix='/test')

        # This is a dummy example. In real-life, use 'example' parameter.
        doc_example = {
            'content': {
                'application/json': {
                    'example': {
                        'test': 123
                    }
                }
            }
        }

        class ItemSchema(ma.Schema):
            if MARSHMALLOW_VERSION_MAJOR < 3:

                class Meta:
                    strict = True

            test = ma.fields.Int()

        @blp.route('/')
        class Resource(MethodView):
            @blp.doc(**{'requestBody': doc_example})
            @blp.doc(**{'responses': {200: doc_example}})
            @blp.arguments(ItemSchema)
            @blp.response(ItemSchema)
            def get(self):
                pass

        api.register_blueprint(blp)
        spec = api.spec.to_dict()
        get = spec['paths']['/test/']['get']
        assert get['requestBody']['content']['application/json'][
            'example'] == {
                'test': 123
            }
        resp = get['responses']['200']
        assert resp['content']['application/json']['example'] == {'test': 123}
        assert 'schema' in resp['content']['application/json']
Exemplo n.º 20
0
    def test_etag_is_deterministic(self):
        """Check etag computation is deterministic

           _generate_etag should return the same value everytime the same
           dictionary is passed. This is not obvious since dictionaries
           are unordered by design. We check this by feeding it different
           OrderedDict instances that are equivalent to the same dictionary.
        """

        blp = Blueprint('test', __name__)

        data = OrderedDict([
            ('a', 1),
            ('b', 2),
            ('c', OrderedDict([('a', 1), ('b', 2)]))
        ])
        etag = blp._generate_etag(data)

        data_copies = [
            OrderedDict([
                ('b', 2),
                ('a', 1),
                ('c', OrderedDict([('a', 1), ('b', 2)])),
            ]),
            OrderedDict([
                ('a', 1),
                ('b', 2),
                ('c', OrderedDict([('b', 2), ('a', 1)])),
            ]),
            OrderedDict([
                ('a', 1),
                ('c', OrderedDict([('a', 1), ('b', 2)])),
                ('b', 2),
            ]),
            OrderedDict([
                ('c', OrderedDict([('a', 1), ('b', 2)])),
                ('b', 2),
                ('a', 1),
            ]),
        ]

        data_copies_etag = [blp._generate_etag(d) for d in data_copies]
        assert all(e == etag for e in data_copies_etag)
Exemplo n.º 21
0
    def test_etag_response_object(self, app):
        api = Api(app)
        blp = Blueprint('test', __name__, url_prefix='/test')
        client = app.test_client()

        @blp.route('/')
        @blp.etag
        @blp.response()
        def func_response_etag():
            # When the view function returns a Response object,
            # the ETag must be specified manually
            blp.set_etag('test')
            return jsonify({})

        api.register_blueprint(blp)

        response = client.get('/test/')
        assert response.json == {}
        assert response.get_etag() == (blp._generate_etag('test'), False)
Exemplo n.º 22
0
    def test_api_register_converter_before_or_after_init(
            self, app, openapi_version):
        app.config["OPENAPI_VERSION"] = openapi_version
        api = Api()
        blp = Blueprint("test", "test", url_prefix="/test")

        class CustomConverter_1(BaseConverter):
            pass

        class CustomConverter_2(BaseConverter):
            pass

        def converter12paramschema(converter):
            return {"type": "custom string 1"}

        def converter22paramschema(converter):
            return {"type": "custom string 2"}

        app.url_map.converters["custom_str_1"] = CustomConverter_1
        app.url_map.converters["custom_str_2"] = CustomConverter_2
        api.register_converter(CustomConverter_1, converter12paramschema)
        api.init_app(app)
        api.register_converter(CustomConverter_2, converter22paramschema)

        @blp.route("/1/<custom_str_1:val>")
        def test_func_1(val):
            pass

        @blp.route("/2/<custom_str_2:val>")
        def test_func_2(val):
            pass

        api.register_blueprint(blp)
        spec = api.spec.to_dict()
        parameter_1 = spec["paths"]["/test/1/{val}"]["parameters"][0]
        parameter_2 = spec["paths"]["/test/2/{val}"]["parameters"][0]
        if openapi_version == "2.0":
            assert parameter_1["type"] == "custom string 1"
            assert parameter_2["type"] == "custom string 2"
        else:
            assert parameter_1["schema"]["type"] == "custom string 1"
            assert parameter_2["schema"]["type"] == "custom string 2"
Exemplo n.º 23
0
    def test_api_register_converter_before_or_after_init(
            self, app, openapi_version):
        app.config['OPENAPI_VERSION'] = openapi_version
        api = Api()
        blp = Blueprint('test', 'test', url_prefix='/test')

        class CustomConverter_1(BaseConverter):
            pass

        class CustomConverter_2(BaseConverter):
            pass

        def converter12paramschema(converter):
            return {'type': 'custom string 1'}

        def converter22paramschema(converter):
            return {'type': 'custom string 2'}

        app.url_map.converters['custom_str_1'] = CustomConverter_1
        app.url_map.converters['custom_str_2'] = CustomConverter_2
        api.register_converter(CustomConverter_1, converter12paramschema)
        api.init_app(app)
        api.register_converter(CustomConverter_2, converter22paramschema)

        @blp.route('/1/<custom_str_1:val>')
        def test_func_1(val):
            pass

        @blp.route('/2/<custom_str_2:val>')
        def test_func_2(val):
            pass

        api.register_blueprint(blp)
        spec = api.spec.to_dict()
        parameter_1 = spec['paths']['/test/1/{val}']['parameters'][0]
        parameter_2 = spec['paths']['/test/2/{val}']['parameters'][0]
        if openapi_version == '2.0':
            assert parameter_1['type'] == 'custom string 1'
            assert parameter_2['type'] == 'custom string 2'
        else:
            assert parameter_1['schema']['type'] == 'custom string 1'
            assert parameter_2['schema']['type'] == 'custom string 2'
Exemplo n.º 24
0
    def test_api_register_converter(self, app, view_type, register,
                                    openapi_version):
        app.config["OPENAPI_VERSION"] = openapi_version
        api = Api(app)
        blp = Blueprint("test", "test", url_prefix="/test")

        class CustomConverter(BaseConverter):
            pass

        def converter2paramschema(converter):
            return {"type": "custom string", "format": "custom format"}

        app.url_map.converters["custom_str"] = CustomConverter
        if register:
            api.register_converter(CustomConverter, converter2paramschema)

        if view_type == "function":

            @blp.route("/<custom_str:val>")
            def test_func(val):
                pass

        else:

            @blp.route("/<custom_str:val>")
            class TestMethod(MethodView):
                def get(self, val):
                    pass

        api.register_blueprint(blp)
        spec = api.spec.to_dict()

        if register:
            schema = {"type": "custom string", "format": "custom format"}
        else:
            schema = {"type": "string"}
        parameter = {"in": "path", "name": "val", "required": True}
        if openapi_version == "2.0":
            parameter.update(schema)
        else:
            parameter["schema"] = schema
        assert spec["paths"]["/test/{val}"]["parameters"] == [parameter]
Exemplo n.º 25
0
    def test_blueprint_alt_response_ref(self, app, openapi_version):
        """Check alternate response passed as reference"""
        app.config['OPENAPI_VERSION'] = openapi_version
        api = Api(app)
        api.spec.components.response('ClientErrorResponse')

        blp = Blueprint('test', 'test', url_prefix='/test')

        @blp.route('/')
        @blp.alt_response(400, "ClientErrorResponse")
        def func():
            pass

        api.register_blueprint(blp)

        paths = api.spec.to_dict()['paths']

        response_ref = build_ref(api.spec, 'response', 'ClientErrorResponse')

        assert paths['/test/']['get']['responses']['400'] == response_ref
Exemplo n.º 26
0
    def test_blueprint_response_description(self, app):
        api = Api(app)
        blp = Blueprint('test', 'test', url_prefix='/test')

        @blp.route('/route_1')
        @blp.response()
        def func_1():
            pass

        @blp.route('/route_2')
        @blp.response(description='Test')
        def func_2():
            pass

        api.register_blueprint(blp)

        get_1 = api.spec.to_dict()['paths']['/test/route_1']['get']
        assert 'description' not in get_1['responses']['200']
        get_2 = api.spec.to_dict()['paths']['/test/route_2']['get']
        assert get_2['responses']['200']['description'] == 'Test'
Exemplo n.º 27
0
    def test_blueprint_response_examples(self, app, openapi_version):
        app.config['OPENAPI_VERSION'] = openapi_version
        api = Api(app)
        blp = Blueprint('test', 'test', url_prefix='/test')

        examples = {
            'example 1': {'summary': 'Example 1', 'value': {'name': 'One'}},
            'example 2': {'summary': 'Example 2', 'value': {'name': 'Two'}},
        }

        @blp.route('/')
        @blp.response(examples=examples)
        def func():
            pass

        api.register_blueprint(blp)

        get = api.spec.to_dict()['paths']['/test/']['get']
        assert get['responses']['200']['content']['application/json'][
            'examples'] == examples
Exemplo n.º 28
0
    def test_blueprint_multiple_registrations(self, app, openapi_version):
        """Check blueprint can be registered multiple times

        The internal doc structure is modified during the reigistration
        process. If it is not deepcopied, the second registration fails.
        """
        app.config['OPENAPI_VERSION'] = openapi_version
        blp = Blueprint('test', __name__, url_prefix='/test')

        @blp.route('/')
        def func():
            pass

        api = Api(app)
        api.register_blueprint(blp)
        spec_1 = api.spec.to_dict()
        api = Api(app)
        api.register_blueprint(blp)
        spec_2 = api.spec.to_dict()
        assert spec_1 == spec_2
Exemplo n.º 29
0
    def test_api_register_blueprint_options(self, app):
        api = Api(app)
        blp = Blueprint('test', 'test', url_prefix='/test1')

        @blp.route('/')
        def test_func():
            return {'response': 'OK'}

        api.register_blueprint(blp, url_prefix='/test2')

        spec = api.spec.to_dict()
        assert '/test1/' not in spec['paths']
        assert '/test2/' in spec['paths']

        client = app.test_client()
        response = client.get('/test1/')
        assert response.status_code == 404
        response = client.get('/test2/')
        assert response.status_code == 200
        assert response.json == {'response': 'OK'}
Exemplo n.º 30
0
    def test_blueprint_doc_function(self, app):
        api = Api(app)
        blp = Blueprint('test', __name__, url_prefix='/test')
        client = app.test_client()

        @blp.route('/', methods=('PUT', 'PATCH', ))
        @blp.doc(summary='Dummy func', description='Do dummy stuff')
        def view_func():
            return {'Value': 'OK'}

        api.register_blueprint(blp)
        spec = api.spec.to_dict()
        path = spec['paths']['/test/']
        for method in ('put', 'patch', ):
            assert path[method]['summary'] == 'Dummy func'
            assert path[method]['description'] == 'Do dummy stuff'

        response = client.put('/test/')
        assert response.status_code == 200
        assert response.json == {'Value': 'OK'}