tests.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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.mktemp()
  83. os.makedirs(self.temp_dir)
  84. self.storage = self.storage_class(location=self.temp_dir,
  85. base_url='/test_media_url/')
  86. def tearDown(self):
  87. shutil.rmtree(self.temp_dir)
  88. def test_file_access_options(self):
  89. """
  90. Standard file access options are available, and work as expected.
  91. """
  92. self.assertFalse(self.storage.exists('storage_test'))
  93. f = self.storage.open('storage_test', 'w')
  94. f.write('storage contents')
  95. f.close()
  96. self.assert_(self.storage.exists('storage_test'))
  97. f = self.storage.open('storage_test', 'r')
  98. self.assertEqual(f.read(), 'storage contents')
  99. f.close()
  100. self.storage.delete('storage_test')
  101. self.assertFalse(self.storage.exists('storage_test'))
  102. def test_file_accessed_time(self):
  103. """
  104. File storage returns a Datetime object for the last accessed time of
  105. a file.
  106. """
  107. self.assertFalse(self.storage.exists('test.file'))
  108. f = ContentFile('custom contents')
  109. f_name = self.storage.save('test.file', f)
  110. atime = self.storage.accessed_time(f_name)
  111. self.assertEqual(atime, datetime.fromtimestamp(
  112. os.path.getatime(self.storage.path(f_name))))
  113. self.assertTrue(datetime.now() - self.storage.accessed_time(f_name) < timedelta(seconds=2))
  114. self.storage.delete(f_name)
  115. def test_file_created_time(self):
  116. """
  117. File storage returns a Datetime object for the creation time of
  118. a file.
  119. """
  120. self.assertFalse(self.storage.exists('test.file'))
  121. f = ContentFile('custom contents')
  122. f_name = self.storage.save('test.file', f)
  123. ctime = self.storage.created_time(f_name)
  124. self.assertEqual(ctime, datetime.fromtimestamp(
  125. os.path.getctime(self.storage.path(f_name))))
  126. self.assertTrue(datetime.now() - self.storage.created_time(f_name) < timedelta(seconds=2))
  127. self.storage.delete(f_name)
  128. def test_file_modified_time(self):
  129. """
  130. File storage returns a Datetime object for the last modified time of
  131. a file.
  132. """
  133. self.assertFalse(self.storage.exists('test.file'))
  134. f = ContentFile('custom contents')
  135. f_name = self.storage.save('test.file', f)
  136. mtime = self.storage.modified_time(f_name)
  137. self.assertEqual(mtime, datetime.fromtimestamp(
  138. os.path.getmtime(self.storage.path(f_name))))
  139. self.assertTrue(datetime.now() - self.storage.modified_time(f_name) < timedelta(seconds=2))
  140. self.storage.delete(f_name)
  141. def test_file_save_without_name(self):
  142. """
  143. File storage extracts the filename from the content object if no
  144. name is given explicitly.
  145. """
  146. self.assertFalse(self.storage.exists('test.file'))
  147. f = ContentFile('custom contents')
  148. f.name = 'test.file'
  149. storage_f_name = self.storage.save(None, f)
  150. self.assertEqual(storage_f_name, f.name)
  151. self.assert_(os.path.exists(os.path.join(self.temp_dir, f.name)))
  152. self.storage.delete(storage_f_name)
  153. def test_file_path(self):
  154. """
  155. File storage returns the full path of a file
  156. """
  157. self.assertFalse(self.storage.exists('test.file'))
  158. f = ContentFile('custom contents')
  159. f_name = self.storage.save('test.file', f)
  160. self.assertEqual(self.storage.path(f_name),
  161. os.path.join(self.temp_dir, f_name))
  162. self.storage.delete(f_name)
  163. def test_file_url(self):
  164. """
  165. File storage returns a url to access a given file from the Web.
  166. """
  167. self.assertEqual(self.storage.url('test.file'),
  168. '%s%s' % (self.storage.base_url, 'test.file'))
  169. self.storage.base_url = None
  170. self.assertRaises(ValueError, self.storage.url, 'test.file')
  171. def test_file_with_mixin(self):
  172. """
  173. File storage can get a mixin to extend the functionality of the
  174. returned file.
  175. """
  176. self.assertFalse(self.storage.exists('test.file'))
  177. class TestFileMixin(object):
  178. mixed_in = True
  179. f = ContentFile('custom contents')
  180. f_name = self.storage.save('test.file', f)
  181. self.assert_(isinstance(
  182. self.storage.open('test.file', mixin=TestFileMixin),
  183. TestFileMixin
  184. ))
  185. self.storage.delete('test.file')
  186. def test_listdir(self):
  187. """
  188. File storage returns a tuple containing directories and files.
  189. """
  190. self.assertFalse(self.storage.exists('storage_test_1'))
  191. self.assertFalse(self.storage.exists('storage_test_2'))
  192. self.assertFalse(self.storage.exists('storage_dir_1'))
  193. f = self.storage.save('storage_test_1', ContentFile('custom content'))
  194. f = self.storage.save('storage_test_2', ContentFile('custom content'))
  195. os.mkdir(os.path.join(self.temp_dir, 'storage_dir_1'))
  196. dirs, files = self.storage.listdir('')
  197. self.assertEqual(set(dirs), set([u'storage_dir_1']))
  198. self.assertEqual(set(files),
  199. set([u'storage_test_1', u'storage_test_2']))
  200. self.storage.delete('storage_test_1')
  201. self.storage.delete('storage_test_2')
  202. os.rmdir(os.path.join(self.temp_dir, 'storage_dir_1'))
  203. def test_file_storage_prevents_directory_traversal(self):
  204. """
  205. File storage prevents directory traversal (files can only be accessed if
  206. they're below the storage location).
  207. """
  208. self.assertRaises(SuspiciousOperation, self.storage.exists, '..')
  209. self.assertRaises(SuspiciousOperation, self.storage.exists, '/etc/passwd')
  210. class CustomStorage(FileSystemStorage):
  211. def get_available_name(self, name):
  212. """
  213. Append numbers to duplicate files rather than underscores, like Trac.
  214. """
  215. parts = name.split('.')
  216. basename, ext = parts[0], parts[1:]
  217. number = 2
  218. while self.exists(name):
  219. name = '.'.join([basename, str(number)] + ext)
  220. number += 1
  221. return name
  222. class CustomStorageTests(FileStorageTests):
  223. storage_class = CustomStorage
  224. def test_custom_get_available_name(self):
  225. first = self.storage.save('custom_storage', ContentFile('custom contents'))
  226. self.assertEqual(first, 'custom_storage')
  227. second = self.storage.save('custom_storage', ContentFile('more contents'))
  228. self.assertEqual(second, 'custom_storage.2')
  229. self.storage.delete(first)
  230. self.storage.delete(second)
  231. class UnicodeFileNameTests(unittest.TestCase):
  232. def test_unicode_file_names(self):
  233. """
  234. Regression test for #8156: files with unicode names I can't quite figure
  235. out the encoding situation between doctest and this file, but the actual
  236. repr doesn't matter; it just shouldn't return a unicode object.
  237. """
  238. uf = UploadedFile(name=u'¿Cómo?',content_type='text')
  239. self.assertEqual(type(uf.__repr__()), str)
  240. # Tests for a race condition on file saving (#4948).
  241. # This is written in such a way that it'll always pass on platforms
  242. # without threading.
  243. class SlowFile(ContentFile):
  244. def chunks(self):
  245. time.sleep(1)
  246. return super(ContentFile, self).chunks()
  247. class FileSaveRaceConditionTest(unittest.TestCase):
  248. def setUp(self):
  249. self.storage_dir = tempfile.mkdtemp()
  250. self.storage = FileSystemStorage(self.storage_dir)
  251. self.thread = threading.Thread(target=self.save_file, args=['conflict'])
  252. def tearDown(self):
  253. shutil.rmtree(self.storage_dir)
  254. def save_file(self, name):
  255. name = self.storage.save(name, SlowFile("Data"))
  256. def test_race_condition(self):
  257. self.thread.start()
  258. name = self.save_file('conflict')
  259. self.thread.join()
  260. self.assert_(self.storage.exists('conflict'))
  261. self.assert_(self.storage.exists('conflict_1'))
  262. self.storage.delete('conflict')
  263. self.storage.delete('conflict_1')
  264. class FileStoragePermissions(unittest.TestCase):
  265. def setUp(self):
  266. self.old_perms = settings.FILE_UPLOAD_PERMISSIONS
  267. settings.FILE_UPLOAD_PERMISSIONS = 0666
  268. self.storage_dir = tempfile.mkdtemp()
  269. self.storage = FileSystemStorage(self.storage_dir)
  270. def tearDown(self):
  271. settings.FILE_UPLOAD_PERMISSIONS = self.old_perms
  272. shutil.rmtree(self.storage_dir)
  273. def test_file_upload_permissions(self):
  274. name = self.storage.save("the_file", ContentFile("data"))
  275. actual_mode = os.stat(self.storage.path(name))[0] & 0777
  276. self.assertEqual(actual_mode, 0666)
  277. class FileStoragePathParsing(unittest.TestCase):
  278. def setUp(self):
  279. self.storage_dir = tempfile.mkdtemp()
  280. self.storage = FileSystemStorage(self.storage_dir)
  281. def tearDown(self):
  282. shutil.rmtree(self.storage_dir)
  283. def test_directory_with_dot(self):
  284. """Regression test for #9610.
  285. If the directory name contains a dot and the file name doesn't, make
  286. sure we still mangle the file name instead of the directory name.
  287. """
  288. self.storage.save('dotted.path/test', ContentFile("1"))
  289. self.storage.save('dotted.path/test', ContentFile("2"))
  290. self.assertFalse(os.path.exists(os.path.join(self.storage_dir, 'dotted_.path')))
  291. self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test')))
  292. self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test_1')))
  293. def test_first_character_dot(self):
  294. """
  295. File names with a dot as their first character don't have an extension,
  296. and the underscore should get added to the end.
  297. """
  298. self.storage.save('dotted.path/.test', ContentFile("1"))
  299. self.storage.save('dotted.path/.test', ContentFile("2"))
  300. self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test')))
  301. # Before 2.6, a leading dot was treated as an extension, and so
  302. # underscore gets added to beginning instead of end.
  303. if sys.version_info < (2, 6):
  304. self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/_1.test')))
  305. else:
  306. self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test_1')))
  307. class DimensionClosingBug(unittest.TestCase):
  308. """
  309. Test that get_image_dimensions() properly closes files (#8817)
  310. """
  311. @unittest.skipUnless(Image, "PIL not installed")
  312. def test_not_closing_of_files(self):
  313. """
  314. Open files passed into get_image_dimensions() should stay opened.
  315. """
  316. empty_io = StringIO()
  317. try:
  318. get_image_dimensions(empty_io)
  319. finally:
  320. self.assert_(not empty_io.closed)
  321. @unittest.skipUnless(Image, "PIL not installed")
  322. def test_closing_of_filenames(self):
  323. """
  324. get_image_dimensions() called with a filename should closed the file.
  325. """
  326. # We need to inject a modified open() builtin into the images module
  327. # that checks if the file was closed properly if the function is
  328. # called with a filename instead of an file object.
  329. # get_image_dimensions will call our catching_open instead of the
  330. # regular builtin one.
  331. class FileWrapper(object):
  332. _closed = []
  333. def __init__(self, f):
  334. self.f = f
  335. def __getattr__(self, name):
  336. return getattr(self.f, name)
  337. def close(self):
  338. self._closed.append(True)
  339. self.f.close()
  340. def catching_open(*args):
  341. return FileWrapper(open(*args))
  342. from django.core.files import images
  343. images.open = catching_open
  344. try:
  345. get_image_dimensions(os.path.join(os.path.dirname(__file__), "test1.png"))
  346. finally:
  347. del images.open
  348. self.assert_(FileWrapper._closed)
  349. class InconsistentGetImageDimensionsBug(unittest.TestCase):
  350. """
  351. Test that get_image_dimensions() works properly after various calls
  352. using a file handler (#11158)
  353. """
  354. @unittest.skipUnless(Image, "PIL not installed")
  355. def test_multiple_calls(self):
  356. """
  357. Multiple calls of get_image_dimensions() should return the same size.
  358. """
  359. from django.core.files.images import ImageFile
  360. img_path = os.path.join(os.path.dirname(__file__), "test.png")
  361. image = ImageFile(open(img_path, 'rb'))
  362. image_pil = Image.open(img_path)
  363. size_1, size_2 = get_image_dimensions(image), get_image_dimensions(image)
  364. self.assertEqual(image_pil.size, size_1)
  365. self.assertEqual(size_1, size_2)