tests.py 24 KB

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