Exemplo n.º 1
0
    def test_media_types(self):
        app = Flask(__name__)
        api = flask_rips.Api(app)

        with app.test_request_context("/foo",
                                      headers={'Accept': 'application/json'}):
            self.assertEquals(api.mediatypes(), ['application/json'])
Exemplo n.º 2
0
    def test_will_prettyprint_json_in_debug_mode(self):
        app = Flask(__name__)
        app.config['DEBUG'] = True
        api = flask_rips.Api(app)

        class Foo1(flask_rips.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'))
Exemplo n.º 3
0
 def test_api_delayed_initialization(self):
     app = Flask(__name__)
     api = flask_rips.Api()
     api.add_resource(HelloWorld, '/', endpoint="hello")
     api.init_app(app)
     with app.test_client() as client:
         self.assertEquals(client.get('/').status_code, 200)
Exemplo n.º 4
0
    def test_calling_owns_endpoint_before_api_init(self):
        api = flask_rips.Api()

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

        class FooError(ValueError):
            pass

        app = Flask(__name__)
        api = flask_rips.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
            })
Exemplo n.º 6
0
 def test_api_base(self):
     app = Mock()
     app.configure_mock(**{'record.side_effect': AttributeError})
     api = flask_rips.Api(app)
     self.assertEquals(api.urls, {})
     self.assertEquals(api.prefix, '')
     self.assertEquals(api.default_mediatype, 'application/json')
Exemplo n.º 7
0
 def test_api_delayed_initialization(self):
     blueprint = Blueprint('test', __name__)
     api = flask_rips.Api()
     api.init_app(blueprint)
     app = Flask(__name__)
     app.register_blueprint(blueprint)
     api.add_resource(HelloWorld, '/', endpoint="hello")
Exemplo n.º 8
0
    def test_exception_header_forwarded(self):
        """Test that HTTPException's headers are extended properly"""
        app = Flask(__name__)
        app.config['DEBUG'] = True
        api = flask_rips.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_rips.Resource):
            def get(self):
                flask_abort(304, etag='myETag')

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

        with app.test_client() as client:
            foo = client.get('/foo')
            self.assertEquals(foo.get_etag(),
                              unquote_etag(quote_etag('myETag')))
Exemplo n.º 9
0
    def test_add_resource(self):
        app = Mock(flask.Flask)
        app.view_functions = {}
        api = flask_rips.Api(app)
        api.output = Mock()
        api.add_resource(views.MethodView, '/foo')

        app.add_url_rule.assert_called_with('/foo', view_func=api.output())
Exemplo n.º 10
0
    def test_handle_non_api_error(self):
        app = Flask(__name__)
        flask_rips.Api(app)
        app = app.test_client()

        resp = app.get("/foo")
        self.assertEquals(resp.status_code, 404)
        self.assertEquals('text/html', resp.headers['Content-Type'])
Exemplo n.º 11
0
 def test_registration_prefix_overrides_blueprint_prefix(self):
     blueprint = Blueprint('test', __name__, url_prefix='/bp')
     api = flask_rips.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')
Exemplo n.º 12
0
 def test_unauthorized_no_challenge_by_default(self):
     app = Flask(__name__)
     api = flask_rips.Api(app)
     response = Mock()
     response.headers = {}
     with app.test_request_context('/foo'):
         response = api.unauthorized(response)
     assert_false('WWW-Authenticate' in response.headers)
Exemplo n.º 13
0
 def test_url_with_api_and_blueprint_prefix(self):
     blueprint = Blueprint('test', __name__, url_prefix='/bp')
     api = flask_rips.Api(blueprint, prefix='/api')
     api.add_resource(HelloWorld, '/hi', endpoint='hello')
     app = Flask(__name__)
     app.register_blueprint(blueprint)
     with app.test_request_context('/bp/api/hi'):
         self.assertEquals(request.endpoint, 'test.hello')
Exemplo n.º 14
0
 def test_add_resource_endpoint_after_registration(self):
     blueprint = Blueprint('test', __name__)
     api = flask_rips.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')
Exemplo n.º 15
0
 def test_api_base(self):
     blueprint = Blueprint('test', __name__)
     api = flask_rips.Api(blueprint)
     app = Flask(__name__)
     app.register_blueprint(blueprint)
     self.assertEquals(api.urls, {})
     self.assertEquals(api.prefix, '')
     self.assertEquals(api.default_mediatype, 'application/json')
Exemplo n.º 16
0
    def test_api_representation(self):
        app = Mock()
        api = flask_rips.Api(app)

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

        self.assertEquals(api.representations['foo'], foo)
Exemplo n.º 17
0
 def test_unauthorized(self):
     app = Flask(__name__)
     api = flask_rips.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"')
Exemplo n.º 18
0
    def test_endpoints(self):
        app = Flask(__name__)
        api = flask_rips.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())
Exemplo n.º 19
0
 def test_unauthorized_custom_realm(self):
     app = Flask(__name__)
     app.config['HTTP_BASIC_AUTH_REALM'] = 'Foo'
     api = flask_rips.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"')
Exemplo n.º 20
0
    def test_add_resource_endpoint(self):
        app = Mock()
        app.view_functions = {}
        view = Mock()

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

        view.as_view.assert_called_with('bar')
Exemplo n.º 21
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_rips.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')
Exemplo n.º 22
0
    def test_resource_decorator(self):
        app = Mock(flask.Flask)
        app.view_functions = {}
        api = flask_rips.Api(app)
        api.output = Mock()

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

        app.add_url_rule.assert_called_with('/foo', view_func=api.output())
Exemplo n.º 23
0
    def test_output_unpack(self):
        def make_empty_response():
            return {'foo': 'bar'}

        app = Flask(__name__)
        api = flask_rips.Api(app)

        with app.test_request_context("/foo"):
            wrapper = api.output(make_empty_response)
            resp = wrapper()
            self.assertEquals(resp.status_code, 200)
            self.assertEquals(resp.data.decode(), '{"foo": "bar"}\n')
Exemplo n.º 24
0
    def test_output_func(self):
        def make_empty_response():
            return flask.make_response('')

        app = Flask(__name__)
        api = flask_rips.Api(app)

        with app.test_request_context("/foo"):
            wrapper = api.output(make_empty_response)
            resp = wrapper()
            self.assertEquals(resp.status_code, 200)
            self.assertEquals(resp.data.decode(), '')
Exemplo n.º 25
0
 def test_fr_405(self):
     app = Flask(__name__)
     api = flask_rips.Api(app)
     api.add_resource(HelloWorld, '/ids/<int:id>', endpoint="hello")
     app = app.test_client()
     resp = app.post('/ids/3')
     self.assertEquals(resp.status_code, 405)
     self.assertEquals(resp.content_type, api.default_mediatype)
     # Allow can be of the form 'GET, PUT, POST'
     allow = ', '.join(set(resp.headers.get_all('Allow')))
     allow = set(method.strip() for method in allow.split(','))
     self.assertEquals(allow, {'HEAD', 'OPTIONS'}.union(HelloWorld.methods))
Exemplo n.º 26
0
    def test_exception_header_forwarding_doesnt_duplicate_headers(self):
        """Test that HTTPException's headers do not add a duplicate
        Content-Length header

        https://github.com/flask-restful/flask-restful/issues/534
        """
        app = Flask(__name__)
        api = flask_rips.Api(app)

        with app.test_request_context('/'):
            r = api.handle_error(BadRequest())

        self.assertEqual(len(r.headers.getlist('Content-Length')), 1)
Exemplo n.º 27
0
    def test_decorator(self):
        def return_zero(func):
            return 0

        app = Mock(flask.Flask)
        app.view_functions = {}
        view = Mock()
        api = flask_rips.Api(app)
        api.decorators.append(return_zero)
        api.output = Mock()
        api.add_resource(view, '/foo', endpoint='bar')

        app.add_url_rule.assert_called_with('/foo', view_func=0)
Exemplo n.º 28
0
    def test_redirect(self):
        app = Flask(__name__)
        api = flask_rips.Api(app)

        class FooResource(flask_rips.Resource):
            def get(self):
                return redirect('/')

        api.add_resource(FooResource, '/api')

        app = app.test_client()
        resp = app.get('/api')
        self.assertEquals(resp.status_code, 302)
        self.assertEquals(resp.headers['Location'], 'http://localhost/')
Exemplo n.º 29
0
    def test_no_crossdomain(self):
        class Foo(flask_rips.Resource):
            def get(self):
                return "data"

        app = Flask(__name__)
        api = flask_rips.Api(app)
        api.add_resource(Foo, '/')

        with app.test_client() as client:
            res = client.get('/')
            assert_equals(res.status_code, 200)
            assert_true('Access-Control-Allow-Origin' not in res.headers)
            assert_true('Access-Control-Allow-Methods' not in res.headers)
            assert_true('Access-Control-Max-Age' not in res.headers)
Exemplo n.º 30
0
    def test_json_with_no_settings(self):
        app = Flask(__name__)
        api = flask_rips.Api(app)

        class Foo(flask_rips.Resource):
            def get(self):
                return {'foo': 'bar'}

        api.add_resource(Foo, '/foo')

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

        expected = b'{"foo": "bar"}\n'
        self.assertEquals(data, expected)