tests.py 23 KB

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