tests.py 21 KB

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