1
0
mirror of https://github.com/django/django.git synced 2025-01-03 15:06:09 +00:00

Used JsonResponse and response.json in file_uploads tests.

This commit is contained in:
Tim Graham 2017-02-07 13:23:57 -05:00
parent 8863c475c5
commit 5e303836b6
2 changed files with 16 additions and 29 deletions

View File

@ -1,6 +1,5 @@
import base64 import base64
import hashlib import hashlib
import json
import os import os
import shutil import shutil
import sys import sys
@ -89,9 +88,7 @@ class FileUploadTests(TestCase):
'wsgi.input': payload, 'wsgi.input': payload,
} }
response = self.client.request(**r) response = self.client.request(**r)
received = json.loads(response.content.decode('utf-8')) self.assertEqual(response.json()['file'], content)
self.assertEqual(received['file'], content)
def test_base64_upload(self): def test_base64_upload(self):
self._test_base64_upload("This data will be transmitted base64-encoded.") self._test_base64_upload("This data will be transmitted base64-encoded.")
@ -196,7 +193,7 @@ class FileUploadTests(TestCase):
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
# Empty filenames should be ignored # Empty filenames should be ignored
received = json.loads(response.content.decode('utf-8')) received = response.json()
for i, name in enumerate(filenames): for i, name in enumerate(filenames):
self.assertIsNone(received.get('file%s' % i)) self.assertIsNone(received.get('file%s' % i))
@ -240,9 +237,8 @@ class FileUploadTests(TestCase):
'wsgi.input': payload, 'wsgi.input': payload,
} }
response = self.client.request(**r) response = self.client.request(**r)
# The filenames should have been sanitized by the time it got to the view. # The filenames should have been sanitized by the time it got to the view.
received = json.loads(response.content.decode('utf-8')) received = response.json()
for i, name in enumerate(scary_file_names): for i, name in enumerate(scary_file_names):
got = received["file%s" % i] got = received["file%s" % i]
self.assertEqual(got, "hax0rd.txt") self.assertEqual(got, "hax0rd.txt")
@ -277,8 +273,7 @@ class FileUploadTests(TestCase):
'wsgi.input': payload, 'wsgi.input': payload,
} }
response = self.client.request(**r) response = self.client.request(**r)
result = response.json()
result = json.loads(response.content.decode('utf-8'))
for name, _, expected in cases: for name, _, expected in cases:
got = result[name] got = result[name]
self.assertEqual(expected, got, 'Mismatch for {}'.format(name)) self.assertEqual(expected, got, 'Mismatch for {}'.format(name))
@ -304,7 +299,7 @@ class FileUploadTests(TestCase):
'string': string_io, 'string': string_io,
'binary': bytes_io, 'binary': bytes_io,
}) })
received = json.loads(response.content.decode('utf-8')) received = response.json()
self.assertEqual(received['no_content_type'], 'no content') self.assertEqual(received['no_content_type'], 'no content')
self.assertEqual(received['simple_file'], 'text content') self.assertEqual(received['simple_file'], 'text content')
self.assertEqual(received['string'], 'string content') self.assertEqual(received['string'], 'string content')
@ -325,7 +320,7 @@ class FileUploadTests(TestCase):
'no_content_type': no_content_type, 'no_content_type': no_content_type,
'simple_file': simple_file, 'simple_file': simple_file,
}) })
received = json.loads(response.content.decode('utf-8')) received = response.json()
self.assertEqual(received['no_content_type'], {}) self.assertEqual(received['no_content_type'], {})
self.assertEqual(received['simple_file'], {'test-key': 'test_value'}) self.assertEqual(received['simple_file'], {'test-key': 'test_value'})
@ -352,8 +347,7 @@ class FileUploadTests(TestCase):
'REQUEST_METHOD': 'POST', 'REQUEST_METHOD': 'POST',
'wsgi.input': payload, 'wsgi.input': payload,
} }
got = json.loads(self.client.request(**r).content.decode('utf-8')) self.assertEqual(self.client.request(**r).json(), {})
self.assertEqual(got, {})
def test_empty_multipart_handled_gracefully(self): def test_empty_multipart_handled_gracefully(self):
""" """
@ -367,8 +361,7 @@ class FileUploadTests(TestCase):
'REQUEST_METHOD': 'POST', 'REQUEST_METHOD': 'POST',
'wsgi.input': client.FakePayload(b''), 'wsgi.input': client.FakePayload(b''),
} }
got = json.loads(self.client.request(**r).content.decode('utf-8')) self.assertEqual(self.client.request(**r).json(), {})
self.assertEqual(got, {})
def test_custom_upload_handler(self): def test_custom_upload_handler(self):
file = tempfile.NamedTemporaryFile file = tempfile.NamedTemporaryFile
@ -382,14 +375,10 @@ class FileUploadTests(TestCase):
bigfile.seek(0) bigfile.seek(0)
# Small file posting should work. # Small file posting should work.
response = self.client.post('/quota/', {'f': smallfile}) self.assertIn('f', self.client.post('/quota/', {'f': smallfile}).json())
got = json.loads(response.content.decode('utf-8'))
self.assertIn('f', got)
# Large files don't go through. # Large files don't go through.
response = self.client.post("/quota/", {'f': bigfile}) self.assertNotIn('f', self.client.post("/quota/", {'f': bigfile}).json())
got = json.loads(response.content.decode('utf-8'))
self.assertNotIn('f', got)
def test_broken_custom_upload_handler(self): def test_broken_custom_upload_handler(self):
with tempfile.NamedTemporaryFile() as file: with tempfile.NamedTemporaryFile() as file:
@ -421,8 +410,7 @@ class FileUploadTests(TestCase):
'field5': 'test7', 'field5': 'test7',
'file2': (file2, file2a) 'file2': (file2, file2a)
}) })
got = json.loads(response.content.decode('utf-8')) got = response.json()
self.assertEqual(got.get('file1'), 1) self.assertEqual(got.get('file1'), 1)
self.assertEqual(got.get('file2'), 2) self.assertEqual(got.get('file2'), 2)

View File

@ -1,9 +1,8 @@
import hashlib import hashlib
import json
import os import os
from django.core.files.uploadedfile import UploadedFile from django.core.files.uploadedfile import UploadedFile
from django.http import HttpResponse, HttpResponseServerError from django.http import HttpResponse, HttpResponseServerError, JsonResponse
from django.utils.encoding import force_bytes, force_text from django.utils.encoding import force_bytes, force_text
from .models import FileModel from .models import FileModel
@ -89,7 +88,7 @@ def file_upload_echo(request):
Simple view to echo back info about uploaded files for tests. Simple view to echo back info about uploaded files for tests.
""" """
r = {k: f.name for k, f in request.FILES.items()} r = {k: f.name for k, f in request.FILES.items()}
return HttpResponse(json.dumps(r)) return JsonResponse(r)
def file_upload_echo_content(request): def file_upload_echo_content(request):
@ -100,7 +99,7 @@ def file_upload_echo_content(request):
with f: with f:
return f.read().decode('utf-8') return f.read().decode('utf-8')
r = {k: read_and_close(f) for k, f in request.FILES.items()} r = {k: read_and_close(f) for k, f in request.FILES.items()}
return HttpResponse(json.dumps(r)) return JsonResponse(r)
def file_upload_quota(request): def file_upload_quota(request):
@ -128,7 +127,7 @@ def file_upload_getlist_count(request):
for key in request.FILES.keys(): for key in request.FILES.keys():
file_counts[key] = len(request.FILES.getlist(key)) file_counts[key] = len(request.FILES.getlist(key))
return HttpResponse(json.dumps(file_counts)) return JsonResponse(file_counts)
def file_upload_errors(request): def file_upload_errors(request):
@ -153,7 +152,7 @@ def file_upload_content_type_extra(request):
params = {} params = {}
for file_name, uploadedfile in request.FILES.items(): for file_name, uploadedfile in request.FILES.items():
params[file_name] = {k: force_text(v) for k, v in uploadedfile.content_type_extra.items()} params[file_name] = {k: force_text(v) for k, v in uploadedfile.content_type_extra.items()}
return HttpResponse(json.dumps(params)) return JsonResponse(params)
def file_upload_fd_closing(request, access): def file_upload_fd_closing(request, access):