Add json util wrapper, failing JSONField test

This commit is contained in:
Ryan P Kilby 2017-07-07 12:46:17 -04:00 committed by Carlton Gibson
parent f6c19e5eac
commit b64f8066c0
4 changed files with 56 additions and 1 deletions

View File

@ -1,7 +1,7 @@
""" """
Helper classes for parsers. Helper classes for parsers.
""" """
from __future__ import unicode_literals from __future__ import absolute_import, unicode_literals
import datetime import datetime
import decimal import decimal

View File

@ -0,0 +1,33 @@
from __future__ import absolute_import
import functools
import json
def strict_constant(o):
raise ValueError('Out of range float values are not JSON compliant: ' + repr(o))
@functools.wraps(json.dump)
def dump(*args, **kwargs):
kwargs.setdefault('allow_nan', False)
return json.dump(*args, **kwargs)
@functools.wraps(json.dumps)
def dumps(*args, **kwargs):
kwargs.setdefault('allow_nan', False)
return json.dumps(*args, **kwargs)
@functools.wraps(json.load)
def load(*args, **kwargs):
kwargs.setdefault('parse_constant', strict_constant)
return json.load(*args, **kwargs)
@functools.wraps(json.loads)
def loads(*args, **kwargs):
kwargs.setdefault('parse_constant', strict_constant)
return json.loads(*args, **kwargs)

View File

@ -1896,6 +1896,7 @@ class TestJSONField(FieldValues):
] ]
invalid_inputs = [ invalid_inputs = [
({'a': set()}, ['Value must be valid JSON.']), ({'a': set()}, ['Value must be valid JSON.']),
({'a': float('inf')}, ['Value must be valid JSON.']),
] ]
outputs = [ outputs = [
({ ({

View File

@ -9,6 +9,7 @@ import rest_framework.utils.model_meta
from rest_framework.compat import _resolve_model from rest_framework.compat import _resolve_model
from rest_framework.routers import SimpleRouter from rest_framework.routers import SimpleRouter
from rest_framework.serializers import ModelSerializer from rest_framework.serializers import ModelSerializer
from rest_framework.utils import json
from rest_framework.utils.breadcrumbs import get_breadcrumbs from rest_framework.utils.breadcrumbs import get_breadcrumbs
from rest_framework.views import APIView from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet from rest_framework.viewsets import ModelViewSet
@ -177,3 +178,23 @@ class ResolveModelWithPatchedDjangoTests(TestCase):
def test_blows_up_if_model_does_not_resolve(self): def test_blows_up_if_model_does_not_resolve(self):
with self.assertRaises(ImproperlyConfigured): with self.assertRaises(ImproperlyConfigured):
_resolve_model('tests.BasicModel') _resolve_model('tests.BasicModel')
class JsonFloatTests(TestCase):
"""
Internaly, wrapped json functions should adhere to strict float handling
"""
def test_dumps(self):
with self.assertRaises(ValueError):
json.dumps(float('inf'))
with self.assertRaises(ValueError):
json.dumps(float('nan'))
def test_loads(self):
with self.assertRaises(ValueError):
json.loads("Infinity")
with self.assertRaises(ValueError):
json.loads("NaN")