Skip to content

Commit

Permalink
Fix json formatter
Browse files Browse the repository at this point in the history
  • Loading branch information
meyt committed Aug 16, 2021
1 parent ce13b0d commit 5c63296
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
13 changes: 12 additions & 1 deletion gongish/response_formatters.py
@@ -1,8 +1,19 @@
try:
import ujson as jsonlib

def dump_json(v, indent):
# ujson 4.x patch
# https://github.com/ultrajson/ultrajson/issues/317
if indent is None:
indent = 0
return jsonlib.dumps(v, indent=indent)


except ImportError: # pragma: no cover
import json as jsonlib

dump_json = jsonlib.dumps


class ResponseFormattersMixin:
@staticmethod
Expand All @@ -16,7 +27,7 @@ def format_json(request, response, indent=None):
# Format in JSON
response.type = "application/json"
response.charset = "utf-8"
response.body = jsonlib.dumps(response.body, indent=indent)
response.body = dump_json(response.body, indent=indent)

@staticmethod
def format_binary(request, response):
Expand Down
22 changes: 22 additions & 0 deletions tests/test_response_formatter.py
Expand Up @@ -13,11 +13,33 @@ class MyApp(Application):
def get():
return dict(a=1)

@app.route("/none")
def get():
return

@app.route("/int")
def get():
return 12

@app.route("/str")
def get():
return 'thestr'

testapp = webtest.TestApp(app)

resp = testapp.get("/")
assert resp.json == dict(a=1)
assert resp.status == "200 OK"

resp = testapp.get("/none")
assert resp.json is None

resp = testapp.get("/int")
assert resp.json == 12

resp = testapp.get("/str")
assert resp.json == 'thestr'


def test_text_formatter():
class MyApp(Application):
Expand Down

0 comments on commit 5c63296

Please sign in to comment.