tests.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import errno
  4. import os
  5. import shutil
  6. import sys
  7. import tempfile
  8. import time
  9. import unittest
  10. import warnings
  11. from datetime import datetime, timedelta
  12. try:
  13. import threading
  14. except ImportError:
  15. import dummy_threading as threading
  16. from django.core.cache import cache
  17. from django.core.exceptions import SuspiciousOperation, SuspiciousFileOperation
  18. from django.core.files.base import File, ContentFile
  19. from django.core.files.storage import FileSystemStorage, get_storage_class
  20. from django.core.files.uploadedfile import (InMemoryUploadedFile, SimpleUploadedFile,
  21. TemporaryUploadedFile)
  22. from django.test import LiveServerTestCase, SimpleTestCase
  23. from django.test import override_settings
  24. from django.utils import six
  25. from django.utils.six.moves.urllib.request import urlopen
  26. from django.utils._os import upath
  27. from .models import Storage, temp_storage, temp_storage_location
  28. FILE_SUFFIX_REGEX = '[A-Za-z0-9]{7}'
  29. class GetStorageClassTests(SimpleTestCase):
  30. def test_get_filesystem_storage(self):
  31. """
  32. get_storage_class returns the class for a storage backend name/path.
  33. """
  34. self.assertEqual(
  35. get_storage_class('django.core.files.storage.FileSystemStorage'),
  36. FileSystemStorage)
  37. def test_get_invalid_storage_module(self):
  38. """
  39. get_storage_class raises an error if the requested import don't exist.
  40. """
  41. with six.assertRaisesRegex(self, ImportError, "No module named '?storage'?"):
  42. get_storage_class('storage.NonExistingStorage')
  43. def test_get_nonexisting_storage_class(self):
  44. """
  45. get_storage_class raises an error if the requested class don't exist.
  46. """
  47. self.assertRaises(ImportError, get_storage_class,
  48. 'django.core.files.storage.NonExistingStorage')
  49. def test_get_nonexisting_storage_module(self):
  50. """
  51. get_storage_class raises an error if the requested module don't exist.
  52. """
  53. # Error message may or may not be the fully qualified path.
  54. with six.assertRaisesRegex(self, ImportError,
  55. "No module named '?(django.core.files.)?non_existing_storage'?"):
  56. get_storage_class(
  57. 'django.core.files.non_existing_storage.NonExistingStorage')
  58. class FileStorageDeconstructionTests(unittest.TestCase):
  59. def test_deconstruction(self):
  60. path, args, kwargs = temp_storage.deconstruct()
  61. self.assertEqual(path, "django.core.files.storage.FileSystemStorage")
  62. self.assertEqual(args, tuple())
  63. self.assertEqual(kwargs, {'location': temp_storage_location})
  64. kwargs_orig = {
  65. 'location': temp_storage_location,
  66. 'base_url': 'http://myfiles.example.com/'
  67. }
  68. storage = FileSystemStorage(**kwargs_orig)
  69. path, args, kwargs = storage.deconstruct()
  70. self.assertEqual(kwargs, kwargs_orig)
  71. class FileStorageTests(unittest.TestCase):
  72. storage_class = FileSystemStorage
  73. def setUp(self):
  74. self.temp_dir = tempfile.mkdtemp()
  75. self.storage = self.storage_class(location=self.temp_dir,
  76. base_url='/test_media_url/')
  77. # Set up a second temporary directory which is ensured to have a mixed
  78. # case name.
  79. self.temp_dir2 = tempfile.mkdtemp(suffix='aBc')
  80. def tearDown(self):
  81. shutil.rmtree(self.temp_dir)
  82. shutil.rmtree(self.temp_dir2)
  83. def test_empty_location(self):
  84. """
  85. Makes sure an exception is raised if the location is empty
  86. """
  87. storage = self.storage_class(location='')
  88. self.assertEqual(storage.base_location, '')
  89. self.assertEqual(storage.location, upath(os.getcwd()))
  90. def test_file_access_options(self):
  91. """
  92. Standard file access options are available, and work as expected.
  93. """
  94. self.assertFalse(self.storage.exists('storage_test'))
  95. f = self.storage.open('storage_test', 'w')
  96. f.write('storage contents')
  97. f.close()
  98. self.assertTrue(self.storage.exists('storage_test'))
  99. f = self.storage.open('storage_test', 'r')
  100. self.assertEqual(f.read(), 'storage contents')
  101. f.close()
  102. self.storage.delete('storage_test')
  103. self.assertFalse(self.storage.exists('storage_test'))
  104. def test_file_accessed_time(self):
  105. """
  106. File storage returns a Datetime object for the last accessed time of
  107. a file.
  108. """
  109. self.assertFalse(self.storage.exists('test.file'))
  110. f = ContentFile('custom contents')
  111. f_name = self.storage.save('test.file', f)
  112. atime = self.storage.accessed_time(f_name)
  113. self.assertEqual(atime, datetime.fromtimestamp(
  114. os.path.getatime(self.storage.path(f_name))))
  115. self.assertLess(datetime.now() - self.storage.accessed_time(f_name), timedelta(seconds=2))
  116. self.storage.delete(f_name)
  117. def test_file_created_time(self):
  118. """
  119. File storage returns a Datetime object for the creation time of
  120. a file.
  121. """
  122. self.assertFalse(self.storage.exists('test.file'))
  123. f = ContentFile('custom contents')
  124. f_name = self.storage.save('test.file', f)
  125. ctime = self.storage.created_time(f_name)
  126. self.assertEqual(ctime, datetime.fromtimestamp(
  127. os.path.getctime(self.storage.path(f_name))))
  128. self.assertLess(datetime.now() - self.storage.created_time(f_name), timedelta(seconds=2))
  129. self.storage.delete(f_name)
  130. def test_file_modified_time(self):
  131. """
  132. File storage returns a Datetime object for the last modified time of
  133. a file.
  134. """
  135. self.assertFalse(self.storage.exists('test.file'))
  136. f = ContentFile('custom contents')
  137. f_name = self.storage.save('test.file', f)
  138. mtime = self.storage.modified_time(f_name)
  139. self.assertEqual(mtime, datetime.fromtimestamp(
  140. os.path.getmtime(self.storage.path(f_name))))
  141. self.assertLess(datetime.now() - self.storage.modified_time(f_name), timedelta(seconds=2))
  142. self.storage.delete(f_name)
  143. def test_file_save_without_name(self):
  144. """
  145. File storage extracts the filename from the content object if no
  146. name is given explicitly.
  147. """
  148. self.assertFalse(self.storage.exists('test.file'))
  149. f = ContentFile('custom contents')
  150. f.name = 'test.file'
  151. storage_f_name = self.storage.save(None, f)
  152. self.assertEqual(storage_f_name, f.name)
  153. self.assertTrue(os.path.exists(os.path.join(self.temp_dir, f.name)))
  154. self.storage.delete(storage_f_name)
  155. def test_file_save_with_path(self):
  156. """
  157. Saving a pathname should create intermediate directories as necessary.
  158. """
  159. self.assertFalse(self.storage.exists('path/to'))
  160. self.storage.save('path/to/test.file',
  161. ContentFile('file saved with path'))
  162. self.assertTrue(self.storage.exists('path/to'))
  163. with self.storage.open('path/to/test.file') as f:
  164. self.assertEqual(f.read(), b'file saved with path')
  165. self.assertTrue(os.path.exists(
  166. os.path.join(self.temp_dir, 'path', 'to', 'test.file')))
  167. self.storage.delete('path/to/test.file')
  168. def test_save_doesnt_close(self):
  169. with TemporaryUploadedFile('test', 'text/plain', 1, 'utf8') as file:
  170. file.write(b'1')
  171. file.seek(0)
  172. self.assertFalse(file.closed)
  173. self.storage.save('path/to/test.file', file)
  174. self.assertFalse(file.closed)
  175. self.assertFalse(file.file.closed)
  176. file = InMemoryUploadedFile(six.StringIO('1'), '', 'test',
  177. 'text/plain', 1, 'utf8')
  178. with file:
  179. self.assertFalse(file.closed)
  180. self.storage.save('path/to/test.file', file)
  181. self.assertFalse(file.closed)
  182. self.assertFalse(file.file.closed)
  183. def test_file_path(self):
  184. """
  185. File storage returns the full path of a file
  186. """
  187. self.assertFalse(self.storage.exists('test.file'))
  188. f = ContentFile('custom contents')
  189. f_name = self.storage.save('test.file', f)
  190. self.assertEqual(self.storage.path(f_name),
  191. os.path.join(self.temp_dir, f_name))
  192. self.storage.delete(f_name)
  193. def test_file_url(self):
  194. """
  195. File storage returns a url to access a given file from the Web.
  196. """
  197. self.assertEqual(self.storage.url('test.file'),
  198. '%s%s' % (self.storage.base_url, 'test.file'))
  199. # should encode special chars except ~!*()'
  200. # like encodeURIComponent() JavaScript function do
  201. self.assertEqual(self.storage.url(r"""~!*()'@#$%^&*abc`+ =.file"""),
  202. """/test_media_url/~!*()'%40%23%24%25%5E%26*abc%60%2B%20%3D.file""")
  203. # should stanslate os path separator(s) to the url path separator
  204. self.assertEqual(self.storage.url("""a/b\\c.file"""),
  205. """/test_media_url/a/b/c.file""")
  206. self.storage.base_url = None
  207. self.assertRaises(ValueError, self.storage.url, 'test.file')
  208. # #22717: missing ending slash in base_url should be auto-corrected
  209. storage = self.storage_class(location=self.temp_dir,
  210. base_url='/no_ending_slash')
  211. self.assertEqual(
  212. storage.url('test.file'),
  213. '%s%s' % (storage.base_url, 'test.file')
  214. )
  215. def test_listdir(self):
  216. """
  217. File storage returns a tuple containing directories and files.
  218. """
  219. self.assertFalse(self.storage.exists('storage_test_1'))
  220. self.assertFalse(self.storage.exists('storage_test_2'))
  221. self.assertFalse(self.storage.exists('storage_dir_1'))
  222. self.storage.save('storage_test_1', ContentFile('custom content'))
  223. self.storage.save('storage_test_2', ContentFile('custom content'))
  224. os.mkdir(os.path.join(self.temp_dir, 'storage_dir_1'))
  225. dirs, files = self.storage.listdir('')
  226. self.assertEqual(set(dirs), {'storage_dir_1'})
  227. self.assertEqual(set(files),
  228. {'storage_test_1', 'storage_test_2'})
  229. self.storage.delete('storage_test_1')
  230. self.storage.delete('storage_test_2')
  231. os.rmdir(os.path.join(self.temp_dir, 'storage_dir_1'))
  232. def test_file_storage_prevents_directory_traversal(self):
  233. """
  234. File storage prevents directory traversal (files can only be accessed if
  235. they're below the storage location).
  236. """
  237. self.assertRaises(SuspiciousOperation, self.storage.exists, '..')
  238. self.assertRaises(SuspiciousOperation, self.storage.exists, '/etc/passwd')
  239. def test_file_storage_preserves_filename_case(self):
  240. """The storage backend should preserve case of filenames."""
  241. # Create a storage backend associated with the mixed case name
  242. # directory.
  243. other_temp_storage = self.storage_class(location=self.temp_dir2)
  244. # Ask that storage backend to store a file with a mixed case filename.
  245. mixed_case = 'CaSe_SeNsItIvE'
  246. file = other_temp_storage.open(mixed_case, 'w')
  247. file.write('storage contents')
  248. file.close()
  249. self.assertEqual(os.path.join(self.temp_dir2, mixed_case),
  250. other_temp_storage.path(mixed_case))
  251. other_temp_storage.delete(mixed_case)
  252. def test_makedirs_race_handling(self):
  253. """
  254. File storage should be robust against directory creation race conditions.
  255. """
  256. real_makedirs = os.makedirs
  257. # Monkey-patch os.makedirs, to simulate a normal call, a raced call,
  258. # and an error.
  259. def fake_makedirs(path):
  260. if path == os.path.join(self.temp_dir, 'normal'):
  261. real_makedirs(path)
  262. elif path == os.path.join(self.temp_dir, 'raced'):
  263. real_makedirs(path)
  264. raise OSError(errno.EEXIST, 'simulated EEXIST')
  265. elif path == os.path.join(self.temp_dir, 'error'):
  266. raise OSError(errno.EACCES, 'simulated EACCES')
  267. else:
  268. self.fail('unexpected argument %r' % path)
  269. try:
  270. os.makedirs = fake_makedirs
  271. self.storage.save('normal/test.file',
  272. ContentFile('saved normally'))
  273. with self.storage.open('normal/test.file') as f:
  274. self.assertEqual(f.read(), b'saved normally')
  275. self.storage.save('raced/test.file',
  276. ContentFile('saved with race'))
  277. with self.storage.open('raced/test.file') as f:
  278. self.assertEqual(f.read(), b'saved with race')
  279. # Check that OSErrors aside from EEXIST are still raised.
  280. self.assertRaises(OSError,
  281. self.storage.save, 'error/test.file', ContentFile('not saved'))
  282. finally:
  283. os.makedirs = real_makedirs
  284. def test_remove_race_handling(self):
  285. """
  286. File storage should be robust against file removal race conditions.
  287. """
  288. real_remove = os.remove
  289. # Monkey-patch os.remove, to simulate a normal call, a raced call,
  290. # and an error.
  291. def fake_remove(path):
  292. if path == os.path.join(self.temp_dir, 'normal.file'):
  293. real_remove(path)
  294. elif path == os.path.join(self.temp_dir, 'raced.file'):
  295. real_remove(path)
  296. raise OSError(errno.ENOENT, 'simulated ENOENT')
  297. elif path == os.path.join(self.temp_dir, 'error.file'):
  298. raise OSError(errno.EACCES, 'simulated EACCES')
  299. else:
  300. self.fail('unexpected argument %r' % path)
  301. try:
  302. os.remove = fake_remove
  303. self.storage.save('normal.file', ContentFile('delete normally'))
  304. self.storage.delete('normal.file')
  305. self.assertFalse(self.storage.exists('normal.file'))
  306. self.storage.save('raced.file', ContentFile('delete with race'))
  307. self.storage.delete('raced.file')
  308. self.assertFalse(self.storage.exists('normal.file'))
  309. # Check that OSErrors aside from ENOENT are still raised.
  310. self.storage.save('error.file', ContentFile('delete with error'))
  311. self.assertRaises(OSError, self.storage.delete, 'error.file')
  312. finally:
  313. os.remove = real_remove
  314. def test_file_chunks_error(self):
  315. """
  316. Test behavior when file.chunks() is raising an error
  317. """
  318. f1 = ContentFile('chunks fails')
  319. def failing_chunks():
  320. raise IOError
  321. f1.chunks = failing_chunks
  322. with self.assertRaises(IOError):
  323. self.storage.save('error.file', f1)
  324. def test_delete_no_name(self):
  325. """
  326. Calling delete with an empty name should not try to remove the base
  327. storage directory, but fail loudly (#20660).
  328. """
  329. with self.assertRaises(AssertionError):
  330. self.storage.delete('')
  331. class CustomStorage(FileSystemStorage):
  332. def get_available_name(self, name, max_length=None):
  333. """
  334. Append numbers to duplicate files rather than underscores, like Trac.
  335. """
  336. parts = name.split('.')
  337. basename, ext = parts[0], parts[1:]
  338. number = 2
  339. while self.exists(name):
  340. name = '.'.join([basename, str(number)] + ext)
  341. number += 1
  342. return name
  343. class CustomStorageTests(FileStorageTests):
  344. storage_class = CustomStorage
  345. def test_custom_get_available_name(self):
  346. first = self.storage.save('custom_storage', ContentFile('custom contents'))
  347. self.assertEqual(first, 'custom_storage')
  348. second = self.storage.save('custom_storage', ContentFile('more contents'))
  349. self.assertEqual(second, 'custom_storage.2')
  350. self.storage.delete(first)
  351. self.storage.delete(second)
  352. class FileFieldStorageTests(SimpleTestCase):
  353. def tearDown(self):
  354. shutil.rmtree(temp_storage_location)
  355. def test_files(self):
  356. # Attempting to access a FileField from the class raises a descriptive
  357. # error
  358. self.assertRaises(AttributeError, lambda: Storage.normal)
  359. # An object without a file has limited functionality.
  360. obj1 = Storage()
  361. self.assertEqual(obj1.normal.name, "")
  362. self.assertRaises(ValueError, lambda: obj1.normal.size)
  363. # Saving a file enables full functionality.
  364. obj1.normal.save("django_test.txt", ContentFile("content"))
  365. self.assertEqual(obj1.normal.name, "tests/django_test.txt")
  366. self.assertEqual(obj1.normal.size, 7)
  367. self.assertEqual(obj1.normal.read(), b"content")
  368. obj1.normal.close()
  369. # File objects can be assigned to FileField attributes, but shouldn't
  370. # get committed until the model it's attached to is saved.
  371. obj1.normal = SimpleUploadedFile("assignment.txt", b"content")
  372. dirs, files = temp_storage.listdir("tests")
  373. self.assertEqual(dirs, [])
  374. self.assertNotIn("assignment.txt", files)
  375. obj1.save()
  376. dirs, files = temp_storage.listdir("tests")
  377. self.assertEqual(sorted(files), ["assignment.txt", "django_test.txt"])
  378. # Save another file with the same name.
  379. obj2 = Storage()
  380. obj2.normal.save("django_test.txt", ContentFile("more content"))
  381. obj2_name = obj2.normal.name
  382. six.assertRegex(self, obj2_name, "tests/django_test_%s.txt" % FILE_SUFFIX_REGEX)
  383. self.assertEqual(obj2.normal.size, 12)
  384. obj2.normal.close()
  385. # Deleting an object does not delete the file it uses.
  386. obj2.delete()
  387. obj2.normal.save("django_test.txt", ContentFile("more content"))
  388. self.assertNotEqual(obj2_name, obj2.normal.name)
  389. six.assertRegex(self, obj2.normal.name, "tests/django_test_%s.txt" % FILE_SUFFIX_REGEX)
  390. obj2.normal.close()
  391. def test_filefield_read(self):
  392. # Files can be read in a little at a time, if necessary.
  393. obj = Storage.objects.create(
  394. normal=SimpleUploadedFile("assignment.txt", b"content"))
  395. obj.normal.open()
  396. self.assertEqual(obj.normal.read(3), b"con")
  397. self.assertEqual(obj.normal.read(), b"tent")
  398. self.assertEqual(list(obj.normal.chunks(chunk_size=2)), [b"co", b"nt", b"en", b"t"])
  399. obj.normal.close()
  400. def test_duplicate_filename(self):
  401. # Multiple files with the same name get _(7 random chars) appended to them.
  402. objs = [Storage() for i in range(2)]
  403. for o in objs:
  404. o.normal.save("multiple_files.txt", ContentFile("Same Content"))
  405. try:
  406. names = [o.normal.name for o in objs]
  407. self.assertEqual(names[0], "tests/multiple_files.txt")
  408. six.assertRegex(self, names[1], "tests/multiple_files_%s.txt" % FILE_SUFFIX_REGEX)
  409. finally:
  410. for o in objs:
  411. o.delete()
  412. def test_file_truncation(self):
  413. # Given the max_length is limited, when multiple files get uploaded
  414. # under the same name, then the filename get truncated in order to fit
  415. # in _(7 random chars). When most of the max_length is taken by
  416. # dirname + extension and there are not enough characters in the
  417. # filename to truncate, an exception should be raised.
  418. objs = [Storage() for i in range(2)]
  419. filename = 'filename.ext'
  420. for o in objs:
  421. o.limited_length.save(filename, ContentFile('Same Content'))
  422. try:
  423. # Testing truncation.
  424. names = [o.limited_length.name for o in objs]
  425. self.assertEqual(names[0], 'tests/%s' % filename)
  426. six.assertRegex(self, names[1], 'tests/fi_%s.ext' % FILE_SUFFIX_REGEX)
  427. # Testing exception is raised when filename is too short to truncate.
  428. filename = 'short.longext'
  429. objs[0].limited_length.save(filename, ContentFile('Same Content'))
  430. self.assertRaisesMessage(
  431. SuspiciousFileOperation, 'Storage can not find an available filename',
  432. objs[1].limited_length.save, *(filename, ContentFile('Same Content'))
  433. )
  434. finally:
  435. for o in objs:
  436. o.delete()
  437. def test_extended_length_storage(self):
  438. # Testing FileField with max_length > 255. Most systems have filename
  439. # length limitation of 255. Path takes extra chars.
  440. filename = 251 * 'a' # 4 chars for extension.
  441. obj = Storage()
  442. obj.extended_length.save('%s.txt' % filename, ContentFile('Same Content'))
  443. self.assertEqual(obj.extended_length.name, 'tests/%s.txt' % filename)
  444. self.assertEqual(obj.extended_length.read(), b'Same Content')
  445. obj.extended_length.close()
  446. def test_old_style_storage(self):
  447. # Testing backward-compatibility with old-style storage backends that
  448. # don't take ``max_length`` parameter in ``get_available_name()``
  449. # and save(). A deprecation warning should be raised.
  450. obj = Storage()
  451. with warnings.catch_warnings(record=True) as warns:
  452. warnings.simplefilter('always')
  453. obj.old_style.save('deprecated_storage_test.txt', ContentFile('Same Content'))
  454. self.assertEqual(len(warns), 2)
  455. self.assertEqual(
  456. str(warns[0].message),
  457. 'Backwards compatibility for storage backends without support for '
  458. 'the `max_length` argument in Storage.save() will be removed in '
  459. 'Django 2.0.'
  460. )
  461. self.assertEqual(
  462. str(warns[1].message),
  463. 'Backwards compatibility for storage backends without support for '
  464. 'the `max_length` argument in Storage.get_available_name() will '
  465. 'be removed in Django 2.0.'
  466. )
  467. self.assertEqual(obj.old_style.name, 'tests/deprecated_storage_test.txt')
  468. self.assertEqual(obj.old_style.read(), b'Same Content')
  469. obj.old_style.close()
  470. def test_filefield_default(self):
  471. # Default values allow an object to access a single file.
  472. temp_storage.save('tests/default.txt', ContentFile('default content'))
  473. obj = Storage.objects.create()
  474. self.assertEqual(obj.default.name, "tests/default.txt")
  475. self.assertEqual(obj.default.read(), b"default content")
  476. obj.default.close()
  477. # But it shouldn't be deleted, even if there are no more objects using
  478. # it.
  479. obj.delete()
  480. obj = Storage()
  481. self.assertEqual(obj.default.read(), b"default content")
  482. obj.default.close()
  483. def test_empty_upload_to(self):
  484. # upload_to can be empty, meaning it does not use subdirectory.
  485. obj = Storage()
  486. obj.empty.save('django_test.txt', ContentFile('more content'))
  487. self.assertEqual(obj.empty.name, "./django_test.txt")
  488. self.assertEqual(obj.empty.read(), b"more content")
  489. obj.empty.close()
  490. def test_random_upload_to(self):
  491. # Verify the fix for #5655, making sure the directory is only
  492. # determined once.
  493. obj = Storage()
  494. obj.random.save("random_file", ContentFile("random content"))
  495. self.assertTrue(obj.random.name.endswith("/random_file"))
  496. obj.random.close()
  497. def test_filefield_pickling(self):
  498. # Push an object into the cache to make sure it pickles properly
  499. obj = Storage()
  500. obj.normal.save("django_test.txt", ContentFile("more content"))
  501. obj.normal.close()
  502. cache.set("obj", obj)
  503. self.assertEqual(cache.get("obj").normal.name, "tests/django_test.txt")
  504. def test_file_object(self):
  505. # Create sample file
  506. temp_storage.save('tests/example.txt', ContentFile('some content'))
  507. # Load it as python file object
  508. with open(temp_storage.path('tests/example.txt')) as file_obj:
  509. # Save it using storage and read its content
  510. temp_storage.save('tests/file_obj', file_obj)
  511. self.assertTrue(temp_storage.exists('tests/file_obj'))
  512. with temp_storage.open('tests/file_obj') as f:
  513. self.assertEqual(f.read(), b'some content')
  514. def test_stringio(self):
  515. # Test passing StringIO instance as content argument to save
  516. output = six.StringIO()
  517. output.write('content')
  518. output.seek(0)
  519. # Save it and read written file
  520. temp_storage.save('tests/stringio', output)
  521. self.assertTrue(temp_storage.exists('tests/stringio'))
  522. with temp_storage.open('tests/stringio') as f:
  523. self.assertEqual(f.read(), b'content')
  524. # Tests for a race condition on file saving (#4948).
  525. # This is written in such a way that it'll always pass on platforms
  526. # without threading.
  527. class SlowFile(ContentFile):
  528. def chunks(self):
  529. time.sleep(1)
  530. return super(ContentFile, self).chunks()
  531. class FileSaveRaceConditionTest(unittest.TestCase):
  532. def setUp(self):
  533. self.storage_dir = tempfile.mkdtemp()
  534. self.storage = FileSystemStorage(self.storage_dir)
  535. self.thread = threading.Thread(target=self.save_file, args=['conflict'])
  536. def tearDown(self):
  537. shutil.rmtree(self.storage_dir)
  538. def save_file(self, name):
  539. name = self.storage.save(name, SlowFile(b"Data"))
  540. def test_race_condition(self):
  541. self.thread.start()
  542. self.save_file('conflict')
  543. self.thread.join()
  544. files = sorted(os.listdir(self.storage_dir))
  545. self.assertEqual(files[0], 'conflict')
  546. six.assertRegex(self, files[1], 'conflict_%s' % FILE_SUFFIX_REGEX)
  547. @unittest.skipIf(sys.platform.startswith('win'), "Windows only partially supports umasks and chmod.")
  548. class FileStoragePermissions(unittest.TestCase):
  549. def setUp(self):
  550. self.umask = 0o027
  551. self.old_umask = os.umask(self.umask)
  552. self.storage_dir = tempfile.mkdtemp()
  553. def tearDown(self):
  554. shutil.rmtree(self.storage_dir)
  555. os.umask(self.old_umask)
  556. @override_settings(FILE_UPLOAD_PERMISSIONS=0o654)
  557. def test_file_upload_permissions(self):
  558. self.storage = FileSystemStorage(self.storage_dir)
  559. name = self.storage.save("the_file", ContentFile("data"))
  560. actual_mode = os.stat(self.storage.path(name))[0] & 0o777
  561. self.assertEqual(actual_mode, 0o654)
  562. @override_settings(FILE_UPLOAD_PERMISSIONS=None)
  563. def test_file_upload_default_permissions(self):
  564. self.storage = FileSystemStorage(self.storage_dir)
  565. fname = self.storage.save("some_file", ContentFile("data"))
  566. mode = os.stat(self.storage.path(fname))[0] & 0o777
  567. self.assertEqual(mode, 0o666 & ~self.umask)
  568. @override_settings(FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765)
  569. def test_file_upload_directory_permissions(self):
  570. self.storage = FileSystemStorage(self.storage_dir)
  571. name = self.storage.save("the_directory/the_file", ContentFile("data"))
  572. dir_mode = os.stat(os.path.dirname(self.storage.path(name)))[0] & 0o777
  573. self.assertEqual(dir_mode, 0o765)
  574. @override_settings(FILE_UPLOAD_DIRECTORY_PERMISSIONS=None)
  575. def test_file_upload_directory_default_permissions(self):
  576. self.storage = FileSystemStorage(self.storage_dir)
  577. name = self.storage.save("the_directory/the_file", ContentFile("data"))
  578. dir_mode = os.stat(os.path.dirname(self.storage.path(name)))[0] & 0o777
  579. self.assertEqual(dir_mode, 0o777 & ~self.umask)
  580. class FileStoragePathParsing(unittest.TestCase):
  581. def setUp(self):
  582. self.storage_dir = tempfile.mkdtemp()
  583. self.storage = FileSystemStorage(self.storage_dir)
  584. def tearDown(self):
  585. shutil.rmtree(self.storage_dir)
  586. def test_directory_with_dot(self):
  587. """Regression test for #9610.
  588. If the directory name contains a dot and the file name doesn't, make
  589. sure we still mangle the file name instead of the directory name.
  590. """
  591. self.storage.save('dotted.path/test', ContentFile("1"))
  592. self.storage.save('dotted.path/test', ContentFile("2"))
  593. files = sorted(os.listdir(os.path.join(self.storage_dir, 'dotted.path')))
  594. self.assertFalse(os.path.exists(os.path.join(self.storage_dir, 'dotted_.path')))
  595. self.assertEqual(files[0], 'test')
  596. six.assertRegex(self, files[1], 'test_%s' % FILE_SUFFIX_REGEX)
  597. def test_first_character_dot(self):
  598. """
  599. File names with a dot as their first character don't have an extension,
  600. and the underscore should get added to the end.
  601. """
  602. self.storage.save('dotted.path/.test', ContentFile("1"))
  603. self.storage.save('dotted.path/.test', ContentFile("2"))
  604. files = sorted(os.listdir(os.path.join(self.storage_dir, 'dotted.path')))
  605. self.assertFalse(os.path.exists(os.path.join(self.storage_dir, 'dotted_.path')))
  606. self.assertEqual(files[0], '.test')
  607. six.assertRegex(self, files[1], '.test_%s' % FILE_SUFFIX_REGEX)
  608. class ContentFileStorageTestCase(unittest.TestCase):
  609. def setUp(self):
  610. self.storage_dir = tempfile.mkdtemp()
  611. self.storage = FileSystemStorage(self.storage_dir)
  612. def tearDown(self):
  613. shutil.rmtree(self.storage_dir)
  614. def test_content_saving(self):
  615. """
  616. Test that ContentFile can be saved correctly with the filesystem storage,
  617. both if it was initialized with string or unicode content"""
  618. self.storage.save('bytes.txt', ContentFile(b"content"))
  619. self.storage.save('unicode.txt', ContentFile("español"))
  620. @override_settings(ROOT_URLCONF='file_storage.urls')
  621. class FileLikeObjectTestCase(LiveServerTestCase):
  622. """
  623. Test file-like objects (#15644).
  624. """
  625. available_apps = []
  626. def setUp(self):
  627. self.temp_dir = tempfile.mkdtemp()
  628. self.storage = FileSystemStorage(location=self.temp_dir)
  629. def tearDown(self):
  630. shutil.rmtree(self.temp_dir)
  631. def test_urllib2_urlopen(self):
  632. """
  633. Test the File storage API with a file like object coming from urllib2.urlopen()
  634. """
  635. file_like_object = urlopen(self.live_server_url + '/')
  636. f = File(file_like_object)
  637. stored_filename = self.storage.save("remote_file.html", f)
  638. remote_file = urlopen(self.live_server_url + '/')
  639. with self.storage.open(stored_filename) as stored_file:
  640. self.assertEqual(stored_file.read(), remote_file.read())