From afea15e4a7834a83ff95ddf974852272e4c94b80 Mon Sep 17 00:00:00 2001 From: Ashley Sommer Date: Mon, 6 Aug 2018 15:02:12 +1000 Subject: [PATCH] Add a test for the graceful CancelledError handling. The user app should _never_ see a CancelledError bubble up, nor should they be able to catch it, because the response is already sent at that point. --- tests/test_response_timeout.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/tests/test_response_timeout.py b/tests/test_response_timeout.py index bf55a42e..44204b5e 100644 --- a/tests/test_response_timeout.py +++ b/tests/test_response_timeout.py @@ -7,6 +7,7 @@ from sanic.config import Config Config.RESPONSE_TIMEOUT = 1 response_timeout_app = Sanic('test_response_timeout') response_timeout_default_app = Sanic('test_response_timeout_default') +response_handler_cancelled_app = Sanic('test_response_handler_cancelled') @response_timeout_app.route('/1') @@ -36,3 +37,29 @@ def test_default_server_error_response_timeout(): request, response = response_timeout_default_app.test_client.get('/1') assert response.status == 503 assert response.text == 'Error: Response Timeout' + + +response_handler_cancelled_app.flag = False + + +@response_handler_cancelled_app.exception(asyncio.CancelledError) +def handler_cancelled(request, exception): + # If we get a CancelledError, it means sanic has already sent a response, + # we should not ever have to handle a CancelledError. + response_handler_cancelled_app.flag = True + return text("App received CancelledError!", 500) + # The client will never receive this response, because the socket + # is already closed when we get a CancelledError. + + +@response_handler_cancelled_app.route('/1') +async def handler_3(request): + await asyncio.sleep(2) + return text('OK') + + +def test_response_handler_cancelled(): + request, response = response_handler_cancelled_app.test_client.get('/1') + assert response.status == 503 + assert response.text == 'Error: Response Timeout' + assert response_handler_cancelled_app.flag is False