Raise RuntimeError when trying to encode coreapi objects (#4790)

This commit is contained in:
Artem Muterko 2017-01-07 00:32:13 +02:00 committed by Tom Christie
parent cf3862d56d
commit a5fcf10c0e
2 changed files with 16 additions and 5 deletions

View File

@ -55,6 +55,11 @@ class JSONEncoder(json.JSONEncoder):
elif hasattr(obj, 'tolist'):
# Numpy arrays and array scalars.
return obj.tolist()
elif (coreapi is not None) and isinstance(obj, (coreapi.Document, coreapi.Error)):
raise RuntimeError(
'Cannot return a coreapi object from a JSON view. '
'You should be using a schema renderer instead for this view.'
)
elif hasattr(obj, '__getitem__'):
try:
return dict(obj)
@ -62,9 +67,4 @@ class JSONEncoder(json.JSONEncoder):
pass
elif hasattr(obj, '__iter__'):
return tuple(item for item in obj)
elif (coreapi is not None) and isinstance(obj, (coreapi.Document, coreapi.Error)):
raise RuntimeError(
'Cannot return a coreapi object from a JSON view. '
'You should be using a schema renderer instead for this view.'
)
return super(JSONEncoder, self).default(obj)

View File

@ -4,6 +4,7 @@ from uuid import uuid4
from django.test import TestCase
from rest_framework.compat import coreapi
from rest_framework.utils.encoders import JSONEncoder
@ -79,3 +80,13 @@ class JSONEncoderTests(TestCase):
"""
unique_id = uuid4()
assert self.encoder.default(unique_id) == str(unique_id)
def test_encode_coreapi_raises_error(self):
"""
Tests encoding a coreapi objects raises proper error
"""
with self.assertRaises(RuntimeError):
self.encoder.default(coreapi.Document())
with self.assertRaises(RuntimeError):
self.encoder.default(coreapi.Error())