From 75fc9f91b942f82cd9e25161e076afa28ae10472 Mon Sep 17 00:00:00 2001 From: 38elements Date: Sun, 18 Dec 2016 09:25:39 +0900 Subject: [PATCH] Change HttpParserError process --- sanic/server.py | 8 ++++---- tests/test_bad_request.py | 20 ++++++++++++++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) create mode 100644 tests/test_bad_request.py diff --git a/sanic/server.py b/sanic/server.py index a86da9fc..9340f374 100644 --- a/sanic/server.py +++ b/sanic/server.py @@ -14,7 +14,7 @@ except ImportError: from .log import log from .request import Request -from .exceptions import RequestTimeout, PayloadTooLarge +from .exceptions import RequestTimeout, PayloadTooLarge, InvalidUsage class Signal: @@ -105,9 +105,9 @@ class HttpProtocol(asyncio.Protocol): # Parse request chunk or close connection try: self.parser.feed_data(data) - except HttpParserError as e: - self.bail_out( - "Invalid request data, connection closed ({})".format(e)) + except HttpParserError: + exception = InvalidUsage('Bad Request') + self.write_error(exception) def on_url(self, url): self.url = url diff --git a/tests/test_bad_request.py b/tests/test_bad_request.py new file mode 100644 index 00000000..095f4ab1 --- /dev/null +++ b/tests/test_bad_request.py @@ -0,0 +1,20 @@ +import asyncio +from sanic import Sanic + + +def test_bad_request_response(): + app = Sanic('test_bad_request_response') + lines = [] + async def _request(sanic, loop): + connect = asyncio.open_connection('127.0.0.1', 42101) + reader, writer = await connect + writer.write(b'not http') + while True: + line = await reader.readline() + if not line: + break + lines.append(line) + app.stop() + app.run(host='127.0.0.1', port=42101, debug=False, after_start=_request) + assert lines[0] == b'HTTP/1.1 400 Bad Request\r\n' + assert lines[-1] == b'Error: Bad Request'