def test_non_blueprint_rest_error_routing(self):
     blueprint = Blueprint('test', __name__)
     api = flask_restbolt.Api(blueprint)
     api.add_resource(HelloWorld(), '/hi', endpoint="hello")
     api.add_resource(GoodbyeWorld(404), '/bye', endpoint="bye")
     app = Flask(__name__)
     app.register_blueprint(blueprint, url_prefix='/blueprint')
     api2 = flask_restbolt.Api(app)
     api2.add_resource(HelloWorld(), '/hi', endpoint="hello")
     api2.add_resource(GoodbyeWorld(404), '/bye', endpoint="bye")
     with app.test_request_context('/hi', method='POST'):
         assert_false(api._should_use_fr_error_handler())
         assert_true(api2._should_use_fr_error_handler())
         assert_false(api._has_fr_route())
         assert_true(api2._has_fr_route())
     with app.test_request_context('/blueprint/hi', method='POST'):
         assert_true(api._should_use_fr_error_handler())
         assert_false(api2._should_use_fr_error_handler())
         assert_true(api._has_fr_route())
         assert_false(api2._has_fr_route())
     api._should_use_fr_error_handler = Mock(return_value=False)
     api2._should_use_fr_error_handler = Mock(return_value=False)
     with app.test_request_context('/bye'):
         assert_false(api._has_fr_route())
         assert_true(api2._has_fr_route())
     with app.test_request_context('/blueprint/bye'):
         assert_true(api._has_fr_route())
         assert_false(api2._has_fr_route())
 def test_api_delayed_initialization(self):
     blueprint = Blueprint('test', __name__)
     api = flask_restbolt.Api()
     api.init_app(blueprint)
     app = Flask(__name__)
     app.register_blueprint(blueprint)
     api.add_resource(HelloWorld, '/', endpoint="hello")
Ejemplo n.º 3
0
    def test_accept_no_default_accept_highest_quality_of_three(self):
        class Foo(flask_restbolt.Resource):
            def get(self):
                return "data"

        app = Flask(__name__)
        api = flask_restbolt.Api(app, default_mediatype=None)

        @api.representation('text/html')
        @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, '/')

        with app.test_client() as client:
            res = client.get(
                '/',
                headers=
                [('Accept',
                  'application/json; q=0.1, text/plain; q=0.3, text/html; q=0.2'
                  )])
            assert_equals(res.status_code, 200)
            assert_equals(res.content_type, 'text/plain')
Ejemplo n.º 4
0
    def test_handle_smart_errors(self):
        app = Flask(__name__)
        api = flask_restbolt.Api(app)
        view = flask_restbolt.Resource

        api.add_resource(view, '/foo', endpoint='bor')
        api.add_resource(view, '/fee', endpoint='bir')
        api.add_resource(view, '/fii', endpoint='ber')

        with app.test_request_context("/faaaaa"):
            resp = api.handle_error(NotFound())
            self.assertEquals(resp.status_code, 404)
            self.assertEquals(
                resp.data.decode(),
                dumps({
                    "message": NotFound.description,
                }) + "\n")

        with app.test_request_context("/fOo"):
            resp = api.handle_error(NotFound())
            self.assertEquals(resp.status_code, 404)
            self.assertTrue('did you mean /foo ?' in resp.data.decode())

        app.config['ERROR_404_HELP'] = False

        with app.test_request_context("/fOo"):
            resp = api.handle_error(NotFound())
            self.assertEquals(resp.status_code, 404)
            self.assertEquals(resp.data.decode(),
                              dumps({"message": NotFound.description}) + "\n")
Ejemplo n.º 5
0
    def test_non_api_error_404_catchall(self):
        app = Flask(__name__)
        api = flask_restbolt.Api(app, catch_all_404s=True)
        app = app.test_client()

        resp = app.get("/foo")
        self.assertEquals(api.default_mediatype, resp.headers['Content-Type'])
Ejemplo n.º 6
0
    def test_media_types(self):
        app = Flask(__name__)
        api = flask_restbolt.Api(app)

        with app.test_request_context("/foo",
                                      headers={'Accept': 'application/json'}):
            self.assertEquals(api.mediatypes(), ['application/json'])
Ejemplo n.º 7
0
 def test_api_base(self):
     app = Mock()
     app.configure_mock(**{'record.side_effect': AttributeError})
     api = flask_restbolt.Api(app)
     self.assertEquals(api.urls, {})
     self.assertEquals(api.prefix, '')
     self.assertEquals(api.default_mediatype, 'application/json')
Ejemplo n.º 8
0
 def test_api_delayed_initialization(self):
     app = Flask(__name__)
     api = flask_restbolt.Api()
     api.add_resource(HelloWorld, '/', endpoint="hello")
     api.init_app(app)
     with app.test_client() as client:
         self.assertEquals(client.get('/').status_code, 200)
Ejemplo n.º 9
0
    def test_exception_header_forwarded(self):
        """Test that HTTPException's headers are extended properly"""
        app = Flask(__name__)
        app.config['DEBUG'] = True
        api = flask_restbolt.Api(app)

        class NotModified(HTTPException):
            code = 304

            def __init__(self, etag, *args, **kwargs):
                super(NotModified, self).__init__(*args, **kwargs)
                self.etag = quote_etag(etag)

            def get_headers(self, *args, **kwargs):
                """Get a list of headers."""
                return [('ETag', self.etag)]

        class Foo1(flask_restbolt.Resource):
            def get(self):
                flask_abort(304, etag='myETag')

        api.add_resource(Foo1, '/foo')
        flask_abort.mapping.update({304: NotModified})

        with app.test_client() as client:
            foo = client.get('/foo')
            self.assertEquals(foo.get_etag(),
                              unquote_etag(quote_etag('myETag')))
Ejemplo n.º 10
0
    def test_will_prettyprint_json_in_debug_mode(self):
        app = Flask(__name__)
        app.config['DEBUG'] = True
        api = flask_restbolt.Api(app)

        class Foo1(flask_restbolt.Resource):
            def get(self):
                return {'foo': 'bar', 'baz': 'asdf'}

        api.add_resource(Foo1, '/foo', endpoint='bar')

        with app.test_client() as client:
            foo = client.get('/foo')

            # Python's dictionaries have random order (as of "new" Pythons,
            # anyway), so we can't verify the actual output here.  We just
            # assert that they're properly prettyprinted.
            lines = foo.data.splitlines()
            lines = [line.decode() for line in lines]
            self.assertEquals("{", lines[0])
            self.assertTrue(lines[1].startswith('    '))
            self.assertTrue(lines[2].startswith('    '))
            self.assertEquals("}", lines[3])

            # Assert our trailing newline.
            self.assertTrue(foo.data.endswith(b'\n'))
Ejemplo n.º 11
0
    def test_calling_owns_endpoint_before_api_init(self):
        api = flask_restbolt.Api()

        try:
            api.owns_endpoint('endpoint')
        except AttributeError as ae:
            self.fail(ae.message)
Ejemplo n.º 12
0
    def test_custom_error_message(self):
        errors = {
            'FooError': {
                'message': "api is foobar",
                'status': 418,
            }
        }

        class FooError(ValueError):
            pass

        app = Flask(__name__)
        api = flask_restbolt.Api(app, errors=errors)

        exception = FooError()
        exception.code = 400
        exception.data = {'message': 'FooError'}

        with app.test_request_context("/foo"):
            resp = api.handle_error(exception)
            self.assertEquals(resp.status_code, 418)
            self.assertEqual(loads(resp.data.decode('utf8')), {
                "message": "api is foobar",
                "status": 418
            })
 def test_url_with_api_prefix(self):
     blueprint = Blueprint('test', __name__)
     api = flask_restbolt.Api(blueprint, prefix='/api')
     api.add_resource(HelloWorld, '/hi', endpoint='hello')
     app = Flask(__name__)
     app.register_blueprint(blueprint)
     with app.test_request_context('/api/hi'):
         self.assertEquals(request.endpoint, 'test.hello')
 def test_api_base(self):
     blueprint = Blueprint('test', __name__)
     api = flask_restbolt.Api(blueprint)
     app = Flask(__name__)
     app.register_blueprint(blueprint)
     self.assertEquals(api.urls, {})
     self.assertEquals(api.prefix, '')
     self.assertEquals(api.default_mediatype, 'application/json')
Ejemplo n.º 15
0
 def test_unauthorized_no_challenge_by_default(self):
     app = Flask(__name__)
     api = flask_restbolt.Api(app)
     response = Mock()
     response.headers = {}
     with app.test_request_context('/foo'):
         response = api.unauthorized(response)
     assert_false('WWW-Authenticate' in response.headers)
Ejemplo n.º 16
0
    def test_handle_non_api_error(self):
        app = Flask(__name__)
        flask_restbolt.Api(app)
        app = app.test_client()

        resp = app.get("/foo")
        self.assertEquals(resp.status_code, 404)
        self.assertEquals('text/html', resp.headers['Content-Type'])
 def test_add_resource_endpoint_after_registration(self):
     blueprint = Blueprint('test', __name__)
     api = flask_restbolt.Api(blueprint)
     app = Flask(__name__)
     app.register_blueprint(blueprint)
     view = Mock(**{'as_view.return_value': Mock(__name__='test_view')})
     api.add_resource(view, '/foo', endpoint='bar')
     view.as_view.assert_called_with('bar')
 def test_registration_prefix_overrides_blueprint_prefix(self):
     blueprint = Blueprint('test', __name__, url_prefix='/bp')
     api = flask_restbolt.Api(blueprint)
     api.add_resource(HelloWorld, '/hi', endpoint='hello')
     app = Flask(__name__)
     app.register_blueprint(blueprint, url_prefix='/reg')
     with app.test_request_context('/reg/hi'):
         self.assertEquals(request.endpoint, 'test.hello')
Ejemplo n.º 19
0
    def test_handle_error_401_no_challenge_by_default(self):
        app = Flask(__name__)
        api = flask_restbolt.Api(app)

        with app.test_request_context('/foo'):
            resp = api.handle_error(Unauthorized())
            self.assertEquals(resp.status_code, 401)
            assert_false('WWW-Autheneticate' in resp.headers)
Ejemplo n.º 20
0
    def test_add_resource(self):
        app = Mock(flask.Flask)
        app.view_functions = {}
        api = flask_restbolt.Api(app)
        api.output = Mock()
        api.add_resource(views.MethodView, '/foo')

        app.add_url_rule.assert_called_with('/foo', view_func=api.output())
Ejemplo n.º 21
0
 def test_unauthorized(self):
     app = Flask(__name__)
     api = flask_restbolt.Api(app, serve_challenge_on_401=True)
     response = Mock()
     response.headers = {}
     with app.test_request_context('/foo'):
         response = api.unauthorized(response)
     self.assertEquals(response.headers['WWW-Authenticate'],
                       'Basic realm="flask-restful"')
Ejemplo n.º 22
0
    def test_handle_error_does_not_swallow_exceptions(self):
        app = Flask(__name__)
        api = flask_restbolt.Api(app)
        exception = BadRequest('x')

        with app.test_request_context('/foo'):
            resp = api.handle_error(exception)
            self.assertEquals(resp.status_code, 400)
            self.assertEquals(resp.get_data(), b'{"message": "x"}\n')
Ejemplo n.º 23
0
    def test_api_representation(self):
        app = Mock()
        api = flask_restbolt.Api(app)

        @api.representation('foo')
        def foo():
            pass

        self.assertEquals(api.representations['foo'], foo)
Ejemplo n.º 24
0
    def test_endpoints(self):
        app = Flask(__name__)
        api = flask_restbolt.Api(app)
        api.add_resource(HelloWorld, '/ids/<int:id>', endpoint="hello")
        with app.test_request_context('/foo'):
            self.assertFalse(api._has_fr_route())

        with app.test_request_context('/ids/3'):
            self.assertTrue(api._has_fr_route())
Ejemplo n.º 25
0
    def test_handle_error_401_sends_challege_configured_realm(self):
        app = Flask(__name__)
        app.config['HTTP_BASIC_AUTH_REALM'] = 'test-realm'
        api = flask_restbolt.Api(app, serve_challenge_on_401=True)

        with app.test_request_context('/foo'):
            resp = api.handle_error(Unauthorized())
            self.assertEquals(resp.status_code, 401)
            self.assertEquals(resp.headers['WWW-Authenticate'],
                              'Basic realm="test-realm"')
Ejemplo n.º 26
0
 def test_unauthorized_custom_realm(self):
     app = Flask(__name__)
     app.config['HTTP_BASIC_AUTH_REALM'] = 'Foo'
     api = flask_restbolt.Api(app, serve_challenge_on_401=True)
     response = Mock()
     response.headers = {}
     with app.test_request_context('/foo'):
         response = api.unauthorized(response)
     self.assertEquals(response.headers['WWW-Authenticate'],
                       'Basic realm="Foo"')
Ejemplo n.º 27
0
    def test_add_resource_endpoint(self):
        app = Mock()
        app.view_functions = {}
        view = Mock()

        api = flask_restbolt.Api(app)
        api.output = Mock()
        api.add_resource(view, '/foo', endpoint='bar')

        view.as_view.assert_called_with('bar')
Ejemplo n.º 28
0
    def test_handle_server_error(self):
        app = Flask(__name__)
        api = flask_restbolt.Api(app)

        with app.test_request_context("/foo"):
            resp = api.handle_error(Exception())
            self.assertEquals(resp.status_code, 500)
            self.assertEquals(
                resp.data.decode(),
                dumps({"message": "Internal Server Error"}) + "\n")
Ejemplo n.º 29
0
 def test_url_for_with_blueprint(self):
     """Verify that url_for works when an Api object is mounted on a
     Blueprint.
     """
     api_bp = Blueprint('api', __name__)
     app = Flask(__name__)
     api = flask_restbolt.Api(api_bp)
     api.add_resource(HelloWorld, '/foo/<string:bar>')
     app.register_blueprint(api_bp)
     with app.test_request_context('/foo'):
         self.assertEqual(api.url_for(HelloWorld, bar='baz'), '/foo/baz')
Ejemplo n.º 30
0
    def test_resource_decorator(self):
        app = Mock(flask.Flask)
        app.view_functions = {}
        api = flask_restbolt.Api(app)
        api.output = Mock()

        @api.resource('/foo', endpoint='bar')
        class Foo(flask_restbolt.Resource):
            pass

        app.add_url_rule.assert_called_with('/foo', view_func=api.output())