From 457507d8dc2772f59a144f713f01bd15f73183eb Mon Sep 17 00:00:00 2001 From: Raphael Deem Date: Wed, 7 Dec 2016 20:33:56 -0800 Subject: [PATCH] return 400 on invalid json post data --- sanic/request.py | 3 ++- tests/test_requests.py | 13 +++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/sanic/request.py b/sanic/request.py index d3c11cd0..62d89781 100644 --- a/sanic/request.py +++ b/sanic/request.py @@ -4,6 +4,7 @@ from http.cookies import SimpleCookie from httptools import parse_url from urllib.parse import parse_qs from ujson import loads as json_loads +from sanic.exceptions import InvalidUsage from .log import log @@ -67,7 +68,7 @@ class Request(dict): try: self.parsed_json = json_loads(self.body) except Exception: - log.exception("Failed when parsing body as json") + raise InvalidUsage("Failed when parsing body as json") return self.parsed_json diff --git a/tests/test_requests.py b/tests/test_requests.py index 756113b2..81895c8c 100644 --- a/tests/test_requests.py +++ b/tests/test_requests.py @@ -49,6 +49,19 @@ def test_json(): assert results.get('test') == True +def test_invalid_json(): + app = Sanic('test_json') + + @app.route('/') + async def handler(request): + return json(request.json()) + + data = "I am not json" + request, response = sanic_endpoint_test(app, data=data) + + assert response.status == 400 + + def test_query_string(): app = Sanic('test_query_string')