tests.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. import base64
  2. import hashlib
  3. import os
  4. import shutil
  5. import sys
  6. import tempfile as sys_tempfile
  7. import unittest
  8. from io import BytesIO, StringIO
  9. from unittest import mock
  10. from urllib.parse import quote
  11. from django.core.files import temp as tempfile
  12. from django.core.files.uploadedfile import SimpleUploadedFile
  13. from django.http.multipartparser import (
  14. FILE, MultiPartParser, MultiPartParserError, Parser, parse_header,
  15. )
  16. from django.test import SimpleTestCase, TestCase, client, override_settings
  17. from . import uploadhandler
  18. from .models import FileModel
  19. UNICODE_FILENAME = 'test-0123456789_中文_Orléans.jpg'
  20. MEDIA_ROOT = sys_tempfile.mkdtemp()
  21. UPLOAD_TO = os.path.join(MEDIA_ROOT, 'test_upload')
  22. @override_settings(MEDIA_ROOT=MEDIA_ROOT, ROOT_URLCONF='file_uploads.urls', MIDDLEWARE=[])
  23. class FileUploadTests(TestCase):
  24. @classmethod
  25. def setUpClass(cls):
  26. super().setUpClass()
  27. os.makedirs(MEDIA_ROOT, exist_ok=True)
  28. @classmethod
  29. def tearDownClass(cls):
  30. shutil.rmtree(MEDIA_ROOT)
  31. super().tearDownClass()
  32. def test_simple_upload(self):
  33. with open(__file__, 'rb') as fp:
  34. post_data = {
  35. 'name': 'Ringo',
  36. 'file_field': fp,
  37. }
  38. response = self.client.post('/upload/', post_data)
  39. self.assertEqual(response.status_code, 200)
  40. def test_large_upload(self):
  41. file = tempfile.NamedTemporaryFile
  42. with file(suffix=".file1") as file1, file(suffix=".file2") as file2:
  43. file1.write(b'a' * (2 ** 21))
  44. file1.seek(0)
  45. file2.write(b'a' * (10 * 2 ** 20))
  46. file2.seek(0)
  47. post_data = {
  48. 'name': 'Ringo',
  49. 'file_field1': file1,
  50. 'file_field2': file2,
  51. }
  52. for key in list(post_data):
  53. try:
  54. post_data[key + '_hash'] = hashlib.sha1(post_data[key].read()).hexdigest()
  55. post_data[key].seek(0)
  56. except AttributeError:
  57. post_data[key + '_hash'] = hashlib.sha1(post_data[key].encode()).hexdigest()
  58. response = self.client.post('/verify/', post_data)
  59. self.assertEqual(response.status_code, 200)
  60. def _test_base64_upload(self, content, encode=base64.b64encode):
  61. payload = client.FakePayload("\r\n".join([
  62. '--' + client.BOUNDARY,
  63. 'Content-Disposition: form-data; name="file"; filename="test.txt"',
  64. 'Content-Type: application/octet-stream',
  65. 'Content-Transfer-Encoding: base64',
  66. '']))
  67. payload.write(b'\r\n' + encode(content.encode()) + b'\r\n')
  68. payload.write('--' + client.BOUNDARY + '--\r\n')
  69. r = {
  70. 'CONTENT_LENGTH': len(payload),
  71. 'CONTENT_TYPE': client.MULTIPART_CONTENT,
  72. 'PATH_INFO': "/echo_content/",
  73. 'REQUEST_METHOD': 'POST',
  74. 'wsgi.input': payload,
  75. }
  76. response = self.client.request(**r)
  77. self.assertEqual(response.json()['file'], content)
  78. def test_base64_upload(self):
  79. self._test_base64_upload("This data will be transmitted base64-encoded.")
  80. def test_big_base64_upload(self):
  81. self._test_base64_upload("Big data" * 68000) # > 512Kb
  82. def test_big_base64_newlines_upload(self):
  83. self._test_base64_upload("Big data" * 68000, encode=base64.encodebytes)
  84. def test_unicode_file_name(self):
  85. with sys_tempfile.TemporaryDirectory() as temp_dir:
  86. # This file contains Chinese symbols and an accented char in the name.
  87. with open(os.path.join(temp_dir, UNICODE_FILENAME), 'w+b') as file1:
  88. file1.write(b'b' * (2 ** 10))
  89. file1.seek(0)
  90. response = self.client.post('/unicode_name/', {'file_unicode': file1})
  91. self.assertEqual(response.status_code, 200)
  92. def test_unicode_file_name_rfc2231(self):
  93. """
  94. Test receiving file upload when filename is encoded with RFC2231
  95. (#22971).
  96. """
  97. payload = client.FakePayload()
  98. payload.write('\r\n'.join([
  99. '--' + client.BOUNDARY,
  100. 'Content-Disposition: form-data; name="file_unicode"; filename*=UTF-8\'\'%s' % quote(UNICODE_FILENAME),
  101. 'Content-Type: application/octet-stream',
  102. '',
  103. 'You got pwnd.\r\n',
  104. '\r\n--' + client.BOUNDARY + '--\r\n'
  105. ]))
  106. r = {
  107. 'CONTENT_LENGTH': len(payload),
  108. 'CONTENT_TYPE': client.MULTIPART_CONTENT,
  109. 'PATH_INFO': "/unicode_name/",
  110. 'REQUEST_METHOD': 'POST',
  111. 'wsgi.input': payload,
  112. }
  113. response = self.client.request(**r)
  114. self.assertEqual(response.status_code, 200)
  115. def test_unicode_name_rfc2231(self):
  116. """
  117. Test receiving file upload when filename is encoded with RFC2231
  118. (#22971).
  119. """
  120. payload = client.FakePayload()
  121. payload.write(
  122. '\r\n'.join([
  123. '--' + client.BOUNDARY,
  124. 'Content-Disposition: form-data; name*=UTF-8\'\'file_unicode; filename*=UTF-8\'\'%s' % quote(
  125. UNICODE_FILENAME
  126. ),
  127. 'Content-Type: application/octet-stream',
  128. '',
  129. 'You got pwnd.\r\n',
  130. '\r\n--' + client.BOUNDARY + '--\r\n'
  131. ])
  132. )
  133. r = {
  134. 'CONTENT_LENGTH': len(payload),
  135. 'CONTENT_TYPE': client.MULTIPART_CONTENT,
  136. 'PATH_INFO': "/unicode_name/",
  137. 'REQUEST_METHOD': 'POST',
  138. 'wsgi.input': payload,
  139. }
  140. response = self.client.request(**r)
  141. self.assertEqual(response.status_code, 200)
  142. def test_unicode_file_name_rfc2231_with_double_quotes(self):
  143. payload = client.FakePayload()
  144. payload.write('\r\n'.join([
  145. '--' + client.BOUNDARY,
  146. 'Content-Disposition: form-data; name="file_unicode"; '
  147. 'filename*="UTF-8\'\'%s"' % quote(UNICODE_FILENAME),
  148. 'Content-Type: application/octet-stream',
  149. '',
  150. 'You got pwnd.\r\n',
  151. '\r\n--' + client.BOUNDARY + '--\r\n',
  152. ]))
  153. r = {
  154. 'CONTENT_LENGTH': len(payload),
  155. 'CONTENT_TYPE': client.MULTIPART_CONTENT,
  156. 'PATH_INFO': '/unicode_name/',
  157. 'REQUEST_METHOD': 'POST',
  158. 'wsgi.input': payload,
  159. }
  160. response = self.client.request(**r)
  161. self.assertEqual(response.status_code, 200)
  162. def test_unicode_name_rfc2231_with_double_quotes(self):
  163. payload = client.FakePayload()
  164. payload.write('\r\n'.join([
  165. '--' + client.BOUNDARY,
  166. 'Content-Disposition: form-data; name*="UTF-8\'\'file_unicode"; '
  167. 'filename*="UTF-8\'\'%s"' % quote(UNICODE_FILENAME),
  168. 'Content-Type: application/octet-stream',
  169. '',
  170. 'You got pwnd.\r\n',
  171. '\r\n--' + client.BOUNDARY + '--\r\n'
  172. ]))
  173. r = {
  174. 'CONTENT_LENGTH': len(payload),
  175. 'CONTENT_TYPE': client.MULTIPART_CONTENT,
  176. 'PATH_INFO': '/unicode_name/',
  177. 'REQUEST_METHOD': 'POST',
  178. 'wsgi.input': payload,
  179. }
  180. response = self.client.request(**r)
  181. self.assertEqual(response.status_code, 200)
  182. def test_blank_filenames(self):
  183. """
  184. Receiving file upload when filename is blank (before and after
  185. sanitization) should be okay.
  186. """
  187. filenames = [
  188. '',
  189. # Normalized by MultiPartParser.IE_sanitize().
  190. 'C:\\Windows\\',
  191. # Normalized by os.path.basename().
  192. '/',
  193. 'ends-with-slash/',
  194. ]
  195. payload = client.FakePayload()
  196. for i, name in enumerate(filenames):
  197. payload.write('\r\n'.join([
  198. '--' + client.BOUNDARY,
  199. 'Content-Disposition: form-data; name="file%s"; filename="%s"' % (i, name),
  200. 'Content-Type: application/octet-stream',
  201. '',
  202. 'You got pwnd.\r\n'
  203. ]))
  204. payload.write('\r\n--' + client.BOUNDARY + '--\r\n')
  205. r = {
  206. 'CONTENT_LENGTH': len(payload),
  207. 'CONTENT_TYPE': client.MULTIPART_CONTENT,
  208. 'PATH_INFO': '/echo/',
  209. 'REQUEST_METHOD': 'POST',
  210. 'wsgi.input': payload,
  211. }
  212. response = self.client.request(**r)
  213. self.assertEqual(response.status_code, 200)
  214. # Empty filenames should be ignored
  215. received = response.json()
  216. for i, name in enumerate(filenames):
  217. self.assertIsNone(received.get('file%s' % i))
  218. def test_dangerous_file_names(self):
  219. """Uploaded file names should be sanitized before ever reaching the view."""
  220. # This test simulates possible directory traversal attacks by a
  221. # malicious uploader We have to do some monkeybusiness here to construct
  222. # a malicious payload with an invalid file name (containing os.sep or
  223. # os.pardir). This similar to what an attacker would need to do when
  224. # trying such an attack.
  225. scary_file_names = [
  226. "/tmp/hax0rd.txt", # Absolute path, *nix-style.
  227. "C:\\Windows\\hax0rd.txt", # Absolute path, win-style.
  228. "C:/Windows/hax0rd.txt", # Absolute path, broken-style.
  229. "\\tmp\\hax0rd.txt", # Absolute path, broken in a different way.
  230. "/tmp\\hax0rd.txt", # Absolute path, broken by mixing.
  231. "subdir/hax0rd.txt", # Descendant path, *nix-style.
  232. "subdir\\hax0rd.txt", # Descendant path, win-style.
  233. "sub/dir\\hax0rd.txt", # Descendant path, mixed.
  234. "../../hax0rd.txt", # Relative path, *nix-style.
  235. "..\\..\\hax0rd.txt", # Relative path, win-style.
  236. "../..\\hax0rd.txt" # Relative path, mixed.
  237. ]
  238. payload = client.FakePayload()
  239. for i, name in enumerate(scary_file_names):
  240. payload.write('\r\n'.join([
  241. '--' + client.BOUNDARY,
  242. 'Content-Disposition: form-data; name="file%s"; filename="%s"' % (i, name),
  243. 'Content-Type: application/octet-stream',
  244. '',
  245. 'You got pwnd.\r\n'
  246. ]))
  247. payload.write('\r\n--' + client.BOUNDARY + '--\r\n')
  248. r = {
  249. 'CONTENT_LENGTH': len(payload),
  250. 'CONTENT_TYPE': client.MULTIPART_CONTENT,
  251. 'PATH_INFO': "/echo/",
  252. 'REQUEST_METHOD': 'POST',
  253. 'wsgi.input': payload,
  254. }
  255. response = self.client.request(**r)
  256. # The filenames should have been sanitized by the time it got to the view.
  257. received = response.json()
  258. for i, name in enumerate(scary_file_names):
  259. got = received["file%s" % i]
  260. self.assertEqual(got, "hax0rd.txt")
  261. def test_filename_overflow(self):
  262. """File names over 256 characters (dangerous on some platforms) get fixed up."""
  263. long_str = 'f' * 300
  264. cases = [
  265. # field name, filename, expected
  266. ('long_filename', '%s.txt' % long_str, '%s.txt' % long_str[:251]),
  267. ('long_extension', 'foo.%s' % long_str, '.%s' % long_str[:254]),
  268. ('no_extension', long_str, long_str[:255]),
  269. ('no_filename', '.%s' % long_str, '.%s' % long_str[:254]),
  270. ('long_everything', '%s.%s' % (long_str, long_str), '.%s' % long_str[:254]),
  271. ]
  272. payload = client.FakePayload()
  273. for name, filename, _ in cases:
  274. payload.write("\r\n".join([
  275. '--' + client.BOUNDARY,
  276. 'Content-Disposition: form-data; name="{}"; filename="{}"',
  277. 'Content-Type: application/octet-stream',
  278. '',
  279. 'Oops.',
  280. ''
  281. ]).format(name, filename))
  282. payload.write('\r\n--' + client.BOUNDARY + '--\r\n')
  283. r = {
  284. 'CONTENT_LENGTH': len(payload),
  285. 'CONTENT_TYPE': client.MULTIPART_CONTENT,
  286. 'PATH_INFO': "/echo/",
  287. 'REQUEST_METHOD': 'POST',
  288. 'wsgi.input': payload,
  289. }
  290. response = self.client.request(**r)
  291. result = response.json()
  292. for name, _, expected in cases:
  293. got = result[name]
  294. self.assertEqual(expected, got, 'Mismatch for {}'.format(name))
  295. self.assertLess(len(got), 256,
  296. "Got a long file name (%s characters)." % len(got))
  297. def test_file_content(self):
  298. file = tempfile.NamedTemporaryFile
  299. with file(suffix=".ctype_extra") as no_content_type, file(suffix=".ctype_extra") as simple_file:
  300. no_content_type.write(b'no content')
  301. no_content_type.seek(0)
  302. simple_file.write(b'text content')
  303. simple_file.seek(0)
  304. simple_file.content_type = 'text/plain'
  305. string_io = StringIO('string content')
  306. bytes_io = BytesIO(b'binary content')
  307. response = self.client.post('/echo_content/', {
  308. 'no_content_type': no_content_type,
  309. 'simple_file': simple_file,
  310. 'string': string_io,
  311. 'binary': bytes_io,
  312. })
  313. received = response.json()
  314. self.assertEqual(received['no_content_type'], 'no content')
  315. self.assertEqual(received['simple_file'], 'text content')
  316. self.assertEqual(received['string'], 'string content')
  317. self.assertEqual(received['binary'], 'binary content')
  318. def test_content_type_extra(self):
  319. """Uploaded files may have content type parameters available."""
  320. file = tempfile.NamedTemporaryFile
  321. with file(suffix=".ctype_extra") as no_content_type, file(suffix=".ctype_extra") as simple_file:
  322. no_content_type.write(b'something')
  323. no_content_type.seek(0)
  324. simple_file.write(b'something')
  325. simple_file.seek(0)
  326. simple_file.content_type = 'text/plain; test-key=test_value'
  327. response = self.client.post('/echo_content_type_extra/', {
  328. 'no_content_type': no_content_type,
  329. 'simple_file': simple_file,
  330. })
  331. received = response.json()
  332. self.assertEqual(received['no_content_type'], {})
  333. self.assertEqual(received['simple_file'], {'test-key': 'test_value'})
  334. def test_truncated_multipart_handled_gracefully(self):
  335. """
  336. If passed an incomplete multipart message, MultiPartParser does not
  337. attempt to read beyond the end of the stream, and simply will handle
  338. the part that can be parsed gracefully.
  339. """
  340. payload_str = "\r\n".join([
  341. '--' + client.BOUNDARY,
  342. 'Content-Disposition: form-data; name="file"; filename="foo.txt"',
  343. 'Content-Type: application/octet-stream',
  344. '',
  345. 'file contents'
  346. '--' + client.BOUNDARY + '--',
  347. '',
  348. ])
  349. payload = client.FakePayload(payload_str[:-10])
  350. r = {
  351. 'CONTENT_LENGTH': len(payload),
  352. 'CONTENT_TYPE': client.MULTIPART_CONTENT,
  353. 'PATH_INFO': '/echo/',
  354. 'REQUEST_METHOD': 'POST',
  355. 'wsgi.input': payload,
  356. }
  357. self.assertEqual(self.client.request(**r).json(), {})
  358. def test_empty_multipart_handled_gracefully(self):
  359. """
  360. If passed an empty multipart message, MultiPartParser will return
  361. an empty QueryDict.
  362. """
  363. r = {
  364. 'CONTENT_LENGTH': 0,
  365. 'CONTENT_TYPE': client.MULTIPART_CONTENT,
  366. 'PATH_INFO': '/echo/',
  367. 'REQUEST_METHOD': 'POST',
  368. 'wsgi.input': client.FakePayload(b''),
  369. }
  370. self.assertEqual(self.client.request(**r).json(), {})
  371. def test_custom_upload_handler(self):
  372. file = tempfile.NamedTemporaryFile
  373. with file() as smallfile, file() as bigfile:
  374. # A small file (under the 5M quota)
  375. smallfile.write(b'a' * (2 ** 21))
  376. smallfile.seek(0)
  377. # A big file (over the quota)
  378. bigfile.write(b'a' * (10 * 2 ** 20))
  379. bigfile.seek(0)
  380. # Small file posting should work.
  381. self.assertIn('f', self.client.post('/quota/', {'f': smallfile}).json())
  382. # Large files don't go through.
  383. self.assertNotIn('f', self.client.post("/quota/", {'f': bigfile}).json())
  384. def test_broken_custom_upload_handler(self):
  385. with tempfile.NamedTemporaryFile() as file:
  386. file.write(b'a' * (2 ** 21))
  387. file.seek(0)
  388. msg = 'You cannot alter upload handlers after the upload has been processed.'
  389. with self.assertRaisesMessage(AttributeError, msg):
  390. self.client.post('/quota/broken/', {'f': file})
  391. def test_stop_upload_temporary_file_handler(self):
  392. with tempfile.NamedTemporaryFile() as temp_file:
  393. temp_file.write(b'a')
  394. temp_file.seek(0)
  395. response = self.client.post('/temp_file/stop_upload/', {'file': temp_file})
  396. temp_path = response.json()['temp_path']
  397. self.assertIs(os.path.exists(temp_path), False)
  398. def test_upload_interrupted_temporary_file_handler(self):
  399. # Simulate an interrupted upload by omitting the closing boundary.
  400. class MockedParser(Parser):
  401. def __iter__(self):
  402. for item in super().__iter__():
  403. item_type, meta_data, field_stream = item
  404. yield item_type, meta_data, field_stream
  405. if item_type == FILE:
  406. return
  407. with tempfile.NamedTemporaryFile() as temp_file:
  408. temp_file.write(b'a')
  409. temp_file.seek(0)
  410. with mock.patch(
  411. 'django.http.multipartparser.Parser',
  412. MockedParser,
  413. ):
  414. response = self.client.post(
  415. '/temp_file/upload_interrupted/',
  416. {'file': temp_file},
  417. )
  418. temp_path = response.json()['temp_path']
  419. self.assertIs(os.path.exists(temp_path), False)
  420. def test_fileupload_getlist(self):
  421. file = tempfile.NamedTemporaryFile
  422. with file() as file1, file() as file2, file() as file2a:
  423. file1.write(b'a' * (2 ** 23))
  424. file1.seek(0)
  425. file2.write(b'a' * (2 * 2 ** 18))
  426. file2.seek(0)
  427. file2a.write(b'a' * (5 * 2 ** 20))
  428. file2a.seek(0)
  429. response = self.client.post('/getlist_count/', {
  430. 'file1': file1,
  431. 'field1': 'test',
  432. 'field2': 'test3',
  433. 'field3': 'test5',
  434. 'field4': 'test6',
  435. 'field5': 'test7',
  436. 'file2': (file2, file2a)
  437. })
  438. got = response.json()
  439. self.assertEqual(got.get('file1'), 1)
  440. self.assertEqual(got.get('file2'), 2)
  441. def test_fileuploads_closed_at_request_end(self):
  442. file = tempfile.NamedTemporaryFile
  443. with file() as f1, file() as f2a, file() as f2b:
  444. response = self.client.post('/fd_closing/t/', {
  445. 'file': f1,
  446. 'file2': (f2a, f2b),
  447. })
  448. request = response.wsgi_request
  449. # The files were parsed.
  450. self.assertTrue(hasattr(request, '_files'))
  451. file = request._files['file']
  452. self.assertTrue(file.closed)
  453. files = request._files.getlist('file2')
  454. self.assertTrue(files[0].closed)
  455. self.assertTrue(files[1].closed)
  456. def test_no_parsing_triggered_by_fd_closing(self):
  457. file = tempfile.NamedTemporaryFile
  458. with file() as f1, file() as f2a, file() as f2b:
  459. response = self.client.post('/fd_closing/f/', {
  460. 'file': f1,
  461. 'file2': (f2a, f2b),
  462. })
  463. request = response.wsgi_request
  464. # The fd closing logic doesn't trigger parsing of the stream
  465. self.assertFalse(hasattr(request, '_files'))
  466. def test_file_error_blocking(self):
  467. """
  468. The server should not block when there are upload errors (bug #8622).
  469. This can happen if something -- i.e. an exception handler -- tries to
  470. access POST while handling an error in parsing POST. This shouldn't
  471. cause an infinite loop!
  472. """
  473. class POSTAccessingHandler(client.ClientHandler):
  474. """A handler that'll access POST during an exception."""
  475. def handle_uncaught_exception(self, request, resolver, exc_info):
  476. ret = super().handle_uncaught_exception(request, resolver, exc_info)
  477. request.POST # evaluate
  478. return ret
  479. # Maybe this is a little more complicated that it needs to be; but if
  480. # the django.test.client.FakePayload.read() implementation changes then
  481. # this test would fail. So we need to know exactly what kind of error
  482. # it raises when there is an attempt to read more than the available bytes:
  483. try:
  484. client.FakePayload(b'a').read(2)
  485. except Exception as err:
  486. reference_error = err
  487. # install the custom handler that tries to access request.POST
  488. self.client.handler = POSTAccessingHandler()
  489. with open(__file__, 'rb') as fp:
  490. post_data = {
  491. 'name': 'Ringo',
  492. 'file_field': fp,
  493. }
  494. try:
  495. self.client.post('/upload_errors/', post_data)
  496. except reference_error.__class__ as err:
  497. self.assertNotEqual(
  498. str(err),
  499. str(reference_error),
  500. "Caught a repeated exception that'll cause an infinite loop in file uploads."
  501. )
  502. except Exception as err:
  503. # CustomUploadError is the error that should have been raised
  504. self.assertEqual(err.__class__, uploadhandler.CustomUploadError)
  505. def test_filename_case_preservation(self):
  506. """
  507. The storage backend shouldn't mess with the case of the filenames
  508. uploaded.
  509. """
  510. # Synthesize the contents of a file upload with a mixed case filename
  511. # so we don't have to carry such a file in the Django tests source code
  512. # tree.
  513. vars = {'boundary': 'oUrBoUnDaRyStRiNg'}
  514. post_data = [
  515. '--%(boundary)s',
  516. 'Content-Disposition: form-data; name="file_field"; filename="MiXeD_cAsE.txt"',
  517. 'Content-Type: application/octet-stream',
  518. '',
  519. 'file contents\n'
  520. '',
  521. '--%(boundary)s--\r\n',
  522. ]
  523. response = self.client.post(
  524. '/filename_case/',
  525. '\r\n'.join(post_data) % vars,
  526. 'multipart/form-data; boundary=%(boundary)s' % vars
  527. )
  528. self.assertEqual(response.status_code, 200)
  529. id = int(response.content)
  530. obj = FileModel.objects.get(pk=id)
  531. # The name of the file uploaded and the file stored in the server-side
  532. # shouldn't differ.
  533. self.assertEqual(os.path.basename(obj.testfile.path), 'MiXeD_cAsE.txt')
  534. @override_settings(MEDIA_ROOT=MEDIA_ROOT)
  535. class DirectoryCreationTests(SimpleTestCase):
  536. """
  537. Tests for error handling during directory creation
  538. via _save_FIELD_file (ticket #6450)
  539. """
  540. @classmethod
  541. def setUpClass(cls):
  542. super().setUpClass()
  543. os.makedirs(MEDIA_ROOT, exist_ok=True)
  544. @classmethod
  545. def tearDownClass(cls):
  546. shutil.rmtree(MEDIA_ROOT)
  547. super().tearDownClass()
  548. def setUp(self):
  549. self.obj = FileModel()
  550. @unittest.skipIf(sys.platform == 'win32', "Python on Windows doesn't have working os.chmod().")
  551. def test_readonly_root(self):
  552. """Permission errors are not swallowed"""
  553. os.chmod(MEDIA_ROOT, 0o500)
  554. self.addCleanup(os.chmod, MEDIA_ROOT, 0o700)
  555. with self.assertRaises(PermissionError):
  556. self.obj.testfile.save('foo.txt', SimpleUploadedFile('foo.txt', b'x'), save=False)
  557. def test_not_a_directory(self):
  558. # Create a file with the upload directory name
  559. open(UPLOAD_TO, 'wb').close()
  560. self.addCleanup(os.remove, UPLOAD_TO)
  561. msg = '%s exists and is not a directory.' % UPLOAD_TO
  562. with self.assertRaisesMessage(FileExistsError, msg):
  563. with SimpleUploadedFile('foo.txt', b'x') as file:
  564. self.obj.testfile.save('foo.txt', file, save=False)
  565. class MultiParserTests(SimpleTestCase):
  566. def test_empty_upload_handlers(self):
  567. # We're not actually parsing here; just checking if the parser properly
  568. # instantiates with empty upload handlers.
  569. MultiPartParser({
  570. 'CONTENT_TYPE': 'multipart/form-data; boundary=_foo',
  571. 'CONTENT_LENGTH': '1'
  572. }, StringIO('x'), [], 'utf-8')
  573. def test_invalid_content_type(self):
  574. with self.assertRaisesMessage(MultiPartParserError, 'Invalid Content-Type: text/plain'):
  575. MultiPartParser({
  576. 'CONTENT_TYPE': 'text/plain',
  577. 'CONTENT_LENGTH': '1',
  578. }, StringIO('x'), [], 'utf-8')
  579. def test_negative_content_length(self):
  580. with self.assertRaisesMessage(MultiPartParserError, 'Invalid content length: -1'):
  581. MultiPartParser({
  582. 'CONTENT_TYPE': 'multipart/form-data; boundary=_foo',
  583. 'CONTENT_LENGTH': -1,
  584. }, StringIO('x'), [], 'utf-8')
  585. def test_bad_type_content_length(self):
  586. multipart_parser = MultiPartParser({
  587. 'CONTENT_TYPE': 'multipart/form-data; boundary=_foo',
  588. 'CONTENT_LENGTH': 'a',
  589. }, StringIO('x'), [], 'utf-8')
  590. self.assertEqual(multipart_parser._content_length, 0)
  591. def test_rfc2231_parsing(self):
  592. test_data = (
  593. (b"Content-Type: application/x-stuff; title*=us-ascii'en-us'This%20is%20%2A%2A%2Afun%2A%2A%2A",
  594. "This is ***fun***"),
  595. (b"Content-Type: application/x-stuff; title*=UTF-8''foo-%c3%a4.html",
  596. "foo-ä.html"),
  597. (b"Content-Type: application/x-stuff; title*=iso-8859-1''foo-%E4.html",
  598. "foo-ä.html"),
  599. )
  600. for raw_line, expected_title in test_data:
  601. parsed = parse_header(raw_line)
  602. self.assertEqual(parsed[1]['title'], expected_title)
  603. def test_rfc2231_wrong_title(self):
  604. """
  605. Test wrongly formatted RFC 2231 headers (missing double single quotes).
  606. Parsing should not crash (#24209).
  607. """
  608. test_data = (
  609. (b"Content-Type: application/x-stuff; title*='This%20is%20%2A%2A%2Afun%2A%2A%2A",
  610. b"'This%20is%20%2A%2A%2Afun%2A%2A%2A"),
  611. (b"Content-Type: application/x-stuff; title*='foo.html",
  612. b"'foo.html"),
  613. (b"Content-Type: application/x-stuff; title*=bar.html",
  614. b"bar.html"),
  615. )
  616. for raw_line, expected_title in test_data:
  617. parsed = parse_header(raw_line)
  618. self.assertEqual(parsed[1]['title'], expected_title)