json encoding for Decimals and lazy translations

This commit is contained in:
Samuel Colvin 2015-04-28 19:12:46 +01:00
parent 6d85f0981c
commit cec2291842
3 changed files with 20 additions and 4 deletions

View File

@ -11,7 +11,7 @@ from __future__ import absolute_import
import codecs
import datetime
import uuid
from decimal import Decimal
try:
import simplejson as json
except ImportError:
@ -30,9 +30,13 @@ class BetterJSONEncoder(json.JSONEncoder):
set: list,
frozenset: list,
bytes: lambda o: o.decode('utf-8', errors='replace'),
Decimal: repr
}
def default(self, obj):
if hasattr(obj, '_proxy____text_cast'):
# django's gettext_lazy proxy strings
return obj.encode('utf8')
try:
encoder = self.ENCODER_BY_TYPE[type(obj)]
except KeyError:

View File

@ -21,7 +21,8 @@ from django.core.signals import got_request_exception
from django.core.handlers.wsgi import WSGIRequest
from django.http import QueryDict
from django.template import TemplateSyntaxError
from django.test import TestCase
from django.test import TestCase, SimpleTestCase
from django.utils.translation import gettext_lazy
from raven.base import Client
from raven.contrib.django.client import DjangoClient
@ -32,7 +33,7 @@ from raven.contrib.django.middleware.wsgi import Sentry
from raven.contrib.django.templatetags.raven import sentry_public_dsn
from raven.contrib.django.views import is_valid_origin
from raven.utils.serializer import transform
from raven.utils import six
from raven.utils import six, json
from raven.utils.six import StringIO
from django.test.client import Client as TestClient, ClientHandler as TestClientHandler
@ -777,3 +778,9 @@ class SentryExceptionHandlerTest(TestCase):
sentry_exception_handler(request=self.request)
assert not captureException.called
class JSONTest(SimpleTestCase):
def test_translation(self):
d = {'lazy_translation': gettext_lazy('testing')}
assert json.dumps(d) == '{"lazy_translation": "testing"}'

View File

@ -2,6 +2,7 @@
import datetime
import uuid
from decimal import Decimal
from raven.utils.testutils import TestCase
from raven.utils import json
@ -31,4 +32,8 @@ class JSONTest(TestCase):
return 'Unknown object'
obj = Unknown()
assert json.dumps(obj) == '"Unknown object"'
assert json.dumps(obj) == '"Unknown object"'
def test_decimal(self):
d = {'decimal': Decimal('123.45')}
assert json.dumps(d) == '{"decimal": "Decimal(\'123.45\')"}'