tests.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. # -*- coding: utf-8 -*-
  2. from __future__ import absolute_import, unicode_literals
  3. import errno
  4. import os
  5. import shutil
  6. import tempfile
  7. import time
  8. from datetime import datetime, timedelta
  9. from io import BytesIO
  10. try:
  11. import threading
  12. except ImportError:
  13. import dummy_threading as threading
  14. from django.conf import settings
  15. from django.core.exceptions import SuspiciousOperation, ImproperlyConfigured
  16. from django.core.files.base import File, ContentFile
  17. from django.core.files.images import get_image_dimensions
  18. from django.core.files.storage import FileSystemStorage, get_storage_class
  19. from django.core.files.uploadedfile import UploadedFile
  20. from django.test import SimpleTestCase
  21. from django.utils import six
  22. from django.utils import unittest
  23. from ..servers.tests import LiveServerBase
  24. # Try to import PIL in either of the two ways it can end up installed.
  25. # Checking for the existence of Image is enough for CPython, but
  26. # for PyPy, you need to check for the underlying modules
  27. try:
  28. from PIL import Image, _imaging
  29. except ImportError:
  30. try:
  31. import Image, _imaging
  32. except ImportError:
  33. Image = None
  34. class GetStorageClassTests(SimpleTestCase):
  35. def test_get_filesystem_storage(self):
  36. """
  37. get_storage_class returns the class for a storage backend name/path.
  38. """
  39. self.assertEqual(
  40. get_storage_class('django.core.files.storage.FileSystemStorage'),
  41. FileSystemStorage)
  42. def test_get_invalid_storage_module(self):
  43. """
  44. get_storage_class raises an error if the requested import don't exist.
  45. """
  46. self.assertRaisesMessage(
  47. ImproperlyConfigured,
  48. "NonExistingStorage isn't a storage module.",
  49. get_storage_class,
  50. 'NonExistingStorage')
  51. def test_get_nonexisting_storage_class(self):
  52. """
  53. get_storage_class raises an error if the requested class don't exist.
  54. """
  55. self.assertRaisesMessage(
  56. ImproperlyConfigured,
  57. 'Storage module "django.core.files.storage" does not define a '\
  58. '"NonExistingStorage" class.',
  59. get_storage_class,
  60. 'django.core.files.storage.NonExistingStorage')
  61. def test_get_nonexisting_storage_module(self):
  62. """
  63. get_storage_class raises an error if the requested module don't exist.
  64. """
  65. # Error message may or may not be the fully qualified path.
  66. self.assertRaisesRegexp(
  67. ImproperlyConfigured,
  68. ('Error importing storage module django.core.files.non_existing_'
  69. 'storage: "No module named .*non_existing_storage"'),
  70. get_storage_class,
  71. 'django.core.files.non_existing_storage.NonExistingStorage'
  72. )
  73. class FileStorageTests(unittest.TestCase):
  74. storage_class = FileSystemStorage
  75. def setUp(self):
  76. self.temp_dir = tempfile.mkdtemp()
  77. self.storage = self.storage_class(location=self.temp_dir,
  78. base_url='/test_media_url/')
  79. # Set up a second temporary directory which is ensured to have a mixed
  80. # case name.
  81. self.temp_dir2 = tempfile.mkdtemp(suffix='aBc')
  82. def tearDown(self):
  83. shutil.rmtree(self.temp_dir)
  84. shutil.rmtree(self.temp_dir2)
  85. def test_emtpy_location(self):
  86. """
  87. Makes sure an exception is raised if the location is empty
  88. """
  89. storage = self.storage_class(location='')
  90. self.assertEqual(storage.base_location, '')
  91. self.assertEqual(storage.location, os.getcwd())
  92. def test_file_access_options(self):
  93. """
  94. Standard file access options are available, and work as expected.
  95. """
  96. self.assertFalse(self.storage.exists('storage_test'))
  97. f = self.storage.open('storage_test', 'w')
  98. f.write('storage contents')
  99. f.close()
  100. self.assertTrue(self.storage.exists('storage_test'))
  101. f = self.storage.open('storage_test', 'r')
  102. self.assertEqual(f.read(), 'storage contents')
  103. f.close()
  104. self.storage.delete('storage_test')
  105. self.assertFalse(self.storage.exists('storage_test'))
  106. def test_file_accessed_time(self):
  107. """
  108. File storage returns a Datetime object for the last accessed time of
  109. a file.
  110. """
  111. self.assertFalse(self.storage.exists('test.file'))
  112. f = ContentFile(b'custom contents')
  113. f_name = self.storage.save('test.file', f)
  114. atime = self.storage.accessed_time(f_name)
  115. self.assertEqual(atime, datetime.fromtimestamp(
  116. os.path.getatime(self.storage.path(f_name))))
  117. self.assertTrue(datetime.now() - self.storage.accessed_time(f_name) < timedelta(seconds=2))
  118. self.storage.delete(f_name)
  119. def test_file_created_time(self):
  120. """
  121. File storage returns a Datetime object for the creation time of
  122. a file.
  123. """
  124. self.assertFalse(self.storage.exists('test.file'))
  125. f = ContentFile(b'custom contents')
  126. f_name = self.storage.save('test.file', f)
  127. ctime = self.storage.created_time(f_name)
  128. self.assertEqual(ctime, datetime.fromtimestamp(
  129. os.path.getctime(self.storage.path(f_name))))
  130. self.assertTrue(datetime.now() - self.storage.created_time(f_name) < timedelta(seconds=2))
  131. self.storage.delete(f_name)
  132. def test_file_modified_time(self):
  133. """
  134. File storage returns a Datetime object for the last modified time of
  135. a file.
  136. """
  137. self.assertFalse(self.storage.exists('test.file'))
  138. f = ContentFile(b'custom contents')
  139. f_name = self.storage.save('test.file', f)
  140. mtime = self.storage.modified_time(f_name)
  141. self.assertEqual(mtime, datetime.fromtimestamp(
  142. os.path.getmtime(self.storage.path(f_name))))
  143. self.assertTrue(datetime.now() - self.storage.modified_time(f_name) < timedelta(seconds=2))
  144. self.storage.delete(f_name)
  145. def test_file_save_without_name(self):
  146. """
  147. File storage extracts the filename from the content object if no
  148. name is given explicitly.
  149. """
  150. self.assertFalse(self.storage.exists('test.file'))
  151. f = ContentFile(b'custom contents')
  152. f.name = 'test.file'
  153. storage_f_name = self.storage.save(None, f)
  154. self.assertEqual(storage_f_name, f.name)
  155. self.assertTrue(os.path.exists(os.path.join(self.temp_dir, f.name)))
  156. self.storage.delete(storage_f_name)
  157. def test_file_save_with_path(self):
  158. """
  159. Saving a pathname should create intermediate directories as necessary.
  160. """
  161. self.assertFalse(self.storage.exists('path/to'))
  162. self.storage.save('path/to/test.file',
  163. ContentFile(b'file saved with path'))
  164. self.assertTrue(self.storage.exists('path/to'))
  165. with self.storage.open('path/to/test.file') as f:
  166. self.assertEqual(f.read(), b'file saved with path')
  167. self.assertTrue(os.path.exists(
  168. os.path.join(self.temp_dir, 'path', 'to', 'test.file')))
  169. self.storage.delete('path/to/test.file')
  170. def test_file_path(self):
  171. """
  172. File storage returns the full path of a file
  173. """
  174. self.assertFalse(self.storage.exists('test.file'))
  175. f = ContentFile(b'custom contents')
  176. f_name = self.storage.save('test.file', f)
  177. self.assertEqual(self.storage.path(f_name),
  178. os.path.join(self.temp_dir, f_name))
  179. self.storage.delete(f_name)
  180. def test_file_url(self):
  181. """
  182. File storage returns a url to access a given file from the Web.
  183. """
  184. self.assertEqual(self.storage.url('test.file'),
  185. '%s%s' % (self.storage.base_url, 'test.file'))
  186. # should encode special chars except ~!*()'
  187. # like encodeURIComponent() JavaScript function do
  188. self.assertEqual(self.storage.url(r"""~!*()'@#$%^&*abc`+ =.file"""),
  189. """/test_media_url/~!*()'%40%23%24%25%5E%26*abc%60%2B%20%3D.file""")
  190. # should stanslate os path separator(s) to the url path separator
  191. self.assertEqual(self.storage.url("""a/b\\c.file"""),
  192. """/test_media_url/a/b/c.file""")
  193. self.storage.base_url = None
  194. self.assertRaises(ValueError, self.storage.url, 'test.file')
  195. def test_listdir(self):
  196. """
  197. File storage returns a tuple containing directories and files.
  198. """
  199. self.assertFalse(self.storage.exists('storage_test_1'))
  200. self.assertFalse(self.storage.exists('storage_test_2'))
  201. self.assertFalse(self.storage.exists('storage_dir_1'))
  202. f = self.storage.save('storage_test_1', ContentFile(b'custom content'))
  203. f = self.storage.save('storage_test_2', ContentFile(b'custom content'))
  204. os.mkdir(os.path.join(self.temp_dir, 'storage_dir_1'))
  205. dirs, files = self.storage.listdir('')
  206. self.assertEqual(set(dirs), set(['storage_dir_1']))
  207. self.assertEqual(set(files),
  208. set(['storage_test_1', 'storage_test_2']))
  209. self.storage.delete('storage_test_1')
  210. self.storage.delete('storage_test_2')
  211. os.rmdir(os.path.join(self.temp_dir, 'storage_dir_1'))
  212. def test_file_storage_prevents_directory_traversal(self):
  213. """
  214. File storage prevents directory traversal (files can only be accessed if
  215. they're below the storage location).
  216. """
  217. self.assertRaises(SuspiciousOperation, self.storage.exists, '..')
  218. self.assertRaises(SuspiciousOperation, self.storage.exists, '/etc/passwd')
  219. def test_file_storage_preserves_filename_case(self):
  220. """The storage backend should preserve case of filenames."""
  221. # Create a storage backend associated with the mixed case name
  222. # directory.
  223. temp_storage = self.storage_class(location=self.temp_dir2)
  224. # Ask that storage backend to store a file with a mixed case filename.
  225. mixed_case = 'CaSe_SeNsItIvE'
  226. file = temp_storage.open(mixed_case, 'w')
  227. file.write('storage contents')
  228. file.close()
  229. self.assertEqual(os.path.join(self.temp_dir2, mixed_case),
  230. temp_storage.path(mixed_case))
  231. temp_storage.delete(mixed_case)
  232. def test_makedirs_race_handling(self):
  233. """
  234. File storage should be robust against directory creation race conditions.
  235. """
  236. real_makedirs = os.makedirs
  237. # Monkey-patch os.makedirs, to simulate a normal call, a raced call,
  238. # and an error.
  239. def fake_makedirs(path):
  240. if path == os.path.join(self.temp_dir, 'normal'):
  241. real_makedirs(path)
  242. elif path == os.path.join(self.temp_dir, 'raced'):
  243. real_makedirs(path)
  244. raise OSError(errno.EEXIST, 'simulated EEXIST')
  245. elif path == os.path.join(self.temp_dir, 'error'):
  246. raise OSError(errno.EACCES, 'simulated EACCES')
  247. else:
  248. self.fail('unexpected argument %r' % path)
  249. try:
  250. os.makedirs = fake_makedirs
  251. self.storage.save('normal/test.file',
  252. ContentFile(b'saved normally'))
  253. with self.storage.open('normal/test.file') as f:
  254. self.assertEqual(f.read(), b'saved normally')
  255. self.storage.save('raced/test.file',
  256. ContentFile(b'saved with race'))
  257. with self.storage.open('raced/test.file') as f:
  258. self.assertEqual(f.read(), b'saved with race')
  259. # Check that OSErrors aside from EEXIST are still raised.
  260. self.assertRaises(OSError,
  261. self.storage.save, 'error/test.file', ContentFile(b'not saved'))
  262. finally:
  263. os.makedirs = real_makedirs
  264. def test_remove_race_handling(self):
  265. """
  266. File storage should be robust against file removal race conditions.
  267. """
  268. real_remove = os.remove
  269. # Monkey-patch os.remove, to simulate a normal call, a raced call,
  270. # and an error.
  271. def fake_remove(path):
  272. if path == os.path.join(self.temp_dir, 'normal.file'):
  273. real_remove(path)
  274. elif path == os.path.join(self.temp_dir, 'raced.file'):
  275. real_remove(path)
  276. raise OSError(errno.ENOENT, 'simulated ENOENT')
  277. elif path == os.path.join(self.temp_dir, 'error.file'):
  278. raise OSError(errno.EACCES, 'simulated EACCES')
  279. else:
  280. self.fail('unexpected argument %r' % path)
  281. try:
  282. os.remove = fake_remove
  283. self.storage.save('normal.file', ContentFile(b'delete normally'))
  284. self.storage.delete('normal.file')
  285. self.assertFalse(self.storage.exists('normal.file'))
  286. self.storage.save('raced.file', ContentFile(b'delete with race'))
  287. self.storage.delete('raced.file')
  288. self.assertFalse(self.storage.exists('normal.file'))
  289. # Check that OSErrors aside from ENOENT are still raised.
  290. self.storage.save('error.file', ContentFile(b'delete with error'))
  291. self.assertRaises(OSError, self.storage.delete, 'error.file')
  292. finally:
  293. os.remove = real_remove
  294. class CustomStorage(FileSystemStorage):
  295. def get_available_name(self, name):
  296. """
  297. Append numbers to duplicate files rather than underscores, like Trac.
  298. """
  299. parts = name.split('.')
  300. basename, ext = parts[0], parts[1:]
  301. number = 2
  302. while self.exists(name):
  303. name = '.'.join([basename, str(number)] + ext)
  304. number += 1
  305. return name
  306. class CustomStorageTests(FileStorageTests):
  307. storage_class = CustomStorage
  308. def test_custom_get_available_name(self):
  309. first = self.storage.save('custom_storage', ContentFile(b'custom contents'))
  310. self.assertEqual(first, 'custom_storage')
  311. second = self.storage.save('custom_storage', ContentFile(b'more contents'))
  312. self.assertEqual(second, 'custom_storage.2')
  313. self.storage.delete(first)
  314. self.storage.delete(second)
  315. class UnicodeFileNameTests(unittest.TestCase):
  316. def test_unicode_file_names(self):
  317. """
  318. Regression test for #8156: files with unicode names I can't quite figure
  319. out the encoding situation between doctest and this file, but the actual
  320. repr doesn't matter; it just shouldn't return a unicode object.
  321. """
  322. uf = UploadedFile(name='¿Cómo?',content_type='text')
  323. self.assertEqual(type(uf.__repr__()), str)
  324. # Tests for a race condition on file saving (#4948).
  325. # This is written in such a way that it'll always pass on platforms
  326. # without threading.
  327. class SlowFile(ContentFile):
  328. def chunks(self):
  329. time.sleep(1)
  330. return super(ContentFile, self).chunks()
  331. class FileSaveRaceConditionTest(unittest.TestCase):
  332. def setUp(self):
  333. self.storage_dir = tempfile.mkdtemp()
  334. self.storage = FileSystemStorage(self.storage_dir)
  335. self.thread = threading.Thread(target=self.save_file, args=['conflict'])
  336. def tearDown(self):
  337. shutil.rmtree(self.storage_dir)
  338. def save_file(self, name):
  339. name = self.storage.save(name, SlowFile(b"Data"))
  340. def test_race_condition(self):
  341. self.thread.start()
  342. name = self.save_file('conflict')
  343. self.thread.join()
  344. self.assertTrue(self.storage.exists('conflict'))
  345. self.assertTrue(self.storage.exists('conflict_1'))
  346. self.storage.delete('conflict')
  347. self.storage.delete('conflict_1')
  348. class FileStoragePermissions(unittest.TestCase):
  349. def setUp(self):
  350. self.old_perms = settings.FILE_UPLOAD_PERMISSIONS
  351. settings.FILE_UPLOAD_PERMISSIONS = 0o666
  352. self.storage_dir = tempfile.mkdtemp()
  353. self.storage = FileSystemStorage(self.storage_dir)
  354. def tearDown(self):
  355. settings.FILE_UPLOAD_PERMISSIONS = self.old_perms
  356. shutil.rmtree(self.storage_dir)
  357. def test_file_upload_permissions(self):
  358. name = self.storage.save("the_file", ContentFile(b"data"))
  359. actual_mode = os.stat(self.storage.path(name))[0] & 0o777
  360. self.assertEqual(actual_mode, 0o666)
  361. class FileStoragePathParsing(unittest.TestCase):
  362. def setUp(self):
  363. self.storage_dir = tempfile.mkdtemp()
  364. self.storage = FileSystemStorage(self.storage_dir)
  365. def tearDown(self):
  366. shutil.rmtree(self.storage_dir)
  367. def test_directory_with_dot(self):
  368. """Regression test for #9610.
  369. If the directory name contains a dot and the file name doesn't, make
  370. sure we still mangle the file name instead of the directory name.
  371. """
  372. self.storage.save('dotted.path/test', ContentFile(b"1"))
  373. self.storage.save('dotted.path/test', ContentFile(b"2"))
  374. self.assertFalse(os.path.exists(os.path.join(self.storage_dir, 'dotted_.path')))
  375. self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test')))
  376. self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test_1')))
  377. def test_first_character_dot(self):
  378. """
  379. File names with a dot as their first character don't have an extension,
  380. and the underscore should get added to the end.
  381. """
  382. self.storage.save('dotted.path/.test', ContentFile(b"1"))
  383. self.storage.save('dotted.path/.test', ContentFile(b"2"))
  384. self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test')))
  385. self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test_1')))
  386. class DimensionClosingBug(unittest.TestCase):
  387. """
  388. Test that get_image_dimensions() properly closes files (#8817)
  389. """
  390. @unittest.skipUnless(Image, "PIL not installed")
  391. def test_not_closing_of_files(self):
  392. """
  393. Open files passed into get_image_dimensions() should stay opened.
  394. """
  395. empty_io = BytesIO()
  396. try:
  397. get_image_dimensions(empty_io)
  398. finally:
  399. self.assertTrue(not empty_io.closed)
  400. @unittest.skipUnless(Image, "PIL not installed")
  401. def test_closing_of_filenames(self):
  402. """
  403. get_image_dimensions() called with a filename should closed the file.
  404. """
  405. # We need to inject a modified open() builtin into the images module
  406. # that checks if the file was closed properly if the function is
  407. # called with a filename instead of an file object.
  408. # get_image_dimensions will call our catching_open instead of the
  409. # regular builtin one.
  410. class FileWrapper(object):
  411. _closed = []
  412. def __init__(self, f):
  413. self.f = f
  414. def __getattr__(self, name):
  415. return getattr(self.f, name)
  416. def close(self):
  417. self._closed.append(True)
  418. self.f.close()
  419. def catching_open(*args):
  420. return FileWrapper(open(*args))
  421. from django.core.files import images
  422. images.open = catching_open
  423. try:
  424. get_image_dimensions(os.path.join(os.path.dirname(__file__), "test1.png"))
  425. finally:
  426. del images.open
  427. self.assertTrue(FileWrapper._closed)
  428. class InconsistentGetImageDimensionsBug(unittest.TestCase):
  429. """
  430. Test that get_image_dimensions() works properly after various calls
  431. using a file handler (#11158)
  432. """
  433. @unittest.skipUnless(Image, "PIL not installed")
  434. def test_multiple_calls(self):
  435. """
  436. Multiple calls of get_image_dimensions() should return the same size.
  437. """
  438. from django.core.files.images import ImageFile
  439. img_path = os.path.join(os.path.dirname(__file__), "test.png")
  440. image = ImageFile(open(img_path, 'rb'))
  441. image_pil = Image.open(img_path)
  442. size_1, size_2 = get_image_dimensions(image), get_image_dimensions(image)
  443. self.assertEqual(image_pil.size, size_1)
  444. self.assertEqual(size_1, size_2)
  445. class ContentFileTestCase(unittest.TestCase):
  446. def test_content_file_default_name(self):
  447. self.assertEqual(ContentFile(b"content").name, None)
  448. def test_content_file_custom_name(self):
  449. """
  450. Test that the constructor of ContentFile accepts 'name' (#16590).
  451. """
  452. name = "I can have a name too!"
  453. self.assertEqual(ContentFile(b"content", name=name).name, name)
  454. def test_content_file_input_type(self):
  455. """
  456. Test that ContentFile can accept both bytes and unicode and that the
  457. retrieved content is of the same type.
  458. """
  459. self.assertTrue(isinstance(ContentFile(b"content").read(), bytes))
  460. self.assertTrue(isinstance(ContentFile("español").read(), six.text_type))
  461. class NoNameFileTestCase(unittest.TestCase):
  462. """
  463. Other examples of unnamed files may be tempfile.SpooledTemporaryFile or
  464. urllib.urlopen()
  465. """
  466. def test_noname_file_default_name(self):
  467. self.assertEqual(File(BytesIO(b'A file with no name')).name, None)
  468. def test_noname_file_get_size(self):
  469. self.assertEqual(File(BytesIO(b'A file with no name')).size, 19)
  470. class FileLikeObjectTestCase(LiveServerBase):
  471. """
  472. Test file-like objects (#15644).
  473. """
  474. def setUp(self):
  475. self.temp_dir = tempfile.mkdtemp()
  476. self.storage = FileSystemStorage(location=self.temp_dir)
  477. def tearDown(self):
  478. shutil.rmtree(self.temp_dir)
  479. def test_urllib2_urlopen(self):
  480. """
  481. Test the File storage API with a file like object coming from urllib2.urlopen()
  482. """
  483. file_like_object = self.urlopen('/example_view/')
  484. f = File(file_like_object)
  485. stored_filename = self.storage.save("remote_file.html", f)
  486. stored_file = self.storage.open(stored_filename)
  487. remote_file = self.urlopen('/example_view/')
  488. self.assertEqual(stored_file.read(), remote_file.read())