diff --git a/sanic/response.py b/sanic/response.py index 3873d90f..9349ce81 100644 --- a/sanic/response.py +++ b/sanic/response.py @@ -72,6 +72,8 @@ STATUS_CODES = { 511: b'Network Authentication Required' } +EMPTY_STATUS_CODES = [204, 304] + class BaseHTTPResponse: def _encode_body(self, data): @@ -195,8 +197,14 @@ class HTTPResponse(BaseHTTPResponse): timeout_header = b'' if keep_alive and keep_alive_timeout is not None: timeout_header = b'Keep-Alive: %d\r\n' % keep_alive_timeout - self.headers['Content-Length'] = self.headers.get( - 'Content-Length', len(self.body)) + + body = b'' + content_length = 0 + if self.status not in EMPTY_STATUS_CODES: + body = self.body + content_length = self.headers.get('Content-Length', len(self.body)) + + self.headers['Content-Length'] = content_length self.headers['Content-Type'] = self.headers.get( 'Content-Type', self.content_type) @@ -218,7 +226,7 @@ class HTTPResponse(BaseHTTPResponse): b'keep-alive' if keep_alive else b'close', timeout_header, headers, - self.body + body ) @property diff --git a/tests/test_requests.py b/tests/test_requests.py index 9eb88243..14da4b0b 100644 --- a/tests/test_requests.py +++ b/tests/test_requests.py @@ -104,18 +104,20 @@ def test_json(): assert results.get('test') == True + def test_empty_json(): app = Sanic('test_json') @app.route('/') async def handler(request): - assert request.json == None + assert request.json is None return json(request.json) request, response = app.test_client.get('/') assert response.status == 200 assert response.text == 'null' + def test_invalid_json(): app = Sanic('test_json') diff --git a/tests/test_response.py b/tests/test_response.py index 6ac77cec..57e01cb6 100644 --- a/tests/test_response.py +++ b/tests/test_response.py @@ -16,7 +16,6 @@ from unittest.mock import MagicMock JSON_DATA = {'ok': True} - def test_response_body_not_a_string(): """Test when a response body sent from the application is not a string""" app = Sanic('response_body_not_a_string') @@ -35,6 +34,7 @@ async def sample_streaming_fn(response): await asyncio.sleep(.001) response.write('bar') + def test_method_not_allowed(): app = Sanic('method_not_allowed') @@ -43,7 +43,7 @@ def test_method_not_allowed(): return response.json({'hello': 'world'}) request, response = app.test_client.head('/') - assert response.headers['Allow']== 'GET' + assert response.headers['Allow'] == 'GET' @app.post('/') async def test(request): @@ -63,6 +63,22 @@ def json_app(): async def test(request): return json(JSON_DATA) + @app.get("/no-content") + async def no_content_handler(request): + return json(JSON_DATA, status=204) + + @app.get("/no-content/unmodified") + async def no_content_unmodified_handler(request): + return json(None, status=304) + + @app.get("/unmodified") + async def unmodified_handler(request): + return json(JSON_DATA, status=304) + + @app.delete("/") + async def delete_handler(request): + return json(None, status=204) + return app @@ -73,6 +89,29 @@ def test_json_response(json_app): assert response.text == json_dumps(JSON_DATA) assert response.json == JSON_DATA + +def test_no_content(json_app): + request, response = json_app.test_client.get('/no-content') + assert response.status == 204 + assert response.text == '' + assert response.headers['Content-Length'] == '0' + + request, response = json_app.test_client.get('/no-content/unmodified') + assert response.status == 304 + assert response.text == '' + assert response.headers['Content-Length'] == '0' + + request, response = json_app.test_client.get('/unmodified') + assert response.status == 304 + assert response.text == '' + assert response.headers['Content-Length'] == '0' + + request, response = json_app.test_client.delete('/') + assert response.status == 204 + assert response.text == '' + assert response.headers['Content-Length'] == '0' + + @pytest.fixture def streaming_app(): app = Sanic('streaming') @@ -156,9 +195,11 @@ def get_file_content(static_file_directory, file_name): with open(os.path.join(static_file_directory, file_name), 'rb') as file: return file.read() + @pytest.mark.parametrize('file_name', ['test.file', 'decode me.txt', 'python.png']) def test_file_response(file_name, static_file_directory): app = Sanic('test_file_helper') + @app.route('/files/', methods=['GET']) def file_route(request, filename): file_path = os.path.join(static_file_directory, filename) @@ -170,10 +211,12 @@ def test_file_response(file_name, static_file_directory): assert response.body == get_file_content(static_file_directory, file_name) assert 'Content-Disposition' not in response.headers + @pytest.mark.parametrize('source,dest', [ ('test.file', 'my_file.txt'), ('decode me.txt', 'readme.md'), ('python.png', 'logo.png')]) def test_file_response_custom_filename(source, dest, static_file_directory): app = Sanic('test_file_helper') + @app.route('/files/', methods=['GET']) def file_route(request, filename): file_path = os.path.join(static_file_directory, filename) @@ -185,9 +228,11 @@ def test_file_response_custom_filename(source, dest, static_file_directory): assert response.body == get_file_content(static_file_directory, source) assert response.headers['Content-Disposition'] == 'attachment; filename="{}"'.format(dest) + @pytest.mark.parametrize('file_name', ['test.file', 'decode me.txt']) def test_file_head_response(file_name, static_file_directory): app = Sanic('test_file_helper') + @app.route('/files/', methods=['GET', 'HEAD']) async def file_route(request, filename): file_path = os.path.join(static_file_directory, filename) @@ -212,25 +257,29 @@ def test_file_head_response(file_name, static_file_directory): 'Content-Length']) == len( get_file_content(static_file_directory, file_name)) + @pytest.mark.parametrize('file_name', ['test.file', 'decode me.txt', 'python.png']) def test_file_stream_response(file_name, static_file_directory): app = Sanic('test_file_helper') + @app.route('/files/', methods=['GET']) def file_route(request, filename): file_path = os.path.join(static_file_directory, filename) file_path = os.path.abspath(unquote(file_path)) return file_stream(file_path, chunk_size=32, - mime_type=guess_type(file_path)[0] or 'text/plain') + mime_type=guess_type(file_path)[0] or 'text/plain') request, response = app.test_client.get('/files/{}'.format(file_name)) assert response.status == 200 assert response.body == get_file_content(static_file_directory, file_name) assert 'Content-Disposition' not in response.headers + @pytest.mark.parametrize('source,dest', [ ('test.file', 'my_file.txt'), ('decode me.txt', 'readme.md'), ('python.png', 'logo.png')]) def test_file_stream_response_custom_filename(source, dest, static_file_directory): app = Sanic('test_file_helper') + @app.route('/files/', methods=['GET']) def file_route(request, filename): file_path = os.path.join(static_file_directory, filename) @@ -242,9 +291,11 @@ def test_file_stream_response_custom_filename(source, dest, static_file_director assert response.body == get_file_content(static_file_directory, source) assert response.headers['Content-Disposition'] == 'attachment; filename="{}"'.format(dest) + @pytest.mark.parametrize('file_name', ['test.file', 'decode me.txt']) def test_file_stream_head_response(file_name, static_file_directory): app = Sanic('test_file_helper') + @app.route('/files/', methods=['GET', 'HEAD']) async def file_route(request, filename): file_path = os.path.join(static_file_directory, filename) @@ -261,7 +312,7 @@ def test_file_stream_head_response(file_name, static_file_directory): content_type=guess_type(file_path)[0] or 'text/plain') else: return file_stream(file_path, chunk_size=32, headers=headers, - mime_type=guess_type(file_path)[0] or 'text/plain') + mime_type=guess_type(file_path)[0] or 'text/plain') request, response = app.test_client.head('/files/{}'.format(file_name)) assert response.status == 200