Merge pull request #517 from r0fls/empty-json

return valid json in request.json
This commit is contained in:
Raphael Deem 2017-03-10 00:35:26 -08:00 committed by GitHub
commit 0f50ac7205
2 changed files with 15 additions and 5 deletions

View File

@ -69,6 +69,8 @@ class Request(dict):
try:
self.parsed_json = json_loads(self.body)
except Exception:
if not self.body:
return None
raise InvalidUsage("Failed when parsing body as json")
return self.parsed_json

View File

@ -85,20 +85,28 @@ def test_json():
request, response = app.test_client.get('/')
try:
results = json_loads(response.text)
except:
raise ValueError("Expected JSON response but got '{}'".format(response))
assert results.get('test') == True
def test_empty_json():
app = Sanic('test_json')
@app.route('/')
async def handler(request):
assert request.json == 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')
@app.route('/')
async def handler(request):
return json(request.json())
return json(request.json)
data = "I am not json"
request, response = app.test_client.get('/', data=data)