async def test_app_handle_request_asyncio_cancelled_error() -> None: app = Quart(__name__) @app.route("/") async def index() -> NoReturn: raise asyncio.CancelledError() request = app.request_class( "GET", "http", "/", b"", CIMultiDict(), send_push_promise=no_op_push, ) with pytest.raises(asyncio.CancelledError): await app.handle_request(request)
def test_bad_request_if_websocket_route() -> None: app = Quart(__name__) url_adapter = Mock() url_adapter.match.side_effect = BadRequest() app.create_url_adapter = lambda *_: url_adapter # type: ignore request = Request( 'GET', 'http', '/', b'', CIMultiDict(), "", "1.1", send_push_promise=no_op_push, ) RequestContext(app, request) assert isinstance(request.routing_exception, BadRequest)
async def test_make_response( result: ResponseReturnValue, expected: Union[Response, WerkzeugResponse], raises: bool ) -> None: app = Quart(__name__) app.config["RESPONSE_TIMEOUT"] = None try: response = await app.make_response(result) except TypeError: if not raises: raise else: assert set(response.headers.keys()) == set(expected.headers.keys()) assert response.status_code == expected.status_code if isinstance(response, Response): assert (await response.get_data()) == (await expected.get_data()) # type: ignore elif isinstance(response, WerkzeugResponse): assert response.get_data() == expected.get_data()
async def test_copy_current_app_context() -> None: app = Quart(__name__) @app.route('/') async def index() -> str: g.foo = 'bar' # type: ignore @copy_current_app_context async def within_context() -> None: assert g.foo == 'bar' await asyncio.ensure_future(within_context()) return '' test_client = app.test_client() response = await test_client.get('/') assert response.status_code == 200
def test_request_context_matching_error( exception_type: Exception, exception_instance: Exception, ) -> None: app = Quart(__name__) url_adapter = Mock() url_adapter.match.side_effect = exception_instance app.create_url_adapter = lambda *_: url_adapter # type: ignore request = Request('GET', 'http', '/', b'', CIMultiDict(), send_push_promise=no_op_push) RequestContext(app, request) assert isinstance(request.routing_exception, exception_type) # type: ignore
async def test_secure_cookie_session_interface_open_session() -> None: session = SecureCookieSession() session['something'] = 'else' interface = SecureCookieSessionInterface() app = Quart(__name__) app.secret_key = 'secret' response = Response('') await interface.save_session(app, session, response) request = Request('GET', 'http', '/', b'', CIMultiDict(), send_push_promise=no_op_push) request.headers['Cookie'] = response.headers['Set-Cookie'] new_session = await interface.open_session(app, request) assert new_session == session
async def test_app_after_request_handler_exception(basic_app: Quart) -> None: @basic_app.after_request def after(_: Response) -> None: raise Exception() test_client = basic_app.test_client() response = await test_client.get("/exception/") assert response.status_code == 500
def test_bad_request_if_websocket_route() -> None: app = Quart(__name__) url_adapter = Mock() url_adapter.match.side_effect = WBadRequest() app.create_url_adapter = lambda *_: url_adapter # type: ignore request = Request( "GET", "http", "/", b"", Headers([("host", "quart.com")]), "", "1.1", send_push_promise=no_op_push, ) RequestContext(app, request) assert isinstance(request.routing_exception, BadRequest)
def test_secure_cookie_session_interface_save_session() -> None: session = SecureCookieSession() session['something'] = 'else' interface = SecureCookieSessionInterface() app = Quart(__name__) app.secret_key = 'secret' response = Response('') interface.save_session(app, session, response) cookies = SimpleCookie() # type: ignore cookies.load(response.headers['Set-Cookie']) cookie = cookies[app.session_cookie_name] assert cookie['path'] == interface.get_cookie_path(app) assert cookie['httponly'] == '' if not interface.get_cookie_httponly(app) else True assert cookie['secure'] == '' if not interface.get_cookie_secure(app) else True assert cookie['domain'] == (interface.get_cookie_domain(app) or '') assert cookie['expires'] == (interface.get_expiration_time(app, session) or '') assert response.headers['Vary'] == 'Cookie'
async def test_app_before_request_exception(basic_app: Quart) -> None: @basic_app.before_request def before() -> None: raise Exception() test_client = basic_app.test_client() response = await test_client.get("/") assert response.status_code == 500
async def test_copy_current_app_context() -> None: app = Quart(__name__) @app.route("/") async def index() -> str: g.foo = "bar" @copy_current_app_context async def within_context() -> None: assert g.foo == "bar" await asyncio.ensure_future(within_context()) return "" test_client = app.test_client() response = await test_client.get("/") assert response.status_code == 200
def test_add_url_rule_automatic_options( methods: Set[str], arg_automatic: Optional[bool], func_automatic: Optional[bool], expected_methods: Set[str], expected_automatic: bool, ) -> None: app = Quart(__name__) def route() -> str: return "" route.provide_automatic_options = func_automatic # type: ignore app.add_url_rule("/", "end", route, methods=methods, provide_automatic_options=arg_automatic) assert app.url_map._rules_by_endpoint["end"][0].methods == expected_methods # type: ignore assert app.url_map._rules_by_endpoint["end"][0].provide_automatic_options == expected_automatic # type: ignore # noqa: E501
async def test_propagation(debug: bool, testing: bool, raises: bool) -> None: app = Quart(__name__) @app.route("/") async def exception() -> ResponseReturnValue: raise SimpleException() app.debug = debug app.testing = testing test_client = app.test_client() if raises: with pytest.raises(SimpleException): await test_client.get("/") else: response = await test_client.get("/") assert response.status_code == 500
async def test_make_response( result: ResponseReturnValue, expected: Response, raises: bool, ) -> None: app = Quart(__name__) app.config['RESPONSE_TIMEOUT'] = None try: response = await app.make_response(result) except TypeError: if not raises: raise else: assert response.headers.keys() == expected.headers.keys() assert response.status_code == expected.status_code assert (await response.get_data()) == (await expected.get_data()) # type: ignore
def test_request_context_match() -> None: app = Quart(__name__) url_adapter = Mock() rule = Rule('/', {'GET'}, 'index') url_adapter.match.return_value = (rule, {'arg': 'value'}) app.create_url_adapter = lambda *_: url_adapter # type: ignore request = Request( 'GET', 'http', '/', b'', CIMultiDict(), "", "1.1", send_push_promise=no_op_push, ) RequestContext(app, request) assert request.url_rule == rule assert request.view_args == {'arg': 'value'}
async def test_has_request_context() -> None: app = Quart(__name__) headers, path, query_string = make_test_headers_path_and_query_string( app, '/') request = Request( 'GET', 'http', path, query_string, headers, "", "1.1", send_push_promise=no_op_push, ) async with RequestContext(Quart(__name__), request): assert has_request_context() is True assert has_app_context() is True assert has_request_context() is False assert has_app_context() is False
async def test_secure_cookie_session_interface_open_session() -> None: session = SecureCookieSession() session["something"] = "else" interface = SecureCookieSessionInterface() app = Quart(__name__) app.secret_key = "secret" response = Response("") await interface.save_session(app, session, response) request = Request("GET", "http", "/", b"", Headers(), "", "1.1", {}, send_push_promise=no_op_push) request.headers["Cookie"] = response.headers["Set-Cookie"] new_session = await interface.open_session(app, request) assert new_session == session
def test_request_context_match() -> None: app = Quart(__name__) url_adapter = Mock() rule = QuartRule("/", methods={"GET"}, endpoint="index") url_adapter.match.return_value = (rule, {"arg": "value"}) app.create_url_adapter = lambda *_: url_adapter # type: ignore request = Request( "GET", "http", "/", b"", Headers([("host", "quart.com")]), "", "1.1", send_push_promise=no_op_push, ) RequestContext(app, request) assert request.url_rule == rule assert request.view_args == {"arg": "value"}
def test_request_context_matching_error( exception_type: Exception, exception_instance: Exception ) -> None: app = Quart(__name__) url_adapter = Mock() url_adapter.match.side_effect = exception_instance app.create_url_adapter = lambda *_: url_adapter # type: ignore request = Request( "GET", "http", "/", b"", Headers([("host", "quart.com")]), "", "1.1", send_push_promise=no_op_push, ) RequestContext(app, request) assert isinstance(request.routing_exception, exception_type) # type: ignore
async def test_after_this_request() -> None: app = Quart(__name__) headers, path, query_string = make_test_headers_path_and_query_string( app, '/') async with RequestContext( Quart(__name__), Request( 'GET', 'http', path, query_string, headers, "", "1.1", send_push_promise=no_op_push, ), ) as context: after_this_request(lambda: 'hello') assert context._after_request_functions[0]() == 'hello'
async def test_app_handle_websocket_asyncio_cancelled_error() -> None: app = Quart(__name__) @app.websocket("/") async def index() -> NoReturn: raise asyncio.CancelledError() websocket = app.websocket_class( "/", b"", "wss", CIMultiDict(), None, None, None, None, ) with pytest.raises(asyncio.CancelledError): await app.handle_websocket(websocket)
async def test_app_handle_request_asyncio_cancelled_error() -> None: app = Quart(__name__) @app.route("/") async def index() -> NoReturn: raise asyncio.CancelledError() request = app.request_class( "GET", "http", "/", b"", Headers([("host", "quart.com")]), "", "1.1", send_push_promise=no_op_push, ) with pytest.raises(asyncio.CancelledError): await app.handle_request(request)
async def test_has_request_context(http_scope: HTTPScope) -> None: app = Quart(__name__) headers, path, query_string = make_test_headers_path_and_query_string(app, "/") request = Request( "GET", "http", path, query_string, headers, "", "1.1", http_scope, send_push_promise=no_op_push, ) async with RequestContext(Quart(__name__), request): assert has_request_context() is True assert has_app_context() is True assert has_request_context() is False assert has_app_context() is False
async def test_after_this_request(http_scope: HTTPScope) -> None: app = Quart(__name__) headers, path, query_string = make_test_headers_path_and_query_string(app, "/") async with RequestContext( Quart(__name__), Request( "GET", "http", path, query_string, headers, "", "1.1", http_scope, send_push_promise=no_op_push, ), ) as context: after_this_request(lambda: "hello") assert context._after_request_functions[0]() == "hello"
async def test_overlapping_request_ctx() -> None: app = Quart(__name__) request = Request( 'GET', 'http', '/', b'', CIMultiDict(), "", "1.1", send_push_promise=no_op_push, ) ctx1 = app.request_context(request) await ctx1.__aenter__() ctx2 = app.request_context(request) await ctx2.__aenter__() await ctx1.__aexit__(None, None, None) assert has_app_context() # Ensure the app context still exists for ctx2 await ctx2.__aexit__(None, None, None)
async def test_overlapping_request_ctx() -> None: app = Quart(__name__) request = Request( "GET", "http", "/", b"", Headers([("host", "quart.com")]), "", "1.1", send_push_promise=no_op_push, ) ctx1 = app.request_context(request) await ctx1.__aenter__() ctx2 = app.request_context(request) await ctx2.__aenter__() await ctx1.__aexit__(None, None, None) assert has_app_context() # Ensure the app context still exists for ctx2 await ctx2.__aexit__(None, None, None)
def _basic_app() -> Quart: app = Quart(__name__) @app.route("/") def route() -> str: return "" @app.route("/exception/") def exception() -> str: raise Exception() return app
def _basic_app() -> Quart: app = Quart(__name__) @app.route('/') def route() -> str: return '' @app.route('/exception/') def exception() -> str: raise Exception() return app
def test_add_url_rule_automatic_options( methods: Set[str], arg_automatic: Optional[bool], func_automatic: Optional[bool], expected_methods: Set[str], expected_automatic: bool, ) -> None: app = Quart(__name__) def route() -> str: return '' route.provide_automatic_options = func_automatic # type: ignore app.add_url_rule('/', 'end', route, methods, provide_automatic_options=arg_automatic) assert app.url_map.endpoints['end'][0].methods == expected_methods assert app.url_map.endpoints['end'][ 0].provide_automatic_options == expected_automatic
async def test_secure_cookie_session_interface_save_session() -> None: session = SecureCookieSession() session["something"] = "else" interface = SecureCookieSessionInterface() app = Quart(__name__) app.secret_key = "secret" response = Response("") await interface.save_session(app, session, response) cookies: SimpleCookie = SimpleCookie() cookies.load(response.headers["Set-Cookie"]) cookie = cookies[app.session_cookie_name] assert cookie["path"] == interface.get_cookie_path(app) assert cookie["httponly"] == "" if not interface.get_cookie_httponly( app) else True assert cookie["secure"] == "" if not interface.get_cookie_secure( app) else True if version_info >= (3, 8): assert cookie["samesite"] == (interface.get_cookie_samesite(app) or "") assert cookie["domain"] == (interface.get_cookie_domain(app) or "") assert cookie["expires"] == (interface.get_expiration_time(app, session) or "") assert response.headers["Vary"] == "Cookie"