tests.py 15 KB

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