Skip to content

Commit 132eab7

Browse files
committed
Raise helpful error when erronously including nested data in multipart post requests with test client. Closes #2919.
1 parent c14ad7a commit 132eab7

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

rest_framework/renderers.py

+8
Original file line numberDiff line numberDiff line change
@@ -679,4 +679,12 @@ class MultiPartRenderer(BaseRenderer):
679679
BOUNDARY = 'BoUnDaRyStRiNg' if django.VERSION >= (1, 5) else b'BoUnDaRyStRiNg'
680680

681681
def render(self, data, accepted_media_type=None, renderer_context=None):
682+
if hasattr(data, 'items'):
683+
for key, value in data.items():
684+
assert not isinstance(value, dict), (
685+
"Test data contained a dictionary value for key '%s', "
686+
"but multipart uploads do not support nested data. "
687+
"You may want to consider using format='JSON' in this "
688+
"test case." % key
689+
)
682690
return encode_multipart(self.BOUNDARY, data)

tests/test_testing.py

+10
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,16 @@ def test_follow_redirect(self):
172172
self.assertIsNotNone(response.redirect_chain)
173173
self.assertEqual(response.status_code, 200)
174174

175+
def test_invalid_multipart_data(self):
176+
"""
177+
MultiPart encoding cannot support nested data, so raise a helpful
178+
error if the user attempts to do so.
179+
"""
180+
self.assertRaises(
181+
AssertionError, self.client.post,
182+
path='/view/', data={'valid': 123, 'invalid': {'a': 123}}
183+
)
184+
175185

176186
class TestAPIRequestFactory(TestCase):
177187
def test_csrf_exempt_by_default(self):

0 commit comments

Comments
 (0)