test_storage.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902
  1. import json
  2. import os
  3. import shutil
  4. import sys
  5. import tempfile
  6. import unittest
  7. from io import StringIO
  8. from pathlib import Path
  9. from unittest import mock
  10. from django.conf import STATICFILES_STORAGE_ALIAS, settings
  11. from django.contrib.staticfiles import finders, storage
  12. from django.contrib.staticfiles.management.commands.collectstatic import (
  13. Command as CollectstaticCommand,
  14. )
  15. from django.core.management import call_command
  16. from django.test import SimpleTestCase, override_settings
  17. from .cases import CollectionTestCase
  18. from .settings import TEST_ROOT
  19. def hashed_file_path(test, path):
  20. fullpath = test.render_template(test.static_template_snippet(path))
  21. return fullpath.replace(settings.STATIC_URL, "")
  22. class TestHashedFiles:
  23. hashed_file_path = hashed_file_path
  24. def tearDown(self):
  25. # Clear hashed files to avoid side effects among tests.
  26. storage.staticfiles_storage.hashed_files.clear()
  27. def assertPostCondition(self):
  28. """
  29. Assert post conditions for a test are met. Must be manually called at
  30. the end of each test.
  31. """
  32. pass
  33. def test_template_tag_return(self):
  34. self.assertStaticRaises(
  35. ValueError, "does/not/exist.png", "/static/does/not/exist.png"
  36. )
  37. self.assertStaticRenders("test/file.txt", "/static/test/file.dad0999e4f8f.txt")
  38. self.assertStaticRenders(
  39. "test/file.txt", "/static/test/file.dad0999e4f8f.txt", asvar=True
  40. )
  41. self.assertStaticRenders(
  42. "cached/styles.css", "/static/cached/styles.5e0040571e1a.css"
  43. )
  44. self.assertStaticRenders("path/", "/static/path/")
  45. self.assertStaticRenders("path/?query", "/static/path/?query")
  46. self.assertPostCondition()
  47. def test_template_tag_simple_content(self):
  48. relpath = self.hashed_file_path("cached/styles.css")
  49. self.assertEqual(relpath, "cached/styles.5e0040571e1a.css")
  50. with storage.staticfiles_storage.open(relpath) as relfile:
  51. content = relfile.read()
  52. self.assertNotIn(b"cached/other.css", content)
  53. self.assertIn(b"other.d41d8cd98f00.css", content)
  54. self.assertPostCondition()
  55. def test_path_ignored_completely(self):
  56. relpath = self.hashed_file_path("cached/css/ignored.css")
  57. self.assertEqual(relpath, "cached/css/ignored.55e7c226dda1.css")
  58. with storage.staticfiles_storage.open(relpath) as relfile:
  59. content = relfile.read()
  60. self.assertIn(b"#foobar", content)
  61. self.assertIn(b"http:foobar", content)
  62. self.assertIn(b"https:foobar", content)
  63. self.assertIn(b"data:foobar", content)
  64. self.assertIn(b"chrome:foobar", content)
  65. self.assertIn(b"//foobar", content)
  66. self.assertIn(b"url()", content)
  67. self.assertPostCondition()
  68. def test_path_with_querystring(self):
  69. relpath = self.hashed_file_path("cached/styles.css?spam=eggs")
  70. self.assertEqual(relpath, "cached/styles.5e0040571e1a.css?spam=eggs")
  71. with storage.staticfiles_storage.open(
  72. "cached/styles.5e0040571e1a.css"
  73. ) as relfile:
  74. content = relfile.read()
  75. self.assertNotIn(b"cached/other.css", content)
  76. self.assertIn(b"other.d41d8cd98f00.css", content)
  77. self.assertPostCondition()
  78. def test_path_with_fragment(self):
  79. relpath = self.hashed_file_path("cached/styles.css#eggs")
  80. self.assertEqual(relpath, "cached/styles.5e0040571e1a.css#eggs")
  81. with storage.staticfiles_storage.open(
  82. "cached/styles.5e0040571e1a.css"
  83. ) as relfile:
  84. content = relfile.read()
  85. self.assertNotIn(b"cached/other.css", content)
  86. self.assertIn(b"other.d41d8cd98f00.css", content)
  87. self.assertPostCondition()
  88. def test_path_with_querystring_and_fragment(self):
  89. relpath = self.hashed_file_path("cached/css/fragments.css")
  90. self.assertEqual(relpath, "cached/css/fragments.a60c0e74834f.css")
  91. with storage.staticfiles_storage.open(relpath) as relfile:
  92. content = relfile.read()
  93. self.assertIn(b"fonts/font.b9b105392eb8.eot?#iefix", content)
  94. self.assertIn(b"fonts/font.b8d603e42714.svg#webfontIyfZbseF", content)
  95. self.assertIn(
  96. b"fonts/font.b8d603e42714.svg#path/to/../../fonts/font.svg", content
  97. )
  98. self.assertIn(
  99. b"data:font/woff;charset=utf-8;"
  100. b"base64,d09GRgABAAAAADJoAA0AAAAAR2QAAQAAAAAAAAAAAAA",
  101. content,
  102. )
  103. self.assertIn(b"#default#VML", content)
  104. self.assertPostCondition()
  105. def test_template_tag_absolute(self):
  106. relpath = self.hashed_file_path("cached/absolute.css")
  107. self.assertEqual(relpath, "cached/absolute.eb04def9f9a4.css")
  108. with storage.staticfiles_storage.open(relpath) as relfile:
  109. content = relfile.read()
  110. self.assertNotIn(b"/static/cached/styles.css", content)
  111. self.assertIn(b"/static/cached/styles.5e0040571e1a.css", content)
  112. self.assertNotIn(b"/static/styles_root.css", content)
  113. self.assertIn(b"/static/styles_root.401f2509a628.css", content)
  114. self.assertIn(b"/static/cached/img/relative.acae32e4532b.png", content)
  115. self.assertPostCondition()
  116. def test_template_tag_absolute_root(self):
  117. """
  118. Like test_template_tag_absolute, but for a file in STATIC_ROOT (#26249).
  119. """
  120. relpath = self.hashed_file_path("absolute_root.css")
  121. self.assertEqual(relpath, "absolute_root.f821df1b64f7.css")
  122. with storage.staticfiles_storage.open(relpath) as relfile:
  123. content = relfile.read()
  124. self.assertNotIn(b"/static/styles_root.css", content)
  125. self.assertIn(b"/static/styles_root.401f2509a628.css", content)
  126. self.assertPostCondition()
  127. def test_template_tag_relative(self):
  128. relpath = self.hashed_file_path("cached/relative.css")
  129. self.assertEqual(relpath, "cached/relative.c3e9e1ea6f2e.css")
  130. with storage.staticfiles_storage.open(relpath) as relfile:
  131. content = relfile.read()
  132. self.assertNotIn(b"../cached/styles.css", content)
  133. self.assertNotIn(b'@import "styles.css"', content)
  134. self.assertNotIn(b"url(img/relative.png)", content)
  135. self.assertIn(b'url("img/relative.acae32e4532b.png")', content)
  136. self.assertIn(b"../cached/styles.5e0040571e1a.css", content)
  137. self.assertPostCondition()
  138. def test_import_replacement(self):
  139. "See #18050"
  140. relpath = self.hashed_file_path("cached/import.css")
  141. self.assertEqual(relpath, "cached/import.f53576679e5a.css")
  142. with storage.staticfiles_storage.open(relpath) as relfile:
  143. self.assertIn(b"""import url("styles.5e0040571e1a.css")""", relfile.read())
  144. self.assertPostCondition()
  145. def test_template_tag_deep_relative(self):
  146. relpath = self.hashed_file_path("cached/css/window.css")
  147. self.assertEqual(relpath, "cached/css/window.5d5c10836967.css")
  148. with storage.staticfiles_storage.open(relpath) as relfile:
  149. content = relfile.read()
  150. self.assertNotIn(b"url(img/window.png)", content)
  151. self.assertIn(b'url("img/window.acae32e4532b.png")', content)
  152. self.assertPostCondition()
  153. def test_template_tag_url(self):
  154. relpath = self.hashed_file_path("cached/url.css")
  155. self.assertEqual(relpath, "cached/url.902310b73412.css")
  156. with storage.staticfiles_storage.open(relpath) as relfile:
  157. self.assertIn(b"https://", relfile.read())
  158. self.assertPostCondition()
  159. @override_settings(
  160. STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "loop")],
  161. STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"],
  162. )
  163. def test_import_loop(self):
  164. finders.get_finder.cache_clear()
  165. err = StringIO()
  166. with self.assertRaisesMessage(RuntimeError, "Max post-process passes exceeded"):
  167. call_command("collectstatic", interactive=False, verbosity=0, stderr=err)
  168. self.assertEqual("Post-processing 'All' failed!\n\n", err.getvalue())
  169. self.assertPostCondition()
  170. def test_post_processing(self):
  171. """
  172. post_processing behaves correctly.
  173. Files that are alterable should always be post-processed; files that
  174. aren't should be skipped.
  175. collectstatic has already been called once in setUp() for this testcase,
  176. therefore we check by verifying behavior on a second run.
  177. """
  178. collectstatic_args = {
  179. "interactive": False,
  180. "verbosity": 0,
  181. "link": False,
  182. "clear": False,
  183. "dry_run": False,
  184. "post_process": True,
  185. "use_default_ignore_patterns": True,
  186. "ignore_patterns": ["*.ignoreme"],
  187. }
  188. collectstatic_cmd = CollectstaticCommand()
  189. collectstatic_cmd.set_options(**collectstatic_args)
  190. stats = collectstatic_cmd.collect()
  191. self.assertIn(
  192. os.path.join("cached", "css", "window.css"), stats["post_processed"]
  193. )
  194. self.assertIn(
  195. os.path.join("cached", "css", "img", "window.png"), stats["unmodified"]
  196. )
  197. self.assertIn(os.path.join("test", "nonascii.css"), stats["post_processed"])
  198. # No file should be yielded twice.
  199. self.assertCountEqual(stats["post_processed"], set(stats["post_processed"]))
  200. self.assertPostCondition()
  201. def test_css_import_case_insensitive(self):
  202. relpath = self.hashed_file_path("cached/styles_insensitive.css")
  203. self.assertEqual(relpath, "cached/styles_insensitive.3fa427592a53.css")
  204. with storage.staticfiles_storage.open(relpath) as relfile:
  205. content = relfile.read()
  206. self.assertNotIn(b"cached/other.css", content)
  207. self.assertIn(b"other.d41d8cd98f00.css", content)
  208. self.assertPostCondition()
  209. def test_css_source_map(self):
  210. relpath = self.hashed_file_path("cached/source_map.css")
  211. self.assertEqual(relpath, "cached/source_map.b2fceaf426aa.css")
  212. with storage.staticfiles_storage.open(relpath) as relfile:
  213. content = relfile.read()
  214. self.assertNotIn(b"/*# sourceMappingURL=source_map.css.map*/", content)
  215. self.assertIn(
  216. b"/*# sourceMappingURL=source_map.css.99914b932bd3.map */",
  217. content,
  218. )
  219. self.assertPostCondition()
  220. def test_css_source_map_tabs(self):
  221. relpath = self.hashed_file_path("cached/source_map_tabs.css")
  222. self.assertEqual(relpath, "cached/source_map_tabs.b2fceaf426aa.css")
  223. with storage.staticfiles_storage.open(relpath) as relfile:
  224. content = relfile.read()
  225. self.assertNotIn(b"/*#\tsourceMappingURL=source_map.css.map\t*/", content)
  226. self.assertIn(
  227. b"/*# sourceMappingURL=source_map.css.99914b932bd3.map */",
  228. content,
  229. )
  230. self.assertPostCondition()
  231. def test_css_source_map_sensitive(self):
  232. relpath = self.hashed_file_path("cached/source_map_sensitive.css")
  233. self.assertEqual(relpath, "cached/source_map_sensitive.456683f2106f.css")
  234. with storage.staticfiles_storage.open(relpath) as relfile:
  235. content = relfile.read()
  236. self.assertIn(b"/*# sOuRcEMaPpInGURL=source_map.css.map */", content)
  237. self.assertNotIn(
  238. b"/*# sourceMappingURL=source_map.css.99914b932bd3.map */",
  239. content,
  240. )
  241. self.assertPostCondition()
  242. def test_css_source_map_data_uri(self):
  243. relpath = self.hashed_file_path("cached/source_map_data_uri.css")
  244. self.assertEqual(relpath, "cached/source_map_data_uri.3166be10260d.css")
  245. with storage.staticfiles_storage.open(relpath) as relfile:
  246. content = relfile.read()
  247. source_map_data_uri = (
  248. b"/*# sourceMappingURL=data:application/json;charset=utf8;base64,"
  249. b"eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIl9zcmMv*/"
  250. )
  251. self.assertIn(source_map_data_uri, content)
  252. self.assertPostCondition()
  253. def test_js_source_map(self):
  254. relpath = self.hashed_file_path("cached/source_map.js")
  255. self.assertEqual(relpath, "cached/source_map.cd45b8534a87.js")
  256. with storage.staticfiles_storage.open(relpath) as relfile:
  257. content = relfile.read()
  258. self.assertNotIn(b"//# sourceMappingURL=source_map.js.map", content)
  259. self.assertIn(
  260. b"//# sourceMappingURL=source_map.js.99914b932bd3.map",
  261. content,
  262. )
  263. self.assertPostCondition()
  264. def test_js_source_map_trailing_whitespace(self):
  265. relpath = self.hashed_file_path("cached/source_map_trailing_whitespace.js")
  266. self.assertEqual(
  267. relpath, "cached/source_map_trailing_whitespace.cd45b8534a87.js"
  268. )
  269. with storage.staticfiles_storage.open(relpath) as relfile:
  270. content = relfile.read()
  271. self.assertNotIn(b"//# sourceMappingURL=source_map.js.map\t ", content)
  272. self.assertIn(
  273. b"//# sourceMappingURL=source_map.js.99914b932bd3.map",
  274. content,
  275. )
  276. self.assertPostCondition()
  277. def test_js_source_map_sensitive(self):
  278. relpath = self.hashed_file_path("cached/source_map_sensitive.js")
  279. self.assertEqual(relpath, "cached/source_map_sensitive.5da96fdd3cb3.js")
  280. with storage.staticfiles_storage.open(relpath) as relfile:
  281. content = relfile.read()
  282. self.assertIn(b"//# sOuRcEMaPpInGURL=source_map.js.map", content)
  283. self.assertNotIn(
  284. b"//# sourceMappingURL=source_map.js.99914b932bd3.map",
  285. content,
  286. )
  287. self.assertPostCondition()
  288. def test_js_source_map_data_uri(self):
  289. relpath = self.hashed_file_path("cached/source_map_data_uri.js")
  290. self.assertEqual(relpath, "cached/source_map_data_uri.a68d23cbf6dd.js")
  291. with storage.staticfiles_storage.open(relpath) as relfile:
  292. content = relfile.read()
  293. source_map_data_uri = (
  294. b"//# sourceMappingURL=data:application/json;charset=utf8;base64,"
  295. b"eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIl9zcmMv"
  296. )
  297. self.assertIn(source_map_data_uri, content)
  298. self.assertPostCondition()
  299. @override_settings(
  300. STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "faulty")],
  301. STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"],
  302. )
  303. def test_post_processing_failure(self):
  304. """
  305. post_processing indicates the origin of the error when it fails.
  306. """
  307. finders.get_finder.cache_clear()
  308. err = StringIO()
  309. with self.assertRaises(Exception):
  310. call_command("collectstatic", interactive=False, verbosity=0, stderr=err)
  311. self.assertEqual("Post-processing 'faulty.css' failed!\n\n", err.getvalue())
  312. self.assertPostCondition()
  313. @override_settings(
  314. STATICFILES_DIRS=[os.path.join(TEST_ROOT, "project", "nonutf8")],
  315. STATICFILES_FINDERS=["django.contrib.staticfiles.finders.FileSystemFinder"],
  316. )
  317. def test_post_processing_nonutf8(self):
  318. finders.get_finder.cache_clear()
  319. err = StringIO()
  320. with self.assertRaises(UnicodeDecodeError):
  321. call_command("collectstatic", interactive=False, verbosity=0, stderr=err)
  322. self.assertEqual("Post-processing 'nonutf8.css' failed!\n\n", err.getvalue())
  323. self.assertPostCondition()
  324. @override_settings(
  325. STORAGES={
  326. **settings.STORAGES,
  327. STATICFILES_STORAGE_ALIAS: {
  328. "BACKEND": "staticfiles_tests.storage.ExtraPatternsStorage",
  329. },
  330. }
  331. )
  332. class TestExtraPatternsStorage(CollectionTestCase):
  333. def setUp(self):
  334. storage.staticfiles_storage.hashed_files.clear() # avoid cache interference
  335. super().setUp()
  336. def cached_file_path(self, path):
  337. fullpath = self.render_template(self.static_template_snippet(path))
  338. return fullpath.replace(settings.STATIC_URL, "")
  339. def test_multi_extension_patterns(self):
  340. """
  341. With storage classes having several file extension patterns, only the
  342. files matching a specific file pattern should be affected by the
  343. substitution (#19670).
  344. """
  345. # CSS files shouldn't be touched by JS patterns.
  346. relpath = self.cached_file_path("cached/import.css")
  347. self.assertEqual(relpath, "cached/import.f53576679e5a.css")
  348. with storage.staticfiles_storage.open(relpath) as relfile:
  349. self.assertIn(b'import url("styles.5e0040571e1a.css")', relfile.read())
  350. # Confirm JS patterns have been applied to JS files.
  351. relpath = self.cached_file_path("cached/test.js")
  352. self.assertEqual(relpath, "cached/test.388d7a790d46.js")
  353. with storage.staticfiles_storage.open(relpath) as relfile:
  354. self.assertIn(b'JS_URL("import.f53576679e5a.css")', relfile.read())
  355. @override_settings(
  356. STORAGES={
  357. **settings.STORAGES,
  358. STATICFILES_STORAGE_ALIAS: {
  359. "BACKEND": "django.contrib.staticfiles.storage.ManifestStaticFilesStorage",
  360. },
  361. }
  362. )
  363. class TestCollectionManifestStorage(TestHashedFiles, CollectionTestCase):
  364. """
  365. Tests for the Cache busting storage
  366. """
  367. def setUp(self):
  368. super().setUp()
  369. temp_dir = tempfile.mkdtemp()
  370. os.makedirs(os.path.join(temp_dir, "test"))
  371. self._clear_filename = os.path.join(temp_dir, "test", "cleared.txt")
  372. with open(self._clear_filename, "w") as f:
  373. f.write("to be deleted in one test")
  374. self.patched_settings = self.settings(
  375. STATICFILES_DIRS=settings.STATICFILES_DIRS + [temp_dir],
  376. )
  377. self.patched_settings.enable()
  378. self.addCleanup(shutil.rmtree, temp_dir)
  379. self._manifest_strict = storage.staticfiles_storage.manifest_strict
  380. def tearDown(self):
  381. self.patched_settings.disable()
  382. if os.path.exists(self._clear_filename):
  383. os.unlink(self._clear_filename)
  384. storage.staticfiles_storage.manifest_strict = self._manifest_strict
  385. super().tearDown()
  386. def assertPostCondition(self):
  387. hashed_files = storage.staticfiles_storage.hashed_files
  388. # The in-memory version of the manifest matches the one on disk
  389. # since a properly created manifest should cover all filenames.
  390. if hashed_files:
  391. manifest, _ = storage.staticfiles_storage.load_manifest()
  392. self.assertEqual(hashed_files, manifest)
  393. def test_manifest_exists(self):
  394. filename = storage.staticfiles_storage.manifest_name
  395. path = storage.staticfiles_storage.path(filename)
  396. self.assertTrue(os.path.exists(path))
  397. def test_manifest_does_not_exist(self):
  398. storage.staticfiles_storage.manifest_name = "does.not.exist.json"
  399. self.assertIsNone(storage.staticfiles_storage.read_manifest())
  400. def test_manifest_does_not_ignore_permission_error(self):
  401. with mock.patch("builtins.open", side_effect=PermissionError):
  402. with self.assertRaises(PermissionError):
  403. storage.staticfiles_storage.read_manifest()
  404. def test_loaded_cache(self):
  405. self.assertNotEqual(storage.staticfiles_storage.hashed_files, {})
  406. manifest_content = storage.staticfiles_storage.read_manifest()
  407. self.assertIn(
  408. '"version": "%s"' % storage.staticfiles_storage.manifest_version,
  409. manifest_content,
  410. )
  411. def test_parse_cache(self):
  412. hashed_files = storage.staticfiles_storage.hashed_files
  413. manifest, _ = storage.staticfiles_storage.load_manifest()
  414. self.assertEqual(hashed_files, manifest)
  415. def test_clear_empties_manifest(self):
  416. cleared_file_name = storage.staticfiles_storage.clean_name(
  417. os.path.join("test", "cleared.txt")
  418. )
  419. # collect the additional file
  420. self.run_collectstatic()
  421. hashed_files = storage.staticfiles_storage.hashed_files
  422. self.assertIn(cleared_file_name, hashed_files)
  423. manifest_content, _ = storage.staticfiles_storage.load_manifest()
  424. self.assertIn(cleared_file_name, manifest_content)
  425. original_path = storage.staticfiles_storage.path(cleared_file_name)
  426. self.assertTrue(os.path.exists(original_path))
  427. # delete the original file form the app, collect with clear
  428. os.unlink(self._clear_filename)
  429. self.run_collectstatic(clear=True)
  430. self.assertFileNotFound(original_path)
  431. hashed_files = storage.staticfiles_storage.hashed_files
  432. self.assertNotIn(cleared_file_name, hashed_files)
  433. manifest_content, _ = storage.staticfiles_storage.load_manifest()
  434. self.assertNotIn(cleared_file_name, manifest_content)
  435. def test_missing_entry(self):
  436. missing_file_name = "cached/missing.css"
  437. configured_storage = storage.staticfiles_storage
  438. self.assertNotIn(missing_file_name, configured_storage.hashed_files)
  439. # File name not found in manifest
  440. with self.assertRaisesMessage(
  441. ValueError,
  442. "Missing staticfiles manifest entry for '%s'" % missing_file_name,
  443. ):
  444. self.hashed_file_path(missing_file_name)
  445. configured_storage.manifest_strict = False
  446. # File doesn't exist on disk
  447. err_msg = "The file '%s' could not be found with %r." % (
  448. missing_file_name,
  449. configured_storage._wrapped,
  450. )
  451. with self.assertRaisesMessage(ValueError, err_msg):
  452. self.hashed_file_path(missing_file_name)
  453. content = StringIO()
  454. content.write("Found")
  455. configured_storage.save(missing_file_name, content)
  456. # File exists on disk
  457. self.hashed_file_path(missing_file_name)
  458. def test_intermediate_files(self):
  459. cached_files = os.listdir(os.path.join(settings.STATIC_ROOT, "cached"))
  460. # Intermediate files shouldn't be created for reference.
  461. self.assertEqual(
  462. len(
  463. [
  464. cached_file
  465. for cached_file in cached_files
  466. if cached_file.startswith("relative.")
  467. ]
  468. ),
  469. 2,
  470. )
  471. def test_manifest_hash(self):
  472. # Collect the additional file.
  473. self.run_collectstatic()
  474. _, manifest_hash_orig = storage.staticfiles_storage.load_manifest()
  475. self.assertNotEqual(manifest_hash_orig, "")
  476. self.assertEqual(storage.staticfiles_storage.manifest_hash, manifest_hash_orig)
  477. # Saving doesn't change the hash.
  478. storage.staticfiles_storage.save_manifest()
  479. self.assertEqual(storage.staticfiles_storage.manifest_hash, manifest_hash_orig)
  480. # Delete the original file from the app, collect with clear.
  481. os.unlink(self._clear_filename)
  482. self.run_collectstatic(clear=True)
  483. # Hash is changed.
  484. _, manifest_hash = storage.staticfiles_storage.load_manifest()
  485. self.assertNotEqual(manifest_hash, manifest_hash_orig)
  486. def test_manifest_hash_v1(self):
  487. storage.staticfiles_storage.manifest_name = "staticfiles_v1.json"
  488. manifest_content, manifest_hash = storage.staticfiles_storage.load_manifest()
  489. self.assertEqual(manifest_hash, "")
  490. self.assertEqual(manifest_content, {"dummy.txt": "dummy.txt"})
  491. @override_settings(
  492. STORAGES={
  493. **settings.STORAGES,
  494. STATICFILES_STORAGE_ALIAS: {
  495. "BACKEND": "staticfiles_tests.storage.NoneHashStorage",
  496. },
  497. }
  498. )
  499. class TestCollectionNoneHashStorage(CollectionTestCase):
  500. hashed_file_path = hashed_file_path
  501. def test_hashed_name(self):
  502. relpath = self.hashed_file_path("cached/styles.css")
  503. self.assertEqual(relpath, "cached/styles.css")
  504. @override_settings(
  505. STORAGES={
  506. **settings.STORAGES,
  507. STATICFILES_STORAGE_ALIAS: {
  508. "BACKEND": "staticfiles_tests.storage.NoPostProcessReplacedPathStorage",
  509. },
  510. }
  511. )
  512. class TestCollectionNoPostProcessReplacedPaths(CollectionTestCase):
  513. run_collectstatic_in_setUp = False
  514. def test_collectstatistic_no_post_process_replaced_paths(self):
  515. stdout = StringIO()
  516. self.run_collectstatic(verbosity=1, stdout=stdout)
  517. self.assertIn("post-processed", stdout.getvalue())
  518. @override_settings(
  519. STORAGES={
  520. **settings.STORAGES,
  521. STATICFILES_STORAGE_ALIAS: {
  522. "BACKEND": "staticfiles_tests.storage.SimpleStorage",
  523. },
  524. }
  525. )
  526. class TestCollectionSimpleStorage(CollectionTestCase):
  527. hashed_file_path = hashed_file_path
  528. def setUp(self):
  529. storage.staticfiles_storage.hashed_files.clear() # avoid cache interference
  530. super().setUp()
  531. def test_template_tag_return(self):
  532. self.assertStaticRaises(
  533. ValueError, "does/not/exist.png", "/static/does/not/exist.png"
  534. )
  535. self.assertStaticRenders("test/file.txt", "/static/test/file.deploy12345.txt")
  536. self.assertStaticRenders(
  537. "cached/styles.css", "/static/cached/styles.deploy12345.css"
  538. )
  539. self.assertStaticRenders("path/", "/static/path/")
  540. self.assertStaticRenders("path/?query", "/static/path/?query")
  541. def test_template_tag_simple_content(self):
  542. relpath = self.hashed_file_path("cached/styles.css")
  543. self.assertEqual(relpath, "cached/styles.deploy12345.css")
  544. with storage.staticfiles_storage.open(relpath) as relfile:
  545. content = relfile.read()
  546. self.assertNotIn(b"cached/other.css", content)
  547. self.assertIn(b"other.deploy12345.css", content)
  548. class JSModuleImportAggregationManifestStorage(storage.ManifestStaticFilesStorage):
  549. support_js_module_import_aggregation = True
  550. @override_settings(
  551. STORAGES={
  552. **settings.STORAGES,
  553. STATICFILES_STORAGE_ALIAS: {
  554. "BACKEND": (
  555. "staticfiles_tests.test_storage."
  556. "JSModuleImportAggregationManifestStorage"
  557. ),
  558. },
  559. }
  560. )
  561. class TestCollectionJSModuleImportAggregationManifestStorage(CollectionTestCase):
  562. hashed_file_path = hashed_file_path
  563. def test_module_import(self):
  564. relpath = self.hashed_file_path("cached/module.js")
  565. self.assertEqual(relpath, "cached/module.55fd6938fbc5.js")
  566. tests = [
  567. # Relative imports.
  568. b'import testConst from "./module_test.477bbebe77f0.js";',
  569. b'import relativeModule from "../nested/js/nested.866475c46bb4.js";',
  570. b'import { firstConst, secondConst } from "./module_test.477bbebe77f0.js";',
  571. # Absolute import.
  572. b'import rootConst from "/static/absolute_root.5586327fe78c.js";',
  573. # Dynamic import.
  574. b'const dynamicModule = import("./module_test.477bbebe77f0.js");',
  575. # Creating a module object.
  576. b'import * as NewModule from "./module_test.477bbebe77f0.js";',
  577. # Aliases.
  578. b'import { testConst as alias } from "./module_test.477bbebe77f0.js";',
  579. b"import {\n"
  580. b" firstVar1 as firstVarAlias,\n"
  581. b" $second_var_2 as secondVarAlias\n"
  582. b'} from "./module_test.477bbebe77f0.js";',
  583. ]
  584. with storage.staticfiles_storage.open(relpath) as relfile:
  585. content = relfile.read()
  586. for module_import in tests:
  587. with self.subTest(module_import=module_import):
  588. self.assertIn(module_import, content)
  589. def test_aggregating_modules(self):
  590. relpath = self.hashed_file_path("cached/module.js")
  591. self.assertEqual(relpath, "cached/module.55fd6938fbc5.js")
  592. tests = [
  593. b'export * from "./module_test.477bbebe77f0.js";',
  594. b'export { testConst } from "./module_test.477bbebe77f0.js";',
  595. b"export {\n"
  596. b" firstVar as firstVarAlias,\n"
  597. b" secondVar as secondVarAlias\n"
  598. b'} from "./module_test.477bbebe77f0.js";',
  599. ]
  600. with storage.staticfiles_storage.open(relpath) as relfile:
  601. content = relfile.read()
  602. for module_import in tests:
  603. with self.subTest(module_import=module_import):
  604. self.assertIn(module_import, content)
  605. class CustomManifestStorage(storage.ManifestStaticFilesStorage):
  606. def __init__(self, *args, manifest_storage=None, **kwargs):
  607. manifest_storage = storage.StaticFilesStorage(
  608. location=kwargs.pop("manifest_location"),
  609. )
  610. super().__init__(*args, manifest_storage=manifest_storage, **kwargs)
  611. class TestCustomManifestStorage(SimpleTestCase):
  612. def setUp(self):
  613. self.manifest_path = Path(tempfile.mkdtemp())
  614. self.addCleanup(shutil.rmtree, self.manifest_path)
  615. self.staticfiles_storage = CustomManifestStorage(
  616. manifest_location=self.manifest_path,
  617. )
  618. self.manifest_file = self.manifest_path / self.staticfiles_storage.manifest_name
  619. # Manifest without paths.
  620. self.manifest = {"version": self.staticfiles_storage.manifest_version}
  621. with self.manifest_file.open("w") as manifest_file:
  622. json.dump(self.manifest, manifest_file)
  623. def test_read_manifest(self):
  624. self.assertEqual(
  625. self.staticfiles_storage.read_manifest(),
  626. json.dumps(self.manifest),
  627. )
  628. def test_read_manifest_nonexistent(self):
  629. os.remove(self.manifest_file)
  630. self.assertIsNone(self.staticfiles_storage.read_manifest())
  631. def test_save_manifest_override(self):
  632. self.assertIs(self.manifest_file.exists(), True)
  633. self.staticfiles_storage.save_manifest()
  634. self.assertIs(self.manifest_file.exists(), True)
  635. new_manifest = json.loads(self.staticfiles_storage.read_manifest())
  636. self.assertIn("paths", new_manifest)
  637. self.assertNotEqual(new_manifest, self.manifest)
  638. def test_save_manifest_create(self):
  639. os.remove(self.manifest_file)
  640. self.staticfiles_storage.save_manifest()
  641. self.assertIs(self.manifest_file.exists(), True)
  642. new_manifest = json.loads(self.staticfiles_storage.read_manifest())
  643. self.assertIn("paths", new_manifest)
  644. self.assertNotEqual(new_manifest, self.manifest)
  645. class CustomStaticFilesStorage(storage.StaticFilesStorage):
  646. """
  647. Used in TestStaticFilePermissions
  648. """
  649. def __init__(self, *args, **kwargs):
  650. kwargs["file_permissions_mode"] = 0o640
  651. kwargs["directory_permissions_mode"] = 0o740
  652. super().__init__(*args, **kwargs)
  653. @unittest.skipIf(sys.platform == "win32", "Windows only partially supports chmod.")
  654. class TestStaticFilePermissions(CollectionTestCase):
  655. command_params = {
  656. "interactive": False,
  657. "verbosity": 0,
  658. "ignore_patterns": ["*.ignoreme"],
  659. }
  660. def setUp(self):
  661. self.umask = 0o027
  662. self.old_umask = os.umask(self.umask)
  663. super().setUp()
  664. def tearDown(self):
  665. os.umask(self.old_umask)
  666. super().tearDown()
  667. # Don't run collectstatic command in this test class.
  668. def run_collectstatic(self, **kwargs):
  669. pass
  670. @override_settings(
  671. FILE_UPLOAD_PERMISSIONS=0o655,
  672. FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765,
  673. )
  674. def test_collect_static_files_permissions(self):
  675. call_command("collectstatic", **self.command_params)
  676. static_root = Path(settings.STATIC_ROOT)
  677. test_file = static_root / "test.txt"
  678. file_mode = test_file.stat().st_mode & 0o777
  679. self.assertEqual(file_mode, 0o655)
  680. tests = [
  681. static_root / "subdir",
  682. static_root / "nested",
  683. static_root / "nested" / "css",
  684. ]
  685. for directory in tests:
  686. with self.subTest(directory=directory):
  687. dir_mode = directory.stat().st_mode & 0o777
  688. self.assertEqual(dir_mode, 0o765)
  689. @override_settings(
  690. FILE_UPLOAD_PERMISSIONS=None,
  691. FILE_UPLOAD_DIRECTORY_PERMISSIONS=None,
  692. )
  693. def test_collect_static_files_default_permissions(self):
  694. call_command("collectstatic", **self.command_params)
  695. static_root = Path(settings.STATIC_ROOT)
  696. test_file = static_root / "test.txt"
  697. file_mode = test_file.stat().st_mode & 0o777
  698. self.assertEqual(file_mode, 0o666 & ~self.umask)
  699. tests = [
  700. static_root / "subdir",
  701. static_root / "nested",
  702. static_root / "nested" / "css",
  703. ]
  704. for directory in tests:
  705. with self.subTest(directory=directory):
  706. dir_mode = directory.stat().st_mode & 0o777
  707. self.assertEqual(dir_mode, 0o777 & ~self.umask)
  708. @override_settings(
  709. FILE_UPLOAD_PERMISSIONS=0o655,
  710. FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765,
  711. STORAGES={
  712. **settings.STORAGES,
  713. STATICFILES_STORAGE_ALIAS: {
  714. "BACKEND": "staticfiles_tests.test_storage.CustomStaticFilesStorage",
  715. },
  716. },
  717. )
  718. def test_collect_static_files_subclass_of_static_storage(self):
  719. call_command("collectstatic", **self.command_params)
  720. static_root = Path(settings.STATIC_ROOT)
  721. test_file = static_root / "test.txt"
  722. file_mode = test_file.stat().st_mode & 0o777
  723. self.assertEqual(file_mode, 0o640)
  724. tests = [
  725. static_root / "subdir",
  726. static_root / "nested",
  727. static_root / "nested" / "css",
  728. ]
  729. for directory in tests:
  730. with self.subTest(directory=directory):
  731. dir_mode = directory.stat().st_mode & 0o777
  732. self.assertEqual(dir_mode, 0o740)
  733. @override_settings(
  734. STORAGES={
  735. **settings.STORAGES,
  736. STATICFILES_STORAGE_ALIAS: {
  737. "BACKEND": "django.contrib.staticfiles.storage.ManifestStaticFilesStorage",
  738. },
  739. }
  740. )
  741. class TestCollectionHashedFilesCache(CollectionTestCase):
  742. """
  743. Files referenced from CSS use the correct final hashed name regardless of
  744. the order in which the files are post-processed.
  745. """
  746. hashed_file_path = hashed_file_path
  747. def setUp(self):
  748. super().setUp()
  749. self._temp_dir = temp_dir = tempfile.mkdtemp()
  750. os.makedirs(os.path.join(temp_dir, "test"))
  751. self.addCleanup(shutil.rmtree, temp_dir)
  752. def _get_filename_path(self, filename):
  753. return os.path.join(self._temp_dir, "test", filename)
  754. def test_file_change_after_collectstatic(self):
  755. # Create initial static files.
  756. file_contents = (
  757. ("foo.png", "foo"),
  758. ("bar.css", 'url("foo.png")\nurl("xyz.png")'),
  759. ("xyz.png", "xyz"),
  760. )
  761. for filename, content in file_contents:
  762. with open(self._get_filename_path(filename), "w") as f:
  763. f.write(content)
  764. with self.modify_settings(STATICFILES_DIRS={"append": self._temp_dir}):
  765. finders.get_finder.cache_clear()
  766. err = StringIO()
  767. # First collectstatic run.
  768. call_command("collectstatic", interactive=False, verbosity=0, stderr=err)
  769. relpath = self.hashed_file_path("test/bar.css")
  770. with storage.staticfiles_storage.open(relpath) as relfile:
  771. content = relfile.read()
  772. self.assertIn(b"foo.acbd18db4cc2.png", content)
  773. self.assertIn(b"xyz.d16fb36f0911.png", content)
  774. # Change the contents of the png files.
  775. for filename in ("foo.png", "xyz.png"):
  776. with open(self._get_filename_path(filename), "w+b") as f:
  777. f.write(b"new content of file to change its hash")
  778. # The hashes of the png files in the CSS file are updated after
  779. # a second collectstatic.
  780. call_command("collectstatic", interactive=False, verbosity=0, stderr=err)
  781. relpath = self.hashed_file_path("test/bar.css")
  782. with storage.staticfiles_storage.open(relpath) as relfile:
  783. content = relfile.read()
  784. self.assertIn(b"foo.57a5cb9ba68d.png", content)
  785. self.assertIn(b"xyz.57a5cb9ba68d.png", content)