Skip to content

Commit a5fcf10

Browse files
biggie-jenkins-bottomchristie
authored andcommitted
Raise RuntimeError when trying to encode coreapi objects (#4790)
1 parent cf3862d commit a5fcf10

File tree

2 files changed

+16
-5
lines changed

2 files changed

+16
-5
lines changed

rest_framework/utils/encoders.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -55,16 +55,16 @@ def default(self, obj):
5555
elif hasattr(obj, 'tolist'):
5656
# Numpy arrays and array scalars.
5757
return obj.tolist()
58+
elif (coreapi is not None) and isinstance(obj, (coreapi.Document, coreapi.Error)):
59+
raise RuntimeError(
60+
'Cannot return a coreapi object from a JSON view. '
61+
'You should be using a schema renderer instead for this view.'
62+
)
5863
elif hasattr(obj, '__getitem__'):
5964
try:
6065
return dict(obj)
6166
except:
6267
pass
6368
elif hasattr(obj, '__iter__'):
6469
return tuple(item for item in obj)
65-
elif (coreapi is not None) and isinstance(obj, (coreapi.Document, coreapi.Error)):
66-
raise RuntimeError(
67-
'Cannot return a coreapi object from a JSON view. '
68-
'You should be using a schema renderer instead for this view.'
69-
)
7070
return super(JSONEncoder, self).default(obj)

tests/test_encoders.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
from django.test import TestCase
66

7+
from rest_framework.compat import coreapi
78
from rest_framework.utils.encoders import JSONEncoder
89

910

@@ -79,3 +80,13 @@ def test_encode_uuid(self):
7980
"""
8081
unique_id = uuid4()
8182
assert self.encoder.default(unique_id) == str(unique_id)
83+
84+
def test_encode_coreapi_raises_error(self):
85+
"""
86+
Tests encoding a coreapi objects raises proper error
87+
"""
88+
with self.assertRaises(RuntimeError):
89+
self.encoder.default(coreapi.Document())
90+
91+
with self.assertRaises(RuntimeError):
92+
self.encoder.default(coreapi.Error())

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy