Beispiel #1
0
    def test_default_endpoint_for_namespace_with_blueprint(self, app):
        blueprint = Blueprint('api', __name__, url_prefix='/api')
        api = restplus.Api(blueprint)
        ns = api.namespace('ns', 'Test namespace')

        @ns.route('/test/')
        class TestResource(restplus.Resource):
            pass

        app.register_blueprint(blueprint)

        with app.test_request_context():
            assert url_for('api.ns_test_resource') == '/api/ns/test/'
Beispiel #2
0
    def test_multiple_default_endpoint_lazy(self, app):
        api = restplus.Api()

        @api.route('/test2/')
        @api.route('/test/')
        class TestResource(restplus.Resource):
            pass

        api.init_app(app)

        with app.test_request_context():
            assert url_for('test_resource') == '/test/'
            assert url_for('test_resource_2') == '/test2/'
    def test_accept_default_any_pick_first(self):
        api = restplus.Api(self.app)

        @api.representation('text/plain')
        def text_rep(data, status_code, headers=None):
            resp = self.app.make_response((str(data), status_code, headers))
            return resp

        api.add_resource(Foo, '/test/')

        res = self.get('/test/', headers=[('Accept', '*/*')])
        self.assertEqual(res.status_code, 200)
        self.assertEqual(res.content_type, 'application/json')
Beispiel #4
0
    def test_handle_api_error(self, app, client):
        api = restplus.Api(app)

        @api.route('/api', endpoint='api')
        class Test(restplus.Resource):
            def get(self):
                abort(404)

        response = client.get("/api")
        assert response.status_code == 404
        assert response.headers['Content-Type'] == 'application/json'
        data = json.loads(response.data.decode())
        assert 'message' in data
    def test_add_two_conflicting_resources_on_same_endpoint(self):
        api = restplus.Api(self.app)

        class Foo1(restplus.Resource):
            def get(self):
                return 'foo1'

        class Foo2(restplus.Resource):
            def get(self):
                return 'foo2'

        api.add_resource(Foo1, '/foo', endpoint='bar')
        self.assertRaises(ValueError, api.add_resource, Foo2, '/foo/toto', endpoint='bar')
Beispiel #6
0
    def _setup_api_format_checker_tests(self, format_checker=None):
        class IPAddress(restplus.fields.Raw):
            __schema_type__ = 'string'
            __schema_format__ = 'ipv4'

        api = restplus.Api(self.app, format_checker=format_checker)
        model = api.model('MyModel', {'ip': IPAddress(required=True)})

        @api.route('/format_checker/')
        class TestResource(restplus.Resource):
            @api.expect(model, validate=True)
            def post(self):
                return {}
Beispiel #7
0
    def test_custom_apidoc_page(self):
        api = restplus.Api(self.app, version='1.0')
        content = 'My Custom API Doc'

        @api.documentation
        def api_doc():
            return content

        with self.context():
            with self.app.test_client() as client:
                response = client.get(url_for('doc'))
                self.assertEquals(response.status_code, 200)
                self.assertEquals(response.data.decode('utf8'), content)
Beispiel #8
0
    def test_empty_payload(self, app, client):
        api = restplus.Api(app, validate=True)

        @api.route('/empty/')
        class Payload(restplus.Resource):
            def post(self):

                return {}

        response = client.post('/empty/', data='',
                               headers={'content-type': 'application/json'})

        assert response.status_code == 200
    def test_apidoc_doc_jsoneditor_parameter(self, app, client):
        restplus.Api(app)

        response = client.get(url_for('doc'))
        assert 'jsonEditor: false' in str(response.data)

        app.config['SWAGGER_UI_JSONEDITOR'] = False
        response = client.get(url_for('doc'))
        assert 'jsonEditor: false' in str(response.data)

        app.config['SWAGGER_UI_JSONEDITOR'] = True
        response = client.get(url_for('doc'))
        assert 'jsonEditor: true' in str(response.data)
Beispiel #10
0
    def test_multiple_default_endpoint_lazy(self):
        api = restplus.Api()

        @api.route('/test2/')
        @api.route('/test/')
        class TestResource(restplus.Resource):
            pass

        api.init_app(self.app)

        with self.context():
            self.assertEqual(url_for('test_resource'), '/test/')
            self.assertEqual(url_for('test_resource_2'), '/test2/')
    def test_apidoc_doc_expansion_parameter(self, app, client):
        restplus.Api(app)

        response = client.get(url_for('doc'))
        assert 'docExpansion: "none"' in str(response.data)

        app.config['SWAGGER_UI_DOC_EXPANSION'] = 'list'
        response = client.get(url_for('doc'))
        assert 'docExpansion: "list"' in str(response.data)

        app.config['SWAGGER_UI_DOC_EXPANSION'] = 'full'
        response = client.get(url_for('doc'))
        assert 'docExpansion: "full"' in str(response.data)
Beispiel #12
0
    def setUp(self):
        """Initialize the app with the corresponding logic."""
        self.app = flask.Flask(__name__)
        self.app.testing = True

        api = restplus.Api(self.app)
        cors = webutils.cors(origin='*',
                             content_type='application/json',
                             credentials=False)
        self.impl = mock.Mock()

        server.init(api, cors, self.impl)
        self.client = self.app.test_client()
Beispiel #13
0
    def test_export_with_swagger(self):
        api = restplus.Api(self.app)

        data = api.as_postman(swagger=True)

        validate(data, schema)

        self.assertEqual(len(data['requests']), 1)
        request = data['requests'][0]
        self.assertEqual(request['name'], 'Swagger specifications')
        self.assertEqual(request['description'],
                         'The API Swagger specifications as JSON')
        self.assertEqual(request['url'], 'http://localhost/swagger.json')
Beispiel #14
0
    def test_apidoc_doc_display_request_duration(self, app, client):
        restplus.Api(app)

        response = client.get(url_for('doc'))
        assert 'displayRequestDuration: false' in str(response.data)

        app.config['SWAGGER_UI_REQUEST_DURATION'] = False
        response = client.get(url_for('doc'))
        assert 'displayRequestDuration: false' in str(response.data)

        app.config['SWAGGER_UI_REQUEST_DURATION'] = True
        response = client.get(url_for('doc'))
        assert 'displayRequestDuration: true' in str(response.data)
Beispiel #15
0
    def test_ns_path_prefixes(self, app):
        api = restplus.Api()
        ns = restplus.Namespace('test_ns', description='Test namespace')

        @ns.route('/test/', endpoint='test_resource')
        class TestResource(restplus.Resource):
            pass

        api.add_namespace(ns, '/api_test')
        api.init_app(app)

        with app.test_request_context():
            assert url_for('test_resource') == '/api_test/test/'
Beispiel #16
0
    def test_apidoc_doc_display_operation_id(self, app, client):
        restplus.Api(app)

        response = client.get(url_for('doc'))
        assert 'displayOperationId: false' in str(response.data)

        app.config['SWAGGER_UI_OPERATION_ID'] = False
        response = client.get(url_for('doc'))
        assert 'displayOperationId: false' in str(response.data)

        app.config['SWAGGER_UI_OPERATION_ID'] = True
        response = client.get(url_for('doc'))
        assert 'displayOperationId: true' in str(response.data)
Beispiel #17
0
    def test_errorhandler_swagger_doc(self, app, client):
        api = restplus.Api(app)

        class CustomException(RuntimeError):
            pass

        error = api.model('Error', {
            'message': restplus.fields.String()
        })

        @api.route('/test/', endpoint='test')
        class TestResource(restplus.Resource):
            def get(self):
                '''
                Do something

                :raises CustomException: In case of something
                '''
                pass

        @api.errorhandler(CustomException)
        @api.header('Custom-Header', 'Some custom header')
        @api.marshal_with(error, code=503)
        def handle_custom_exception(error):
            '''Some description'''
            pass

        specs = client.get_specs()

        assert 'Error' in specs['definitions']
        assert 'CustomException' in specs['responses']

        response = specs['responses']['CustomException']
        assert response['description'] == 'Some description'
        assert response['schema'] == {
            '$ref': '#/definitions/Error'
        }
        assert response['headers'] == {
            'Custom-Header': {
                'description': 'Some custom header',
                'type': 'string'
            }
        }

        operation = specs['paths']['/test/']['get']
        assert 'responses' in operation
        assert operation['responses'] == {
            '503': {
                '$ref': '#/responses/CustomException'
            }
        }
Beispiel #18
0
    def test_apidoc_doc_minified(self):
        restplus.Api(self.app)

        self.app.config['DEBUG'] = True
        with self.context():
            with self.app.test_client() as client:
                response = client.get(url_for('doc'))
                self.assertIn('swagger-ui.js', str(response.data))

        self.app.config['DEBUG'] = False
        with self.context():
            with self.app.test_client() as client:
                response = client.get(url_for('doc'))
                self.assertIn('swagger-ui.min.js', str(response.data))
Beispiel #19
0
    def test_apidoc_with_custom_validator(self):
        self.app.config[
            'SWAGGER_VALIDATOR_URL'] = 'http://somewhere.com/validator'
        restplus.Api(self.app, version='1.0')

        with self.context():
            with self.app.test_client() as client:
                response = client.get(url_for('doc'))
                self.assertEquals(response.status_code, 200)
                self.assertEquals(response.content_type,
                                  'text/html; charset=utf-8')
                self.assertIn(
                    'validatorUrl: "http://somewhere.com/validator" || null,',
                    str(response.data))
Beispiel #20
0
    def test_multiple_default_endpoint_lazy_for_namespace(self, app):
        api = restplus.Api()
        ns = api.namespace('ns', 'Test namespace')

        @ns.route('/test2/')
        @ns.route('/test/')
        class TestResource(restplus.Resource):
            pass

        api.init_app(app)

        with app.test_request_context():
            assert url_for('ns_test_resource') == '/ns/test/'
            assert url_for('ns_test_resource_2') == '/ns/test2/'
    def test_apidoc_try_it_out_feature_flag_parameter(self, app, client):
        restplus.Api(app)

        # assert that with no config then 'Try it Out' is enabled as is default in swagger-ui
        response = client.get(url_for('doc'))
        assert re.compile("plugins.*?\[.*?DisableTryItOut.*?\]").match(str(response.data)) is None

        app.config['SWAGGER_UI_TRY_IT_OUT'] = True
        response = client.get(url_for('doc'))
        assert re.compile("plugins.*?\[.*?DisableTryItOut.*?\]").match(str(response.data)) is None

        app.config['SWAGGER_UI_TRY_IT_OUT'] = False
        response = client.get(url_for('doc'))
        assert re.compile("plugins.*?\[.*?DisableTryItOut.*?\]").search(str(response.data), re.MULTILINE)
    def test_custom_apidoc_page_lazy(self, app, client):
        blueprint = Blueprint('api', __name__, url_prefix='/api')
        api = restplus.Api(blueprint, version='1.0')
        content = 'My Custom API Doc'

        @api.documentation
        def api_doc():
            return content

        app.register_blueprint(blueprint)

        response = client.get(url_for('api.doc'))
        assert response.status_code == 200
        assert response.data.decode('utf8') == content
Beispiel #23
0
    def test_abort_on_exception(self, app, client):
        api = restplus.Api(app)

        @api.route('/test/', endpoint='test')
        class TestResource(restplus.Resource):
            def get(self):
                raise ValueError()

        response = client.get('/test/')
        assert response.status_code == 500
        assert response.content_type == 'application/json'

        data = json.loads(response.data.decode('utf8'))
        assert 'message' in data
Beispiel #24
0
    def test_default_errorhandler(self, app, client):
        api = restplus.Api(app)

        @api.route('/test/')
        class TestResource(restplus.Resource):
            def get(self):
                raise Exception('error')

        response = client.get('/test/')
        assert response.status_code == 500
        assert response.content_type == 'application/json'

        data = json.loads(response.data.decode('utf8'))
        assert 'message' in data
Beispiel #25
0
    def test_abort_with_message(self, app, client):
        api = restplus.Api(app)

        @api.route('/test/', endpoint='test')
        class TestResource(restplus.Resource):
            def get(self):
                api.abort(403, 'A message')

        response = client.get('/test/')
        assert response.status_code == 403
        assert response.content_type == 'application/json'

        data = json.loads(response.data.decode('utf8'))
        assert data['message'] == 'A message'
    def test_export_infos(self):
        api = restplus.Api(
            self.app,
            version='1.0',
            title='My API',
            description='This is a testing API',
        )

        data = api.as_postman()

        validate(data, schema)

        self.assertEqual(data['name'], 'My API 1.0')
        self.assertEqual(data['description'], 'This is a testing API')
Beispiel #27
0
    def test_handle_api_error(self):
        api = restplus.Api(self.app)

        @api.route('/api', endpoint='api')
        class Test(restplus.Resource):
            def get(self):
                abort(404)

        with self.app.test_client() as client:
            response = client.get("/api")
            self.assertEquals(response.status_code, 404)
            self.assertEquals(response.headers['Content-Type'], 'application/json')
            data = json.loads(response.data.decode())
            self.assertIn('message', data)
Beispiel #28
0
    def test_accept_no_default_custom_repr_not_acceptable(self, app, client):
        api = restplus.Api(app, default_mediatype=None)
        api.representations = {}

        @api.representation('text/plain')
        def text_rep(data, status_code, headers=None):
            resp = app.make_response((str(data), status_code, headers))
            return resp

        api.add_resource(Foo, '/test/')

        res = client.get('/test/', headers=[('Accept', 'application/json')])
        assert res.status_code == 406
        assert res.content_type == 'text/plain'
Beispiel #29
0
    def test_accept_no_default_custom_repr_match(self):
        api = restplus.Api(self.app, default_mediatype=None)
        api.representations = {}

        @api.representation('text/plain')
        def text_rep(data, status_code, headers=None):
            resp = self.app.make_response((str(data), status_code, headers))
            return resp

        api.add_resource(Foo, '/test/')

        res = self.get('/test/', headers=[('Accept', 'text/plain')])
        self.assertEqual(res.status_code, 200)
        self.assertEqual(res.content_type, 'text/plain')
Beispiel #30
0
    def test_accept_no_default_accept_highest_quality_of_three(self):
        api = restplus.Api(self.app, default_mediatype=None)

        @api.representation('text/html')
        @api.representation('text/plain')
        def text_rep(data, status_code, headers=None):
            resp = self.app.make_response((str(data), status_code, headers))
            return resp

        api.add_resource(Foo, '/test/')

        res = self.get('/test/', headers=[('Accept', 'application/json; q=0.1, text/plain; q=0.3, text/html; q=0.2')])
        self.assertEqual(res.status_code, 200)
        self.assertEqual(res.content_type, 'text/plain')