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'])
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'))
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)
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)
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 })
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')
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")
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')))
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())
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'])
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')
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)
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')
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')
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')
def test_api_representation(self): app = Mock() api = flask_rips.Api(app) @api.representation('foo') def foo(): pass self.assertEquals(api.representations['foo'], foo)
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"')
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())
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"')
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')
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')
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())
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')
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(), '')
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))
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)
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)
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/')
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)
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)