tests.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. # -*- coding: utf-8 -*-
  2. import os
  3. import shutil
  4. import sys
  5. import tempfile
  6. import time
  7. from datetime import datetime, timedelta
  8. try:
  9. from cStringIO import StringIO
  10. except ImportError:
  11. from StringIO import StringIO
  12. try:
  13. import threading
  14. except ImportError:
  15. import dummy_threading as threading
  16. from django.conf import settings
  17. from django.core.exceptions import SuspiciousOperation, ImproperlyConfigured
  18. from django.core.files.base import ContentFile, File
  19. from django.core.files.images import get_image_dimensions
  20. from django.core.files.storage import FileSystemStorage, get_storage_class
  21. from django.core.files.uploadedfile import UploadedFile
  22. from django.utils import unittest
  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(unittest.TestCase):
  34. def assertRaisesErrorWithMessage(self, error, message, callable,
  35. *args, **kwargs):
  36. self.assertRaises(error, callable, *args, **kwargs)
  37. try:
  38. callable(*args, **kwargs)
  39. except error, e:
  40. self.assertEqual(message, str(e))
  41. def test_get_filesystem_storage(self):
  42. """
  43. get_storage_class returns the class for a storage backend name/path.
  44. """
  45. self.assertEqual(
  46. get_storage_class('django.core.files.storage.FileSystemStorage'),
  47. FileSystemStorage)
  48. def test_get_invalid_storage_module(self):
  49. """
  50. get_storage_class raises an error if the requested import don't exist.
  51. """
  52. self.assertRaisesErrorWithMessage(
  53. ImproperlyConfigured,
  54. "NonExistingStorage isn't a storage module.",
  55. get_storage_class,
  56. 'NonExistingStorage')
  57. def test_get_nonexisting_storage_class(self):
  58. """
  59. get_storage_class raises an error if the requested class don't exist.
  60. """
  61. self.assertRaisesErrorWithMessage(
  62. ImproperlyConfigured,
  63. 'Storage module "django.core.files.storage" does not define a '\
  64. '"NonExistingStorage" class.',
  65. get_storage_class,
  66. 'django.core.files.storage.NonExistingStorage')
  67. def test_get_nonexisting_storage_module(self):
  68. """
  69. get_storage_class raises an error if the requested module don't exist.
  70. """
  71. # Error message may or may not be the fully qualified path.
  72. self.assertRaisesRegexp(
  73. ImproperlyConfigured,
  74. ('Error importing storage module django.core.files.non_existing_'
  75. 'storage: "No module named .*non_existing_storage"'),
  76. get_storage_class,
  77. 'django.core.files.non_existing_storage.NonExistingStorage'
  78. )
  79. class FileStorageTests(unittest.TestCase):
  80. storage_class = FileSystemStorage
  81. def setUp(self):
  82. self.temp_dir = tempfile.mkdtemp()
  83. self.storage = self.storage_class(location=self.temp_dir,
  84. base_url='/test_media_url/')
  85. # Set up a second temporary directory which is ensured to have a mixed
  86. # case name.
  87. self.temp_dir2 = tempfile.mkdtemp(suffix='aBc')
  88. def tearDown(self):
  89. shutil.rmtree(self.temp_dir)
  90. shutil.rmtree(self.temp_dir2)
  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_path(self):
  157. """
  158. File storage returns the full path of a file
  159. """
  160. self.assertFalse(self.storage.exists('test.file'))
  161. f = ContentFile('custom contents')
  162. f_name = self.storage.save('test.file', f)
  163. self.assertEqual(self.storage.path(f_name),
  164. os.path.join(self.temp_dir, f_name))
  165. self.storage.delete(f_name)
  166. def test_file_url(self):
  167. """
  168. File storage returns a url to access a given file from the Web.
  169. """
  170. self.assertEqual(self.storage.url('test.file'),
  171. '%s%s' % (self.storage.base_url, 'test.file'))
  172. # should encode special chars except ~!*()'
  173. # like encodeURIComponent() JavaScript function do
  174. self.assertEqual(self.storage.url(r"""~!*()'@#$%^&*abc`+=.file"""),
  175. """/test_media_url/~!*()'%40%23%24%25%5E%26*abc%60%2B%3D.file""")
  176. # should stanslate os path separator(s) to the url path separator
  177. self.assertEqual(self.storage.url("""a/b\\c.file"""),
  178. """/test_media_url/a/b/c.file""")
  179. self.storage.base_url = None
  180. self.assertRaises(ValueError, self.storage.url, 'test.file')
  181. def test_file_with_mixin(self):
  182. """
  183. File storage can get a mixin to extend the functionality of the
  184. returned file.
  185. """
  186. self.assertFalse(self.storage.exists('test.file'))
  187. class TestFileMixin(object):
  188. mixed_in = True
  189. f = ContentFile('custom contents')
  190. f_name = self.storage.save('test.file', f)
  191. self.assertTrue(isinstance(
  192. self.storage.open('test.file', mixin=TestFileMixin),
  193. TestFileMixin
  194. ))
  195. self.storage.delete('test.file')
  196. def test_listdir(self):
  197. """
  198. File storage returns a tuple containing directories and files.
  199. """
  200. self.assertFalse(self.storage.exists('storage_test_1'))
  201. self.assertFalse(self.storage.exists('storage_test_2'))
  202. self.assertFalse(self.storage.exists('storage_dir_1'))
  203. f = self.storage.save('storage_test_1', ContentFile('custom content'))
  204. f = self.storage.save('storage_test_2', ContentFile('custom content'))
  205. os.mkdir(os.path.join(self.temp_dir, 'storage_dir_1'))
  206. dirs, files = self.storage.listdir('')
  207. self.assertEqual(set(dirs), set([u'storage_dir_1']))
  208. self.assertEqual(set(files),
  209. set([u'storage_test_1', u'storage_test_2']))
  210. self.storage.delete('storage_test_1')
  211. self.storage.delete('storage_test_2')
  212. os.rmdir(os.path.join(self.temp_dir, 'storage_dir_1'))
  213. def test_file_storage_prevents_directory_traversal(self):
  214. """
  215. File storage prevents directory traversal (files can only be accessed if
  216. they're below the storage location).
  217. """
  218. self.assertRaises(SuspiciousOperation, self.storage.exists, '..')
  219. self.assertRaises(SuspiciousOperation, self.storage.exists, '/etc/passwd')
  220. def test_file_storage_preserves_filename_case(self):
  221. """The storage backend should preserve case of filenames."""
  222. # Create a storage backend associated with the mixed case name
  223. # directory.
  224. temp_storage = self.storage_class(location=self.temp_dir2)
  225. # Ask that storage backend to store a file with a mixed case filename.
  226. mixed_case = 'CaSe_SeNsItIvE'
  227. file = temp_storage.open(mixed_case, 'w')
  228. file.write('storage contents')
  229. file.close()
  230. self.assertEqual(os.path.join(self.temp_dir2, mixed_case),
  231. temp_storage.path(mixed_case))
  232. temp_storage.delete(mixed_case)
  233. class CustomStorage(FileSystemStorage):
  234. def get_available_name(self, name):
  235. """
  236. Append numbers to duplicate files rather than underscores, like Trac.
  237. """
  238. parts = name.split('.')
  239. basename, ext = parts[0], parts[1:]
  240. number = 2
  241. while self.exists(name):
  242. name = '.'.join([basename, str(number)] + ext)
  243. number += 1
  244. return name
  245. class CustomStorageTests(FileStorageTests):
  246. storage_class = CustomStorage
  247. def test_custom_get_available_name(self):
  248. first = self.storage.save('custom_storage', ContentFile('custom contents'))
  249. self.assertEqual(first, 'custom_storage')
  250. second = self.storage.save('custom_storage', ContentFile('more contents'))
  251. self.assertEqual(second, 'custom_storage.2')
  252. self.storage.delete(first)
  253. self.storage.delete(second)
  254. class UnicodeFileNameTests(unittest.TestCase):
  255. def test_unicode_file_names(self):
  256. """
  257. Regression test for #8156: files with unicode names I can't quite figure
  258. out the encoding situation between doctest and this file, but the actual
  259. repr doesn't matter; it just shouldn't return a unicode object.
  260. """
  261. uf = UploadedFile(name=u'¿Cómo?',content_type='text')
  262. self.assertEqual(type(uf.__repr__()), str)
  263. # Tests for a race condition on file saving (#4948).
  264. # This is written in such a way that it'll always pass on platforms
  265. # without threading.
  266. class SlowFile(ContentFile):
  267. def chunks(self):
  268. time.sleep(1)
  269. return super(ContentFile, self).chunks()
  270. class FileSaveRaceConditionTest(unittest.TestCase):
  271. def setUp(self):
  272. self.storage_dir = tempfile.mkdtemp()
  273. self.storage = FileSystemStorage(self.storage_dir)
  274. self.thread = threading.Thread(target=self.save_file, args=['conflict'])
  275. def tearDown(self):
  276. shutil.rmtree(self.storage_dir)
  277. def save_file(self, name):
  278. name = self.storage.save(name, SlowFile("Data"))
  279. def test_race_condition(self):
  280. self.thread.start()
  281. name = self.save_file('conflict')
  282. self.thread.join()
  283. self.assertTrue(self.storage.exists('conflict'))
  284. self.assertTrue(self.storage.exists('conflict_1'))
  285. self.storage.delete('conflict')
  286. self.storage.delete('conflict_1')
  287. class FileStoragePermissions(unittest.TestCase):
  288. def setUp(self):
  289. self.old_perms = settings.FILE_UPLOAD_PERMISSIONS
  290. settings.FILE_UPLOAD_PERMISSIONS = 0666
  291. self.storage_dir = tempfile.mkdtemp()
  292. self.storage = FileSystemStorage(self.storage_dir)
  293. def tearDown(self):
  294. settings.FILE_UPLOAD_PERMISSIONS = self.old_perms
  295. shutil.rmtree(self.storage_dir)
  296. def test_file_upload_permissions(self):
  297. name = self.storage.save("the_file", ContentFile("data"))
  298. actual_mode = os.stat(self.storage.path(name))[0] & 0777
  299. self.assertEqual(actual_mode, 0666)
  300. class FileStoragePathParsing(unittest.TestCase):
  301. def setUp(self):
  302. self.storage_dir = tempfile.mkdtemp()
  303. self.storage = FileSystemStorage(self.storage_dir)
  304. def tearDown(self):
  305. shutil.rmtree(self.storage_dir)
  306. def test_directory_with_dot(self):
  307. """Regression test for #9610.
  308. If the directory name contains a dot and the file name doesn't, make
  309. sure we still mangle the file name instead of the directory name.
  310. """
  311. self.storage.save('dotted.path/test', ContentFile("1"))
  312. self.storage.save('dotted.path/test', ContentFile("2"))
  313. self.assertFalse(os.path.exists(os.path.join(self.storage_dir, 'dotted_.path')))
  314. self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test')))
  315. self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test_1')))
  316. def test_first_character_dot(self):
  317. """
  318. File names with a dot as their first character don't have an extension,
  319. and the underscore should get added to the end.
  320. """
  321. self.storage.save('dotted.path/.test', ContentFile("1"))
  322. self.storage.save('dotted.path/.test', ContentFile("2"))
  323. self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test')))
  324. # Before 2.6, a leading dot was treated as an extension, and so
  325. # underscore gets added to beginning instead of end.
  326. if sys.version_info < (2, 6):
  327. self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/_1.test')))
  328. else:
  329. self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test_1')))
  330. class DimensionClosingBug(unittest.TestCase):
  331. """
  332. Test that get_image_dimensions() properly closes files (#8817)
  333. """
  334. @unittest.skipUnless(Image, "PIL not installed")
  335. def test_not_closing_of_files(self):
  336. """
  337. Open files passed into get_image_dimensions() should stay opened.
  338. """
  339. empty_io = StringIO()
  340. try:
  341. get_image_dimensions(empty_io)
  342. finally:
  343. self.assertTrue(not empty_io.closed)
  344. @unittest.skipUnless(Image, "PIL not installed")
  345. def test_closing_of_filenames(self):
  346. """
  347. get_image_dimensions() called with a filename should closed the file.
  348. """
  349. # We need to inject a modified open() builtin into the images module
  350. # that checks if the file was closed properly if the function is
  351. # called with a filename instead of an file object.
  352. # get_image_dimensions will call our catching_open instead of the
  353. # regular builtin one.
  354. class FileWrapper(object):
  355. _closed = []
  356. def __init__(self, f):
  357. self.f = f
  358. def __getattr__(self, name):
  359. return getattr(self.f, name)
  360. def close(self):
  361. self._closed.append(True)
  362. self.f.close()
  363. def catching_open(*args):
  364. return FileWrapper(open(*args))
  365. from django.core.files import images
  366. images.open = catching_open
  367. try:
  368. get_image_dimensions(os.path.join(os.path.dirname(__file__), "test1.png"))
  369. finally:
  370. del images.open
  371. self.assertTrue(FileWrapper._closed)
  372. class InconsistentGetImageDimensionsBug(unittest.TestCase):
  373. """
  374. Test that get_image_dimensions() works properly after various calls
  375. using a file handler (#11158)
  376. """
  377. @unittest.skipUnless(Image, "PIL not installed")
  378. def test_multiple_calls(self):
  379. """
  380. Multiple calls of get_image_dimensions() should return the same size.
  381. """
  382. from django.core.files.images import ImageFile
  383. img_path = os.path.join(os.path.dirname(__file__), "test.png")
  384. image = ImageFile(open(img_path, 'rb'))
  385. image_pil = Image.open(img_path)
  386. size_1, size_2 = get_image_dimensions(image), get_image_dimensions(image)
  387. self.assertEqual(image_pil.size, size_1)
  388. self.assertEqual(size_1, size_2)