Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

[py3] Fixed file_uploads tests

  • Loading branch information...
commit 0120985095ad6fd59be111bb9a3927ee04b426e8 1 parent 34ac145
Claude Paroz authored
4  django/http/multipartparser.py
@@ -6,7 +6,9 @@
6 6
 """
7 7
 from __future__ import unicode_literals
8 8
 
  9
+import base64
9 10
 import cgi
  11
+
10 12
 from django.conf import settings
11 13
 from django.core.exceptions import SuspiciousOperation
12 14
 from django.utils.datastructures import MultiValueDict
@@ -199,7 +201,7 @@ def parse(self):
199 201
                             if transfer_encoding == 'base64':
200 202
                                 # We only special-case base64 transfer encoding
201 203
                                 try:
202  
-                                    chunk = str(chunk).decode('base64')
  204
+                                    chunk = base64.b64decode(chunk)
203 205
                                 except Exception as e:
204 206
                                     # Since this is only a chunk, any error is an unfixable error.
205 207
                                     raise MultiPartParserError("Could not decode base64 data: %r" % e)
27  tests/regressiontests/file_uploads/tests.py
@@ -12,6 +12,7 @@
12 12
 from django.core.files.uploadedfile import SimpleUploadedFile
13 13
 from django.http.multipartparser import MultiPartParser
14 14
 from django.test import TestCase, client
  15
+from django.utils.encoding import smart_bytes
15 16
 from django.utils.six import StringIO
16 17
 from django.utils import unittest
17 18
 
@@ -48,12 +49,12 @@ def test_large_upload(self):
48 49
             'file_field2': file2,
49 50
             }
50 51
 
51  
-        for key in post_data.keys():
  52
+        for key in list(post_data):
52 53
             try:
53 54
                 post_data[key + '_hash'] = hashlib.sha1(post_data[key].read()).hexdigest()
54 55
                 post_data[key].seek(0)
55 56
             except AttributeError:
56  
-                post_data[key + '_hash'] = hashlib.sha1(post_data[key]).hexdigest()
  57
+                post_data[key + '_hash'] = hashlib.sha1(smart_bytes(post_data[key])).hexdigest()
57 58
 
58 59
         response = self.client.post('/file_uploads/verify/', post_data)
59 60
 
@@ -67,7 +68,7 @@ def test_base64_upload(self):
67 68
             'Content-Type: application/octet-stream',
68 69
             'Content-Transfer-Encoding: base64',
69 70
             '',
70  
-            base64.b64encode(test_string),
  71
+            base64.b64encode(smart_bytes(test_string)).decode('ascii'),
71 72
             '--' + client.BOUNDARY + '--',
72 73
             '',
73 74
         ]).encode('utf-8')
@@ -79,7 +80,7 @@ def test_base64_upload(self):
79 80
             'wsgi.input':     client.FakePayload(payload),
80 81
         }
81 82
         response = self.client.request(**r)
82  
-        received = json.loads(response.content)
  83
+        received = json.loads(response.content.decode('utf-8'))
83 84
 
84 85
         self.assertEqual(received['file'], test_string)
85 86
 
@@ -150,7 +151,7 @@ def test_dangerous_file_names(self):
150 151
         response = self.client.request(**r)
151 152
 
152 153
         # The filenames should have been sanitized by the time it got to the view.
153  
-        recieved = json.loads(response.content)
  154
+        recieved = json.loads(response.content.decode('utf-8'))
154 155
         for i, name in enumerate(scary_file_names):
155 156
             got = recieved["file%s" % i]
156 157
             self.assertEqual(got, "hax0rd.txt")
@@ -174,7 +175,7 @@ def test_filename_overflow(self):
174 175
             'REQUEST_METHOD': 'POST',
175 176
             'wsgi.input':     client.FakePayload(payload),
176 177
         }
177  
-        got = json.loads(self.client.request(**r).content)
  178
+        got = json.loads(self.client.request(**r).content.decode('utf-8'))
178 179
         self.assertTrue(len(got['file']) < 256, "Got a long file name (%s characters)." % len(got['file']))
179 180
 
180 181
     def test_truncated_multipart_handled_gracefully(self):
@@ -200,7 +201,7 @@ def test_truncated_multipart_handled_gracefully(self):
200 201
             'REQUEST_METHOD': 'POST',
201 202
             'wsgi.input': client.FakePayload(payload),
202 203
         }
203  
-        got = json.loads(self.client.request(**r).content)
  204
+        got = json.loads(self.client.request(**r).content.decode('utf-8'))
204 205
         self.assertEqual(got, {})
205 206
 
206 207
     def test_empty_multipart_handled_gracefully(self):
@@ -215,7 +216,7 @@ def test_empty_multipart_handled_gracefully(self):
215 216
             'REQUEST_METHOD': 'POST',
216 217
             'wsgi.input': client.FakePayload(b''),
217 218
         }
218  
-        got = json.loads(self.client.request(**r).content)
  219
+        got = json.loads(self.client.request(**r).content.decode('utf-8'))
219 220
         self.assertEqual(got, {})
220 221
 
221 222
     def test_custom_upload_handler(self):
@@ -231,12 +232,12 @@ def test_custom_upload_handler(self):
231 232
 
232 233
         # Small file posting should work.
233 234
         response = self.client.post('/file_uploads/quota/', {'f': smallfile})
234  
-        got = json.loads(response.content)
  235
+        got = json.loads(response.content.decode('utf-8'))
235 236
         self.assertTrue('f' in got)
236 237
 
237 238
         # Large files don't go through.
238 239
         response = self.client.post("/file_uploads/quota/", {'f': bigfile})
239  
-        got = json.loads(response.content)
  240
+        got = json.loads(response.content.decode('utf-8'))
240 241
         self.assertTrue('f' not in got)
241 242
 
242 243
     def test_broken_custom_upload_handler(self):
@@ -274,7 +275,7 @@ def test_fileupload_getlist(self):
274 275
             'field5': 'test7',
275 276
             'file2': (file2, file2a)
276 277
         })
277  
-        got = json.loads(response.content)
  278
+        got = json.loads(response.content.decode('utf-8'))
278 279
 
279 280
         self.assertEqual(got.get('file1'), 1)
280 281
         self.assertEqual(got.get('file2'), 2)
@@ -299,8 +300,8 @@ def handle_uncaught_exception(self, request, resolver, exc_info):
299 300
         # it raises when there is an attempt to read more than the available bytes:
300 301
         try:
301 302
             client.FakePayload(b'a').read(2)
302  
-        except Exception as reference_error:
303  
-            pass
  303
+        except Exception as err:
  304
+            reference_error = err
304 305
 
305 306
         # install the custom handler that tries to access request.POST
306 307
         self.client.handler = POSTAccessingHandler()
5  tests/regressiontests/file_uploads/views.py
@@ -7,6 +7,7 @@
7 7
 from django.core.files.uploadedfile import UploadedFile
8 8
 from django.http import HttpResponse, HttpResponseServerError
9 9
 from django.utils import six
  10
+from django.utils.encoding import smart_bytes
10 11
 
11 12
 from .models import FileModel, UPLOAD_TO
12 13
 from .tests import UNICODE_FILENAME
@@ -45,7 +46,7 @@ def file_upload_view_verify(request):
45 46
         if isinstance(value, UploadedFile):
46 47
             new_hash = hashlib.sha1(value.read()).hexdigest()
47 48
         else:
48  
-            new_hash = hashlib.sha1(value).hexdigest()
  49
+            new_hash = hashlib.sha1(smart_bytes(value)).hexdigest()
49 50
         if new_hash != submitted_hash:
50 51
             return HttpResponseServerError()
51 52
 
@@ -95,7 +96,7 @@ def file_upload_echo_content(request):
95 96
     """
96 97
     Simple view to echo back the content of uploaded files for tests.
97 98
     """
98  
-    r = dict([(k, f.read()) for k, f in request.FILES.items()])
  99
+    r = dict([(k, f.read().decode('utf-8')) for k, f in request.FILES.items()])
99 100
     return HttpResponse(json.dumps(r))
100 101
 
101 102
 def file_upload_quota(request):

0 notes on commit 0120985

Please sign in to comment.
Something went wrong with that request. Please try again.