test_storage.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. import os
  2. import shutil
  3. import sys
  4. import tempfile
  5. import unittest
  6. from io import StringIO
  7. from pathlib import Path
  8. from unittest import mock
  9. from django.conf import settings
  10. from django.contrib.staticfiles import finders, storage
  11. from django.contrib.staticfiles.management.commands.collectstatic import (
  12. Command as CollectstaticCommand,
  13. )
  14. from django.core.management import call_command
  15. from django.test import override_settings
  16. from .cases import CollectionTestCase
  17. from .settings import TEST_ROOT
  18. def hashed_file_path(test, path):
  19. fullpath = test.render_template(test.static_template_snippet(path))
  20. return fullpath.replace(settings.STATIC_URL, '')
  21. class TestHashedFiles:
  22. hashed_file_path = hashed_file_path
  23. def tearDown(self):
  24. # Clear hashed files to avoid side effects among tests.
  25. storage.staticfiles_storage.hashed_files.clear()
  26. def assertPostCondition(self):
  27. """
  28. Assert post conditions for a test are met. Must be manually called at
  29. the end of each test.
  30. """
  31. pass
  32. def test_template_tag_return(self):
  33. self.assertStaticRaises(ValueError, "does/not/exist.png", "/static/does/not/exist.png")
  34. self.assertStaticRenders("test/file.txt", "/static/test/file.dad0999e4f8f.txt")
  35. self.assertStaticRenders("test/file.txt", "/static/test/file.dad0999e4f8f.txt", asvar=True)
  36. self.assertStaticRenders("cached/styles.css", "/static/cached/styles.5e0040571e1a.css")
  37. self.assertStaticRenders("path/", "/static/path/")
  38. self.assertStaticRenders("path/?query", "/static/path/?query")
  39. self.assertPostCondition()
  40. def test_template_tag_simple_content(self):
  41. relpath = self.hashed_file_path("cached/styles.css")
  42. self.assertEqual(relpath, "cached/styles.5e0040571e1a.css")
  43. with storage.staticfiles_storage.open(relpath) as relfile:
  44. content = relfile.read()
  45. self.assertNotIn(b"cached/other.css", content)
  46. self.assertIn(b"other.d41d8cd98f00.css", content)
  47. self.assertPostCondition()
  48. def test_path_ignored_completely(self):
  49. relpath = self.hashed_file_path("cached/css/ignored.css")
  50. self.assertEqual(relpath, "cached/css/ignored.554da52152af.css")
  51. with storage.staticfiles_storage.open(relpath) as relfile:
  52. content = relfile.read()
  53. self.assertIn(b'#foobar', content)
  54. self.assertIn(b'http:foobar', content)
  55. self.assertIn(b'https:foobar', content)
  56. self.assertIn(b'data:foobar', content)
  57. self.assertIn(b'chrome:foobar', content)
  58. self.assertIn(b'//foobar', content)
  59. self.assertPostCondition()
  60. def test_path_with_querystring(self):
  61. relpath = self.hashed_file_path("cached/styles.css?spam=eggs")
  62. self.assertEqual(relpath, "cached/styles.5e0040571e1a.css?spam=eggs")
  63. with storage.staticfiles_storage.open("cached/styles.5e0040571e1a.css") as relfile:
  64. content = relfile.read()
  65. self.assertNotIn(b"cached/other.css", content)
  66. self.assertIn(b"other.d41d8cd98f00.css", content)
  67. self.assertPostCondition()
  68. def test_path_with_fragment(self):
  69. relpath = self.hashed_file_path("cached/styles.css#eggs")
  70. self.assertEqual(relpath, "cached/styles.5e0040571e1a.css#eggs")
  71. with storage.staticfiles_storage.open("cached/styles.5e0040571e1a.css") as relfile:
  72. content = relfile.read()
  73. self.assertNotIn(b"cached/other.css", content)
  74. self.assertIn(b"other.d41d8cd98f00.css", content)
  75. self.assertPostCondition()
  76. def test_path_with_querystring_and_fragment(self):
  77. relpath = self.hashed_file_path("cached/css/fragments.css")
  78. self.assertEqual(relpath, "cached/css/fragments.a60c0e74834f.css")
  79. with storage.staticfiles_storage.open(relpath) as relfile:
  80. content = relfile.read()
  81. self.assertIn(b'fonts/font.b9b105392eb8.eot?#iefix', content)
  82. self.assertIn(b'fonts/font.b8d603e42714.svg#webfontIyfZbseF', content)
  83. self.assertIn(b'fonts/font.b8d603e42714.svg#path/to/../../fonts/font.svg', content)
  84. self.assertIn(b'data:font/woff;charset=utf-8;base64,d09GRgABAAAAADJoAA0AAAAAR2QAAQAAAAAAAAAAAAA', content)
  85. self.assertIn(b'#default#VML', content)
  86. self.assertPostCondition()
  87. def test_template_tag_absolute(self):
  88. relpath = self.hashed_file_path("cached/absolute.css")
  89. self.assertEqual(relpath, "cached/absolute.eb04def9f9a4.css")
  90. with storage.staticfiles_storage.open(relpath) as relfile:
  91. content = relfile.read()
  92. self.assertNotIn(b"/static/cached/styles.css", content)
  93. self.assertIn(b"/static/cached/styles.5e0040571e1a.css", content)
  94. self.assertNotIn(b"/static/styles_root.css", content)
  95. self.assertIn(b"/static/styles_root.401f2509a628.css", content)
  96. self.assertIn(b'/static/cached/img/relative.acae32e4532b.png', content)
  97. self.assertPostCondition()
  98. def test_template_tag_absolute_root(self):
  99. """
  100. Like test_template_tag_absolute, but for a file in STATIC_ROOT (#26249).
  101. """
  102. relpath = self.hashed_file_path("absolute_root.css")
  103. self.assertEqual(relpath, "absolute_root.f821df1b64f7.css")
  104. with storage.staticfiles_storage.open(relpath) as relfile:
  105. content = relfile.read()
  106. self.assertNotIn(b"/static/styles_root.css", content)
  107. self.assertIn(b"/static/styles_root.401f2509a628.css", content)
  108. self.assertPostCondition()
  109. def test_template_tag_relative(self):
  110. relpath = self.hashed_file_path("cached/relative.css")
  111. self.assertEqual(relpath, "cached/relative.c3e9e1ea6f2e.css")
  112. with storage.staticfiles_storage.open(relpath) as relfile:
  113. content = relfile.read()
  114. self.assertNotIn(b"../cached/styles.css", content)
  115. self.assertNotIn(b'@import "styles.css"', content)
  116. self.assertNotIn(b'url(img/relative.png)', content)
  117. self.assertIn(b'url("img/relative.acae32e4532b.png")', content)
  118. self.assertIn(b"../cached/styles.5e0040571e1a.css", content)
  119. self.assertPostCondition()
  120. def test_import_replacement(self):
  121. "See #18050"
  122. relpath = self.hashed_file_path("cached/import.css")
  123. self.assertEqual(relpath, "cached/import.f53576679e5a.css")
  124. with storage.staticfiles_storage.open(relpath) as relfile:
  125. self.assertIn(b"""import url("styles.5e0040571e1a.css")""", relfile.read())
  126. self.assertPostCondition()
  127. def test_template_tag_deep_relative(self):
  128. relpath = self.hashed_file_path("cached/css/window.css")
  129. self.assertEqual(relpath, "cached/css/window.5d5c10836967.css")
  130. with storage.staticfiles_storage.open(relpath) as relfile:
  131. content = relfile.read()
  132. self.assertNotIn(b'url(img/window.png)', content)
  133. self.assertIn(b'url("img/window.acae32e4532b.png")', content)
  134. self.assertPostCondition()
  135. def test_template_tag_url(self):
  136. relpath = self.hashed_file_path("cached/url.css")
  137. self.assertEqual(relpath, "cached/url.902310b73412.css")
  138. with storage.staticfiles_storage.open(relpath) as relfile:
  139. self.assertIn(b"https://", relfile.read())
  140. self.assertPostCondition()
  141. @override_settings(
  142. STATICFILES_DIRS=[os.path.join(TEST_ROOT, 'project', 'loop')],
  143. STATICFILES_FINDERS=['django.contrib.staticfiles.finders.FileSystemFinder'],
  144. )
  145. def test_import_loop(self):
  146. finders.get_finder.cache_clear()
  147. err = StringIO()
  148. with self.assertRaisesMessage(RuntimeError, 'Max post-process passes exceeded'):
  149. call_command('collectstatic', interactive=False, verbosity=0, stderr=err)
  150. self.assertEqual("Post-processing 'All' failed!\n\n", err.getvalue())
  151. self.assertPostCondition()
  152. def test_post_processing(self):
  153. """
  154. post_processing behaves correctly.
  155. Files that are alterable should always be post-processed; files that
  156. aren't should be skipped.
  157. collectstatic has already been called once in setUp() for this testcase,
  158. therefore we check by verifying behavior on a second run.
  159. """
  160. collectstatic_args = {
  161. 'interactive': False,
  162. 'verbosity': 0,
  163. 'link': False,
  164. 'clear': False,
  165. 'dry_run': False,
  166. 'post_process': True,
  167. 'use_default_ignore_patterns': True,
  168. 'ignore_patterns': ['*.ignoreme'],
  169. }
  170. collectstatic_cmd = CollectstaticCommand()
  171. collectstatic_cmd.set_options(**collectstatic_args)
  172. stats = collectstatic_cmd.collect()
  173. self.assertIn(os.path.join('cached', 'css', 'window.css'), stats['post_processed'])
  174. self.assertIn(os.path.join('cached', 'css', 'img', 'window.png'), stats['unmodified'])
  175. self.assertIn(os.path.join('test', 'nonascii.css'), stats['post_processed'])
  176. # No file should be yielded twice.
  177. self.assertCountEqual(stats['post_processed'], set(stats['post_processed']))
  178. self.assertPostCondition()
  179. def test_css_import_case_insensitive(self):
  180. relpath = self.hashed_file_path("cached/styles_insensitive.css")
  181. self.assertEqual(relpath, "cached/styles_insensitive.3fa427592a53.css")
  182. with storage.staticfiles_storage.open(relpath) as relfile:
  183. content = relfile.read()
  184. self.assertNotIn(b"cached/other.css", content)
  185. self.assertIn(b"other.d41d8cd98f00.css", content)
  186. self.assertPostCondition()
  187. def test_js_source_map(self):
  188. relpath = self.hashed_file_path('cached/source_map.js')
  189. self.assertEqual(relpath, 'cached/source_map.9371cbb02a26.js')
  190. with storage.staticfiles_storage.open(relpath) as relfile:
  191. content = relfile.read()
  192. self.assertNotIn(b'//# sourceMappingURL=source_map.js.map', content)
  193. self.assertIn(
  194. b'//# sourceMappingURL=source_map.js.99914b932bd3.map',
  195. content,
  196. )
  197. self.assertPostCondition()
  198. def test_js_source_map_sensitive(self):
  199. relpath = self.hashed_file_path('cached/source_map_sensitive.js')
  200. self.assertEqual(relpath, 'cached/source_map_sensitive.5da96fdd3cb3.js')
  201. with storage.staticfiles_storage.open(relpath) as relfile:
  202. content = relfile.read()
  203. self.assertIn(b'//# sOuRcEMaPpInGURL=source_map.js.map', content)
  204. self.assertNotIn(
  205. b'//# sourceMappingURL=source_map.js.99914b932bd3.map',
  206. content,
  207. )
  208. self.assertPostCondition()
  209. @override_settings(
  210. STATICFILES_DIRS=[os.path.join(TEST_ROOT, 'project', 'faulty')],
  211. STATICFILES_FINDERS=['django.contrib.staticfiles.finders.FileSystemFinder'],
  212. )
  213. def test_post_processing_failure(self):
  214. """
  215. post_processing indicates the origin of the error when it fails.
  216. """
  217. finders.get_finder.cache_clear()
  218. err = StringIO()
  219. with self.assertRaises(Exception):
  220. call_command('collectstatic', interactive=False, verbosity=0, stderr=err)
  221. self.assertEqual("Post-processing 'faulty.css' failed!\n\n", err.getvalue())
  222. self.assertPostCondition()
  223. @override_settings(STATICFILES_STORAGE='staticfiles_tests.storage.ExtraPatternsStorage')
  224. class TestExtraPatternsStorage(CollectionTestCase):
  225. def setUp(self):
  226. storage.staticfiles_storage.hashed_files.clear() # avoid cache interference
  227. super().setUp()
  228. def cached_file_path(self, path):
  229. fullpath = self.render_template(self.static_template_snippet(path))
  230. return fullpath.replace(settings.STATIC_URL, '')
  231. def test_multi_extension_patterns(self):
  232. """
  233. With storage classes having several file extension patterns, only the
  234. files matching a specific file pattern should be affected by the
  235. substitution (#19670).
  236. """
  237. # CSS files shouldn't be touched by JS patterns.
  238. relpath = self.cached_file_path("cached/import.css")
  239. self.assertEqual(relpath, "cached/import.f53576679e5a.css")
  240. with storage.staticfiles_storage.open(relpath) as relfile:
  241. self.assertIn(b'import url("styles.5e0040571e1a.css")', relfile.read())
  242. # Confirm JS patterns have been applied to JS files.
  243. relpath = self.cached_file_path("cached/test.js")
  244. self.assertEqual(relpath, "cached/test.388d7a790d46.js")
  245. with storage.staticfiles_storage.open(relpath) as relfile:
  246. self.assertIn(b'JS_URL("import.f53576679e5a.css")', relfile.read())
  247. @override_settings(
  248. STATICFILES_STORAGE='django.contrib.staticfiles.storage.ManifestStaticFilesStorage',
  249. )
  250. class TestCollectionManifestStorage(TestHashedFiles, CollectionTestCase):
  251. """
  252. Tests for the Cache busting storage
  253. """
  254. def setUp(self):
  255. super().setUp()
  256. temp_dir = tempfile.mkdtemp()
  257. os.makedirs(os.path.join(temp_dir, 'test'))
  258. self._clear_filename = os.path.join(temp_dir, 'test', 'cleared.txt')
  259. with open(self._clear_filename, 'w') as f:
  260. f.write('to be deleted in one test')
  261. self.patched_settings = self.settings(
  262. STATICFILES_DIRS=settings.STATICFILES_DIRS + [temp_dir],
  263. )
  264. self.patched_settings.enable()
  265. self.addCleanup(shutil.rmtree, temp_dir)
  266. self._manifest_strict = storage.staticfiles_storage.manifest_strict
  267. def tearDown(self):
  268. self.patched_settings.disable()
  269. if os.path.exists(self._clear_filename):
  270. os.unlink(self._clear_filename)
  271. storage.staticfiles_storage.manifest_strict = self._manifest_strict
  272. super().tearDown()
  273. def assertPostCondition(self):
  274. hashed_files = storage.staticfiles_storage.hashed_files
  275. # The in-memory version of the manifest matches the one on disk
  276. # since a properly created manifest should cover all filenames.
  277. if hashed_files:
  278. manifest = storage.staticfiles_storage.load_manifest()
  279. self.assertEqual(hashed_files, manifest)
  280. def test_manifest_exists(self):
  281. filename = storage.staticfiles_storage.manifest_name
  282. path = storage.staticfiles_storage.path(filename)
  283. self.assertTrue(os.path.exists(path))
  284. def test_manifest_does_not_exist(self):
  285. storage.staticfiles_storage.manifest_name = 'does.not.exist.json'
  286. self.assertIsNone(storage.staticfiles_storage.read_manifest())
  287. def test_manifest_does_not_ignore_permission_error(self):
  288. with mock.patch('builtins.open', side_effect=PermissionError):
  289. with self.assertRaises(PermissionError):
  290. storage.staticfiles_storage.read_manifest()
  291. def test_loaded_cache(self):
  292. self.assertNotEqual(storage.staticfiles_storage.hashed_files, {})
  293. manifest_content = storage.staticfiles_storage.read_manifest()
  294. self.assertIn(
  295. '"version": "%s"' % storage.staticfiles_storage.manifest_version,
  296. manifest_content
  297. )
  298. def test_parse_cache(self):
  299. hashed_files = storage.staticfiles_storage.hashed_files
  300. manifest = storage.staticfiles_storage.load_manifest()
  301. self.assertEqual(hashed_files, manifest)
  302. def test_clear_empties_manifest(self):
  303. cleared_file_name = storage.staticfiles_storage.clean_name(os.path.join('test', 'cleared.txt'))
  304. # collect the additional file
  305. self.run_collectstatic()
  306. hashed_files = storage.staticfiles_storage.hashed_files
  307. self.assertIn(cleared_file_name, hashed_files)
  308. manifest_content = storage.staticfiles_storage.load_manifest()
  309. self.assertIn(cleared_file_name, manifest_content)
  310. original_path = storage.staticfiles_storage.path(cleared_file_name)
  311. self.assertTrue(os.path.exists(original_path))
  312. # delete the original file form the app, collect with clear
  313. os.unlink(self._clear_filename)
  314. self.run_collectstatic(clear=True)
  315. self.assertFileNotFound(original_path)
  316. hashed_files = storage.staticfiles_storage.hashed_files
  317. self.assertNotIn(cleared_file_name, hashed_files)
  318. manifest_content = storage.staticfiles_storage.load_manifest()
  319. self.assertNotIn(cleared_file_name, manifest_content)
  320. def test_missing_entry(self):
  321. missing_file_name = 'cached/missing.css'
  322. configured_storage = storage.staticfiles_storage
  323. self.assertNotIn(missing_file_name, configured_storage.hashed_files)
  324. # File name not found in manifest
  325. with self.assertRaisesMessage(ValueError, "Missing staticfiles manifest entry for '%s'" % missing_file_name):
  326. self.hashed_file_path(missing_file_name)
  327. configured_storage.manifest_strict = False
  328. # File doesn't exist on disk
  329. err_msg = "The file '%s' could not be found with %r." % (missing_file_name, configured_storage._wrapped)
  330. with self.assertRaisesMessage(ValueError, err_msg):
  331. self.hashed_file_path(missing_file_name)
  332. content = StringIO()
  333. content.write('Found')
  334. configured_storage.save(missing_file_name, content)
  335. # File exists on disk
  336. self.hashed_file_path(missing_file_name)
  337. def test_intermediate_files(self):
  338. cached_files = os.listdir(os.path.join(settings.STATIC_ROOT, 'cached'))
  339. # Intermediate files shouldn't be created for reference.
  340. self.assertEqual(
  341. len([
  342. cached_file
  343. for cached_file in cached_files
  344. if cached_file.startswith('relative.')
  345. ]),
  346. 2,
  347. )
  348. @override_settings(STATICFILES_STORAGE='staticfiles_tests.storage.NoneHashStorage')
  349. class TestCollectionNoneHashStorage(CollectionTestCase):
  350. hashed_file_path = hashed_file_path
  351. def test_hashed_name(self):
  352. relpath = self.hashed_file_path('cached/styles.css')
  353. self.assertEqual(relpath, 'cached/styles.css')
  354. @override_settings(STATICFILES_STORAGE='staticfiles_tests.storage.SimpleStorage')
  355. class TestCollectionSimpleStorage(CollectionTestCase):
  356. hashed_file_path = hashed_file_path
  357. def setUp(self):
  358. storage.staticfiles_storage.hashed_files.clear() # avoid cache interference
  359. super().setUp()
  360. def test_template_tag_return(self):
  361. self.assertStaticRaises(ValueError, "does/not/exist.png", "/static/does/not/exist.png")
  362. self.assertStaticRenders("test/file.txt", "/static/test/file.deploy12345.txt")
  363. self.assertStaticRenders("cached/styles.css", "/static/cached/styles.deploy12345.css")
  364. self.assertStaticRenders("path/", "/static/path/")
  365. self.assertStaticRenders("path/?query", "/static/path/?query")
  366. def test_template_tag_simple_content(self):
  367. relpath = self.hashed_file_path("cached/styles.css")
  368. self.assertEqual(relpath, "cached/styles.deploy12345.css")
  369. with storage.staticfiles_storage.open(relpath) as relfile:
  370. content = relfile.read()
  371. self.assertNotIn(b"cached/other.css", content)
  372. self.assertIn(b"other.deploy12345.css", content)
  373. class CustomStaticFilesStorage(storage.StaticFilesStorage):
  374. """
  375. Used in TestStaticFilePermissions
  376. """
  377. def __init__(self, *args, **kwargs):
  378. kwargs['file_permissions_mode'] = 0o640
  379. kwargs['directory_permissions_mode'] = 0o740
  380. super().__init__(*args, **kwargs)
  381. @unittest.skipIf(sys.platform == 'win32', "Windows only partially supports chmod.")
  382. class TestStaticFilePermissions(CollectionTestCase):
  383. command_params = {
  384. 'interactive': False,
  385. 'verbosity': 0,
  386. 'ignore_patterns': ['*.ignoreme'],
  387. }
  388. def setUp(self):
  389. self.umask = 0o027
  390. self.old_umask = os.umask(self.umask)
  391. super().setUp()
  392. def tearDown(self):
  393. os.umask(self.old_umask)
  394. super().tearDown()
  395. # Don't run collectstatic command in this test class.
  396. def run_collectstatic(self, **kwargs):
  397. pass
  398. @override_settings(
  399. FILE_UPLOAD_PERMISSIONS=0o655,
  400. FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765,
  401. )
  402. def test_collect_static_files_permissions(self):
  403. call_command('collectstatic', **self.command_params)
  404. static_root = Path(settings.STATIC_ROOT)
  405. test_file = static_root / 'test.txt'
  406. file_mode = test_file.stat().st_mode & 0o777
  407. self.assertEqual(file_mode, 0o655)
  408. tests = [
  409. static_root / 'subdir',
  410. static_root / 'nested',
  411. static_root / 'nested' / 'css',
  412. ]
  413. for directory in tests:
  414. with self.subTest(directory=directory):
  415. dir_mode = directory.stat().st_mode & 0o777
  416. self.assertEqual(dir_mode, 0o765)
  417. @override_settings(
  418. FILE_UPLOAD_PERMISSIONS=None,
  419. FILE_UPLOAD_DIRECTORY_PERMISSIONS=None,
  420. )
  421. def test_collect_static_files_default_permissions(self):
  422. call_command('collectstatic', **self.command_params)
  423. static_root = Path(settings.STATIC_ROOT)
  424. test_file = static_root / 'test.txt'
  425. file_mode = test_file.stat().st_mode & 0o777
  426. self.assertEqual(file_mode, 0o666 & ~self.umask)
  427. tests = [
  428. static_root / 'subdir',
  429. static_root / 'nested',
  430. static_root / 'nested' / 'css',
  431. ]
  432. for directory in tests:
  433. with self.subTest(directory=directory):
  434. dir_mode = directory.stat().st_mode & 0o777
  435. self.assertEqual(dir_mode, 0o777 & ~self.umask)
  436. @override_settings(
  437. FILE_UPLOAD_PERMISSIONS=0o655,
  438. FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765,
  439. STATICFILES_STORAGE='staticfiles_tests.test_storage.CustomStaticFilesStorage',
  440. )
  441. def test_collect_static_files_subclass_of_static_storage(self):
  442. call_command('collectstatic', **self.command_params)
  443. static_root = Path(settings.STATIC_ROOT)
  444. test_file = static_root / 'test.txt'
  445. file_mode = test_file.stat().st_mode & 0o777
  446. self.assertEqual(file_mode, 0o640)
  447. tests = [
  448. static_root / 'subdir',
  449. static_root / 'nested',
  450. static_root / 'nested' / 'css',
  451. ]
  452. for directory in tests:
  453. with self.subTest(directory=directory):
  454. dir_mode = directory.stat().st_mode & 0o777
  455. self.assertEqual(dir_mode, 0o740)
  456. @override_settings(
  457. STATICFILES_STORAGE='django.contrib.staticfiles.storage.ManifestStaticFilesStorage',
  458. )
  459. class TestCollectionHashedFilesCache(CollectionTestCase):
  460. """
  461. Files referenced from CSS use the correct final hashed name regardless of
  462. the order in which the files are post-processed.
  463. """
  464. hashed_file_path = hashed_file_path
  465. def setUp(self):
  466. super().setUp()
  467. self._temp_dir = temp_dir = tempfile.mkdtemp()
  468. os.makedirs(os.path.join(temp_dir, 'test'))
  469. self.addCleanup(shutil.rmtree, temp_dir)
  470. def _get_filename_path(self, filename):
  471. return os.path.join(self._temp_dir, 'test', filename)
  472. def test_file_change_after_collectstatic(self):
  473. # Create initial static files.
  474. file_contents = (
  475. ('foo.png', 'foo'),
  476. ('bar.css', 'url("foo.png")\nurl("xyz.png")'),
  477. ('xyz.png', 'xyz'),
  478. )
  479. for filename, content in file_contents:
  480. with open(self._get_filename_path(filename), 'w') as f:
  481. f.write(content)
  482. with self.modify_settings(STATICFILES_DIRS={'append': self._temp_dir}):
  483. finders.get_finder.cache_clear()
  484. err = StringIO()
  485. # First collectstatic run.
  486. call_command('collectstatic', interactive=False, verbosity=0, stderr=err)
  487. relpath = self.hashed_file_path('test/bar.css')
  488. with storage.staticfiles_storage.open(relpath) as relfile:
  489. content = relfile.read()
  490. self.assertIn(b'foo.acbd18db4cc2.png', content)
  491. self.assertIn(b'xyz.d16fb36f0911.png', content)
  492. # Change the contents of the png files.
  493. for filename in ('foo.png', 'xyz.png'):
  494. with open(self._get_filename_path(filename), 'w+b') as f:
  495. f.write(b"new content of file to change its hash")
  496. # The hashes of the png files in the CSS file are updated after
  497. # a second collectstatic.
  498. call_command('collectstatic', interactive=False, verbosity=0, stderr=err)
  499. relpath = self.hashed_file_path('test/bar.css')
  500. with storage.staticfiles_storage.open(relpath) as relfile:
  501. content = relfile.read()
  502. self.assertIn(b'foo.57a5cb9ba68d.png', content)
  503. self.assertIn(b'xyz.57a5cb9ba68d.png', content)